Laravel form with placeholder, class and input::old - forms

I am trying to get used to work with Laravel's blade.
I would like to create a text input called company.
The input field needs to have an id and a class.
I also want to show a placeholder if there is no data in the database, or the data stored if already exists.
Finally, I would like to keep the introduced input in case of errors.
I would like to use something similar at this:
{{ Form::text(
'company',
isset($user->company)?$user->company:array('placeholder'=>'Your company'),
array('class' => 'field required', 'id' => 'company'),
Input::old('company')
) }}
Any help would be appreciated. Thanks!

The easy way, using form model binding:
{{ Form::model($user, [ ...options...]) }}
{{ Form::text(
'company', // refers to $user->company
null, // auto populated with old input in case of error OR $user->company
array('class' => 'field required', 'id' => 'company',
'placeholder' => 'Your company') // placeholder is html attribute, don't use model data here
) }}
And if you don't want form model binding, this is all you need:
{{ Form::text(
'company',
$user->company, // auto populated with old input in case of error
array('class' => 'field required', 'id' => 'company',
'placeholder' => 'Your company')
) }}

Laravel will handle re-populating inputs for you, so long as the key in the POST data is the same as your input’s name attribute.
With Form::text(), the first parameter is the field name, the second parameter is the default value you want, and the third parameter is an array of HTML attributes you want set. So, you would have:
{{ Form::text('company', null, array(
'class' => '',
'id' => '',
'placeholder' => '',
)) }}
Obviously replaced the class, id, and placeholder values with your desired values.

Found it!
It works fine for me if I do this:
{{ Form::text(
'company',
Input::old( 'company', $user -> company ) ,
array( 'class' => 'field required', 'id' => 'company', 'placeholder' => 'Your company' )
) }}

Related

How to add an error to a constraint in form?

