I have an edit form I need verified with several datetime inputs.
Here is an example of one of the inputs. Can old() be used this way?
<input
type="text"
name="call_timeRecd"
id="call_timeRecd"
class="form-control
form-control-sm"
value="{{ $data->call_timeRecd ? date('Y-m-d H:i', (new DateTime( old($data->call_timeRecd, $data->call_timeRecd) ))->getTimestamp()) : '' }}" />
I'm trying to have invalid inputs return to the form with an error and the invalid input displayed in the input box. However, it is showing the original input rather than the incorrect version when it returns with the error.
$data is a MySql record and call_timeRecd is a timestamp field.
Related
I am building a form with Yup, React Hook Form and, MUI V5. I am using a DateTimePicker from MUI V5 but it is not displaying Yup's error messages as expected.
Ideally, the errors should display as follow:
Invalid format message: Invalid date format. (mm/dd/yyyy hh:mm am or
pm)
Required field's message: The field cannot be left blank.
Additionally, when there is a validation error or when the field
loses its focus it does not turn red.
So, if the field is empty and I press the submit button, the invalid format message is displayed.
here is the schemas code:
const schema = yup.object().shape({
name: yup
.string()
.required("Please enter your name. The field cannot be left blank."),
date: yup
.date()
.transform(parseDateString)
.typeError("Invalid date format. (mm/dd/yyyy hh:mm am or pm)")
.nullable()
.required("Please enter a valid date. The field cannot be left blank.")
});
I have tried moving nullable() to every different position and the result still the same.
I have commented nullable() and typeError and I get the default error from date (date must be a date type, but the final value was: Invalid Date.)
Here is a working example
The Invalid Date error comes from the date-fns parser function that is in the parseDateString function called in the Yup transform method.
Yup transform method is used to transform incoming date from the input field, in this case it's MUI's DateTimePicker.
That being sad it has nothing to do with this error and the problem is in the DatePicker component. Make note of the TextField and {...params} destructuring. Since the error prop was before we destructure params it was overwritten.
Here is a working example.
const CalPicker = ({ helperText, name, label, control, required, error }) => {
const [value, setValue] = React.useState();
return (
<Stack sx={{ mt: 2 }}>
<LocalizationProvider dateAdapter={DateAdapter}>
<Controller
name={name}
control={control}
render={({ field }) => (
<DateTimePicker
{...field}
renderInput={(params) => (
<TextField
required={required}
{...params}
helperText={helperText}
error={error}
/>
)}
label={label}
value={value}
onChange={(newValue) => {
field.onChange(newValue);
setValue(newValue);
}}
/>
)}
/>
</LocalizationProvider>
</Stack>
);
};
add under LocalizationProvider:
{error ? <div className="error">{error}</div> : null}
I am running laravel backpack 3.4 and created a custom select2 fieldtype from the standard one, I am now trying to based on an onchange event change the value selected on another select options but no change is happening
This is the field declararion
<select onchange="updateunit(this, '{{$field['name']}}' )" id="{{$field['name']}}_<% $index %>" data-index="<% $index %>"
ng-model="item.{{ $field['name'] }}"
[ngValue]="value"
#include('crud::inc.field_attributes', ['default_class' => 'form-control select2'])
>
<option value="">-</option>
#if (isset($field['model']))
#foreach ($field['model']::all() as $connected_entity_entry)
<option value="{{ $connected_entity_entry->getKey() }}"
>{{ $connected_entity_entry->{$field['attribute']} }}</option>
#endforeach
#endif
</select>
And this is the way I am trying to modify the select field selected option
function updateunit(object,name){
var fieldname;
fieldname = object.id;
fieldname = fieldname.replace('product_id','order_unit');
/* data:'_token = <?php echo csrf_token() ?>', */
$.ajax({
type:'POST',
url:'/getmsg',
data: {id:object.value},
async: false,
success:function(data) {
alert(fieldname);
alert(data.msg);
document.getElementById(fieldname).value = data.msg;
},
error:function(){alert('Unidade de Compra não está definida')},
});
This is not working, but I have not enough knowledge either on JS neither Angular to understand why this won't bind.
The elements that are created by your field configurations use the jquery select2 plugin to create a fancy select box. It does this by hiding the plain select element then displaying an html structure that builds the fancy dropdown etc in its place.
document.getElementById(fieldname).value = data.msg; will set the value of the hidden select field, but will not update the value shown by the plugin's fancy html dropdown.
To make the value that's display by the plugin change, we have to call .trigger('change') so the select element tells any listening javascript (ie the select2 plugin) that it's internal value has changed and the plugin should now update its display to match. ie, run this:
$('#'+fieldname).val(data.msg).trigger('change')
See more detailed documentation here
Say I have checkboxes. Each with a value that goes into the array when checked.
<input type="checkbox" id="card_type1" name="card_type[]" value="easy" #if(old('card_type') != NULL && in_array('easy', old('card_type')) || old('foo', $parkingLot->m_plots_can_easycard) === '1') checked #endif>
<input type="checkbox" id="card_type2" name="card_type[]" value="icash" #if(old('card_type') != NULL && in_array('icash', old('card_type')) || old('foo', $parkingLot->m_plots_can_icash20) === '1') checked #endif>
<input type="checkbox" id="card_type3" name="card_type[]" value="ipass" #if(old('card_type') != NULL && in_array('ipass', old('card_type')) || old('foo', $parkingLot->m_plots_can_ipass) === '1') checked #endif>
Upon loading my form first time, I want to reflect the database value. If a value in the DB is '1', check the checkbox. I then modify the checkboxes - checking some and unchecking some - and submit the form and say the form submission fails. I then want to reflect the old values by checking whether each value is in the old checkbox array, checking the checkboxes if so.
My problem is that old('value', 'default') consists of both 'value' and 'default' and I can't really use separate methods to determine whether the checkbox should be checked. And if I do (as in above), then I can't just have old('default') - and do a separate check there - because having one parameter makes it old('value').
I'm not sure how to go about it in my situation. Any pointers or help would be much appreciated. I hope I illustrated clear enough what my situation is.
You may try the following
<input type="checkbox" id="card_type1" name="card_type[]" value="easy"
#if (in_array('easy', old('card_type', [$parkingLot->m_plots_can_easycard === '1' ? 'easy' : ''])))
checked
#endif>
<input type="checkbox" id="card_type2" name="card_type[]" value="icash"
#if (in_array('icash', old('card_type', [$parkingLot->m_plots_can_icash20 === '1' ? 'icash' : ''])))
checked
#endif>
<input type="checkbox" id="card_type3" name="card_type[]" value="ipass"
#if (in_array('ipass', old('card_type', [$parkingLot->m_plots_can_ipass === '1' ? 'ipass' : ''])))
checked
#endif>
I am stuck here and would very much appreciate help. I have a form in a razor view with a input field for current city which looks like this:
#Html.LabelFor(x => x.UserModel.CurrentCity)
#Html.TextBoxFor(x => x.UserModel.CurrentCity, new { #data_bind = "value: UserModel.CurrentCity ", #class = "city", #data_val = "true", #data_val_required="City is required" })
#Html.ValidationMessageFor(x => x.UserModel.CurrentCity)
I want autocomplete for this field and am using jquery token input plugin for this like:
$(".city").tokenInput('#Url.Action("AutocompleteCity", "Settings")',{ minChars: 2, tokenLimit: 1, hintText: "Type in a city" });
$(".city").tokenInput("add", {name: viewModel.UserModel.CurrentCity()});
Everything works fine except the clientside unobtrusive validation. The form gets posted even if CurrentCity is empty.
I also tried to change the MVC helpers to plain html:
<input data-val="true" data-val-required="City is required" type="text" class="city" data-bind = "value: UserModel.CurrentCity, attr: { name: 'UserModel.CurrentCity', id: 'UserModel.CurrentCity'}" />
<span class="field-validation-valid" data-valmsg-for="UserModel.CurrentCity" data-valmsg-replace="true"></span>
This approach prevents the form from being submitted but the validation-error class is not injected into the span and the error message does not show up.
Any suggestions?
The original input element you created is hidden. You will likely need to enable validation of hidden elements: jquery.validate v. 1.9 ignores some hidden inputs or https://stackoverflow.com/a/13295938/173225.
Imagine this scenario: in our company there is an employee that "play" around graphic,css,html and so on.
Our new project will born under symfony2 so we're trying some silly - but "real" - stuff (like authentication from db, submit data from a form and persist it to db and so on..)
The problem
As far i know, learnt from symfony2 "book" that i found on the site (you can find it here), there is an "automated" way for creating and rendering forms:
1) Build the form up into a controller in this way
$form = $this->createFormBuilder($task)
->add('task','text'),
->add('dueDate','date'),
->getForm();
return $this->render('pathToBundle:Controller:templateTwig',
array('form'=>$form->createview());
2) Into templateTwig render the template
{{ form_widget(form) }} // or single rows method
3) Into a controller (the same that have a route where you can submit data), take back submitted information
if($rquest->getMethod()=='POST'){
$form->bindRequest($request);
/* and so on */
}
Return to scenario
Our graphic employee don't want to access controllers, write php and other stuff like those. So he'll write a twig template with a "unconventional" (from symfony2 point of view, but conventional from HTML point of view) method:
/* into twig template */
<form action="{{ path('SestanteUserBundle_homepage') }}" method="post" name="userForm">
<div>
USERNAME: <input type="text" name="user_name" value="{{ user.username}}"/>
</div>
<div>
EMAIL: <input type="text" name="user_mail" value="{{ user.email }}"/>
</div>
<input type="hidden" name="user_id" value="{{ id }}" />
<input type="submit" value="modifica i dati">
</form>
Now, if into the controller that handle the submission of data we do something like that
public function indexAction(Request $request)
{
if($request->getMethod() == 'POST'){ // sono arrivato per via di un submit, quindi devo modificare i dati prima di farli vedere a video
$defaultData = array('message'=>'ho visto questa cosa in esempio, ma non capisco se posso farne a meno');
$form = $this->createFormBuilder($defaultData)
->add('user_name','text')
->add('user_mail','email')
->add('user_id','integer')
->getForm();
$form->bindRequest($request); //bindo la form ad una request
$data = $form->getData(); //mi aspetto un'array chiave=>valore
/* .... */
We expected that $data will contain an array with key,value from the submitted form.
We found that it isn't true. After googling for a while and try with other "bad" ideas, we're frozen into that.
So, if you have a "graphic office" that can't handle directly php code, how can we interface from form(s) to controller(s) ?
UPDATE
It seems that Symfony2 use a different convention for form's field name and lookup once you've submitted that.
In particular, if my form's name is addUser and a field is named userName, the field's name will be AddUser[username] so maybe it have a "dynamic" lookup method that will extract form's name, field's name, concat them and lookup for values.
Is it possible?
You can force Symfony2 to set the name of a form field, though I don't suggest it: $formBuilder->add('dummyfield', 'text', array( 'attr' => array('name' => 'yournamehere') ) );
Alternatively (also a bad idea), you can do this, which won't even let you use the form API: $this->getRequest()->get('whatever_the_field_name_is');
OR you can hackily add elements to the request based on the Sf2 generated names before binding it (copying the values that exist).
OR you can make use of the bind method of the form component (instead of bindRequest) as documented here.
But seriously...just use the formbuilder api. Your life will be easier, and isn't that what a framework is for? :)
Symfony 2 is based on twig as templating language. Let him use it :
{{ form_label(form.field) }}
will generate something like this :
<label for="field">field</label>
You can use all the available functions in order to render the form :
{{ form_label() }}
{{ form_widget() }}
{{ form_errors() }}
If you want to customize what is rendered by those functions, you can override twig templates as defined in the Symfony2 documentation.
Otherwise if you really want to something ugly, you can go for this kind of syntax :
{{ myform.vars.value.myField }}