Using Symfony 3.2 on Ubuntu 16.04
I created a FormType.php with several fields. One of them is a phone number, so I added a constraint where only numbers could be accepted. Here is the code for the phone form
->add('authorPhone', NumberType::class, array('label' => 'Numéro de téléphone',
'required' => true,
'attr' => array(
'class' => 'validate',
'id' => 'icon_telephone'
),
'constraints' => array(new Regex("#^0[1-9]([-. ]?[0-9]{2}){4}$#"))
))
After that, in my controller I added an error to tell that numbers only need to be filled in
public function indexAction()
{
$form = $this->createForm(FormType::class);
$form->get('authorPhone')->addError(new FormError('error message'));
return $this->render('app/main/index.html.twig', array(
'form' => $form->createView()
));
}
But when I look at my page the error message is actually showing without having filled the field. And of course I don't want that.
(you can see under "Numéro de téléphone", which means phone number)
I only want numbers in my phone number field, and if there are letters, an error should be displayed or something saying it's not right.
Standard how to to this stuff in Symfony is to define an entity with contraints and error messages and then create entity bound form which will handle validation based on entity's contraints automatically.
But if you need, for some reason, independent form, it can be done to. The addError() method is for adding error "state" the the form field (e.g. for own validation) and you're adding the error by default right after the form is created. That's the reason why the error shows constantly.
UPDATED:
The right way to assign an error message to a form field is by the invalid_message property (which is showed when the entered value doesn't correspond with the field type). But when there's a constraint used for validation, then the err message has to be set according to the constraint validator - so, in your case, by associative array with pattern and message keys.
Next thing need to be corrected is TextType instead of NumberType, because when the NumberType is used, then it won't allow to enter dashes and also automatically trims leading zeros in numbers - so bad for phone numbers :-)
->add('authorPhone', TextType::class, array(
'label' => 'Numéro de téléphone',
'required' => true,
'attr' => array(
'class' => 'validate',
'id' => 'icon_telephone'
),
'constraints' => array(new Regex(
array(
'pattern' => '#^0[1-9]([-. ]?[0-9]{2}){4}$#',
'message' => 'Phone error message'
)
)),
))
And last thing to review - in the controller (after form declaration) has to be form submission handling routine:
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
....
You can learn more in Symfony's form submission handling: http://symfony.com/doc/current/forms.html#handling-form-submissions
Form rendering is fairly simple. Twig syntax to render whole form:
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
or, if you want to selectively render fields one by one:
{{ form_start(form) }}
{{ form_row(form.authorPhone) }}
{{ form_row(form.submit) }}
{{ form_end(form) }}
It'll renders complete field including labels and errors

Symfony2 (2.3) birthday field set default value in twig (form_widget)

i can't figure out how to set a default vaule to a birthday field in symfony.
for text field this works:
{{ form_widget(form.name, {'value' : 'Max' }) }}
is it possible to set a date default value? something like:
{{ form_widget(form.birthday, {'value' : '02.03.1980' } )}}
symfony.com/doc/current/reference/forms/types/birthday.html
thank you!
Thank you for the hint (see data field). This works with choice. I set the default date in the controller and not in the twig template.
$formAntragssteller = $this->createForm(new StandardType(), $antragssteller)
->add('geburtsdatum', 'birthday', array(
'widget' => 'choice',
'attr' => array(
'class' => 'form-control'
),
'label' => 'Geburtsdatum',
'input' => 'string',
'format' => 'dd.MM.yyyy',
'empty_value' => array('year' => 'Jahr', 'month' => 'Monat', 'day' => 'Tag'),
'data' => '1984-04-04'
));
"value" has nothing to do with the form type, but only with the internal widget template handling
you need to match the right widget via the "widget" word in the add method of the form builder
i.e. if you set ['widget' => 'single_text', 'format' => 'dd-MM-yyyy'] value is for sure in the form of '02-03-1980'
birthday field tipe - widget paragraph

Using Laravel to Add Dynamic Attributes to Form Fields

I am trying to create a dynamic value for a form attribute that is auto-populated based on a previous setting stored in the database. It works fine in HTML with a little Laravel and looks like:
<input type="text" class="class" id="firstName" placeholder="First Name" value="{{ $user->firstName }}">
But I want to fully generate the entire form in Laravel. I'm unsure how to pass the value into the array. I can't seem to get the form to pull the information. Here is how it is currently looking:
{{ Form::text('first_name', '', [
'class' => 'class',
'id' => 'firstName',
'placeholder' => 'First Name',
'value' => $user->firstName
])}}
Try this:
{{ Form::text('first_name', $user->firstName, [
'class' => 'class',
'id' => 'firstName',
'placeholder' => 'First Name'
])}}
For more information regarding this topic, visit this
See, if that works.
To specify a default value in laravel's form generator, the second value you pass in is made for you:
{{ Form::text('first_name', $user->firstName,
[
'class' => 'class',
'id' => 'firstName',
'placeholder' => 'First Name',
]
) }}
Please note that from laravel 5, being published next week, the form helpers are removed (and for the actual state the installable replacement packages don't work very well/without bugs). So if you are planning on upgrading to laravel 5 better don't use this, instead go with html form elements.

Symfony, Hidden Form Field

i have problem with hiding my form fields. For example:
->add('new_password', 'repeated', array(
'first_options' => array(
'label' => 'Nowe hasło',
'attr' => array('style'=>'display:none;')),
'second_options' => array(
'label' => 'Powtórz nowe hasło',
'attr' => array('style'=>'display:none;')),
'mapped' => false,
'required' => false,
));
Field is not visible but label is visible. I want to have hidden field but label should be hidden to. I want to show it in Jquery after clicking on the button. Any ideas guys ?
First, this is not a Hidden Field Type but a repeated type you want to hide by passing a style='display:none;' attribute.
In general, if you don't want to display a given label, you may need to customize your form rendering.
For example,
{{ form_row(yourForm.new_password) }} {# in case you're using the form_row helper #}
should be replaced by
{{form_widget(yourForm.new_password) }}
Because form_row(yourForm.yourField) is in fact a shortcut for,
{{ form_errors(yourForm.yourField) }}
{{ form_label(yourForm.yourField) }}
{{ form_widget(yourForm.yourField) }}
Also,
Why do you need to hide a repeated password field this way?
If you want to show it only when you click on a button why dont you wrap the newPassword widget in a div with display none?
But if you want to add attributes to the label you can use the option label_attr like this:
{{ form_row(form.name, {'label_attr ':{'class':'hidden'}}) }}
or
->add('new_password', 'repeated', array(
'first_options' => array(
'label' => 'Nowe hasło',
'label_attr' => array('style'=>'display:none;')),
'second_options' => array(
'label' => 'Powtórz nowe hasło',
'label_attr' => array('style'=>'display:none;')),
'mapped' => false,
'required' => false,
));

Symfony2 form repeated field - how to move 'not matching' message to confirm field?

I'm creating a sign-up type of form and within that I use a 'repeated' field type to get the user's desired password and confirm it. I add this field to my form like this:
$builder->add(
'password',
'repeated',
array(
'first_options' => array('label' => 'user.form.password.label'),
'second_options' => array('label' => 'user.form.password_confirm.label'),
'invalid_message' => 'user.password_confirm.not_matched',
'type' => 'password',
)
);
This works fine - except that when the passwords do not match the 'does not match' error message is displayed with the first field (the password field) rather than with the second, confirm, field. It seems to me that it's much more logical to have this message appear with the confirm field - but I'm struggling to find a way to achieve this?
I thought that perhaps the 'error_mapping' option was what I needed, but I've not managed to make that work and I'm not sure if that is the right direction for me to be looking in or not?
Thanks for any help,
Matt
if anyone still interested how it can be done sf2 2.7 (i dont check older versions)
->add('plainPassword', 'repeated', [
'type' => 'password',
'invalid_message' => 'user.password_repeat.not_match',
'error_mapping' => [
'.' => 'second'
]
])
So i hope it will be helpful because google search results for this task still lead to this question without proper answer
Move a confirm field to the first option:
$builder->add(
'password',
'repeated',
array(
'second_options' => array('label' => 'user.form.password.label'),
'first_options' => array('label' => 'user.form.password_confirm.label'),
'invalid_message' => 'user.password_confirm.not_matched',
'type' => 'password',
)
);
and change the fields order in the template
{{ form_row(form.password.second) }}
{{ form_row(form.password.first) }}