Show form errors - php

I would like to show error messages in the top of my registration form. I created my registration form:
<div class="example-wrapper">
<h1>Register</h1>
{{ form_start(form) }}
{{ form_row(form.email) }}
{{ form_row(form.plainPassword.first) }}
{{ form_row(form.plainPassword.second) }}
{{ form_row(form.firstname) }}
{{ form_row(form.lastname) }}
{{ form_row(form.termsAccepted) }}
<button type="submit">Register!</button>
{{ form_end(form) }}
</div>
And on my UserType class, I added all necessaries input:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
'constraints' => [
new NotBlank([
'message' => 'Enter a valid password.'
]),
new Length([
'min' => 8,
'minMessage' => 'Password must be at least 8 characters.'
])
]
))
->add('firstname', TextType::class)
->add('lastname', TextType::class)
->add('termsAccepted', CheckboxType::class, array(
'mapped' => false,
'constraints' => new IsTrue(),
))
;
}}
Every time I get an error message, correctly displayed, I found it under the concerned input and not in the top of my registration form.
I added this on my form but don't help:
{{ form_errors(form) }}
Any suggestion?

Did you set error_bubbling => true?
Documentation: https://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling

Related

How can I separate RepeatedType widget in the view?

I am working on a ResetPassword system and this is the page where the user writes his new password after he gets an email.
Basically what I want to do is to separate the RepeatedType in the view page!
In the view(.twig) I have :
{{ form_start(resetForm) }}
{{ form_widget(resetForm.plainPassword) }}
<button>Reset password</button>
{{ form_end(resetForm) }}
Instead of
{{ form_widget(resetForm.plainPassword) }}
I want to separate them and make something like :
{{ form_widget(resetForm.plainPassword[1]) }}
{{ form_widget(resetForm.plainPassword[2]) }}
Is that possible? If yes what is the proper syntax to do it?
Here is the code of the ChangePasswordFormType.php :
class ChangePasswordFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
'attr' => [
'class' => 'form-control form-control-sm',
],
'constraints' => [
new NotBlank([
'message' => 'Please enter a password',
]),
new Length([
'min' => 6,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
],
'label' => 'New password :',
],
'second_options' => [
'attr' => [
'class' => 'form-control',
],
'label' => 'Repeat it :',
],
'invalid_message' => 'The password fields must match.',
// Instead of being set onto the object directly,
// this is read and encoded in the controller
'mapped' => false,
])
;
}
https://symfony.com/doc/current/reference/forms/types/repeated.html#rendering
{# .first and .second may vary in your use - see the note below #}
{{ form_row(form.password.first) }}
{{ form_row(form.password.second) }}

How to remove specific entities from a checkbox type in Symfony?

I have a form in which I want to have checkboxes to add or remove elements from a collection: a User which have Responsability[].
I want to show some of the existing Responsability in the form but not all of them. I use an attribute called automatic to determine if I want to display them or not.
How can I edit my form to do such a thing?
UserType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class, [
'label' => 'Nom d\'utilisateurice'
])
->add('responsibilities', EntityType::class, [
// looks for choices from this entity
'class' => Responsibility::class,
// uses the Responsibility.label property as the visible option string
'choice_label' => 'label',
'label' => 'RĂ´les',
'multiple' => true,
'expanded' => true,
'choice_attr' => function($responsibility)
{
return [
'data-responsibility-description' => $responsibility->getDescription(),
];
},
])
->add('submit',SubmitType::class, [
'label' => 'Changer les informations',
'attr' => [
'class' => 'btn btn-outline-primary float-right'
]
]);
}
edit.html.twig:
{{ form_start(edit_form, {'attr': {'id': 'form-edit-user'}}) }}
<div class="form-group">
{{ form_label(edit_form.username) }}
{{ form_widget(edit_form.username) }}
</div>
<div class="form-group">
{{ form_label(edit_form.responsibilities) }}
{% for responsibility in edit_form.responsibilities %}
<div class="form-group">
{{ form_widget(responsibility) }}
{{ form_label(responsibility) }}
<span class="text-muted responsibility-description">
{{ responsibility.vars.attr['data-responsibility-description'] }}
</span>
</div>
{% endfor %}
</div>
{{ form_widget(edit_form) }}
{{ form_end(edit_form) }}
You can use query_builder form option as documented here.
Something like this should work:
'query_builder' => function (EntityRepository $repository) {
return $repository
->createQueryBuilder('o')
->where('o.automatic = FALSE');
}
Or like this if you prefer having a parameter:
'query_builder' => function (EntityRepository $repository) {
return $repository
->createQueryBuilder('o')
->where('o.automatic = :automatic')
->setParameter('automatic', false);
}

Symfony 2 multiple upload

using symfony 2.5 and Php 5.3.13.
i just want to add a field file type with option multiple => true.
It works ! but when the user click a second time on the button [Upload] it's deleting the first one already uploaded..
How can i do something like that : https://jsfiddle.net/gxfwvtqe/
In a symfony way, AdvertType.php :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
->add('content', 'textarea')
->add('category', 'choice', array(
'choices' => array(
'incident' => 'Incident',
'general' => 'General',
),
'multiple' => false,
'expanded' => true,
'required' => true,))
->add('documents','file', array(
'required' => false,
'data_class'=> null,
'multiple' => true))
->add('save', 'submit')
;
}
form.html.twig :
<div class="well">
{{ form_start(form, {'attr': {'class': ''}}) }}
{{ form_errors(form) }}
{{ form_row(form.documents) }}
{{ form_widget(form.save, {'attr': {'class': 'btn btn-primary'}}) }}
{{ form_rest(form) }}
{{ form_end(form) }}

Symfony Form filtered drop down choice

I have for with drop down entity Customer by field name, my question how to change form for filter by name. Example in my drop down many customer, and I write "a" and in drop down remained only who have first letter in name "a"
$builder
->add('customer', 'entity', array(
'class' => Customer::class,
'attr' => array('class' => 'form-control select2 all_customers'),
'property' => 'name',
'empty_value' => 'Choice Customer',
'query_builder' => function ($repository) {
/** #var CustomerRepository $repository */
return $repository->getAllQuery();
},
'required' => false
))
this my template what need to do which create text field for filter
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_label(form.customer, label|default(null), {'label_attr': {'class': 'control-label'}}) }}
{{ form_widget(form.customer, {'attr': {'class': 'select2', 'type': 'text'}}) }}
{{ form_end(form) }}

Invalid message not assoiciated to field

I am in need to displaying an error when two passwords fields are mismatching. I am trying to achieve this through setting invalid_message in my repeated password field, But when I try to call the error as {{form_errors(form.password)}} the error does not appear. However if I use {{form_errors(form)}} the the password mismatch error appears. I need to make the error field specific and would greatly value your input on this :)
I tried many online searches but none helped. Following is my implementation,
the twig
{{ form_start(form, {'attr': {'class': 'form-horizontal', 'role': 'form', 'novalidate': 'novalidate'}}) }}
<!--just placed the error here for debug purposes-->
{{ form_errors(form) }}
<div class="form-group {% if form.email.vars.errors|length > 0 %}has-error{% endif %} {% if form.email.vars.required == 'true' %}required{% endif %}">
{{ form_label(form.email) }}
<div class="col-sm-8">
{{ form_widget(form.email) }}
<span class="help-block">{{ form_errors(form.email) }}</span>
</div>
</div>
<div class="form-group {% if form.password.vars.errors|length > 0 %}has-error{% endif %} {% if form.password.vars.required == 'true' %}required{% endif %}">
{{ form_label(form.password.first) }}
<div class="col-sm-8">
{{ form_widget(form.password.first) }}
</div>
</div>
<div class="form-group required">
{{ form_label(form.password.second) }}
<div class="col-sm-8">
{{ form_widget(form.password.second) }}
</div>
</div>
<div class="form-group">
<div class="center-block btn-sign-in">
{{ form_widget(form.submit) }}
</div>
</div>
<span class="form-footer-msg">Already have an account? Sign In</span>
{{ form_end(form) }}
the form
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('email', 'email', array('label'=>'Email',
'attr'=>array('class'=>'form-control'),
'required'=>true,
'trim' => true,
'data'=>'user1#test.com',
'label_attr'=>array('class'=>'col-sm-3 control-label')));
$builder->add( 'password', 'repeated', array( 'type' => 'password',
//here is the password mismatch error message
'invalid_message' => ErrorMessages::PASSWORDS_DONOT_MATCH,
'options' => array('attr' => array('class' => 'password-field form-control')),
'error_bubbling' => true,
'required' => true,
'trim' => true,
'first_options' => array('label' => 'Password',
'error_bubbling' => true,
'label_attr'=>array('class'=>'col-sm-3 control-label')),
'second_options' => array('label' => 'Confirm password',
'error_bubbling' => true,
'label_attr'=>array('class'=>'col-sm-3 control-label'))));
$builder->add('submit', 'submit', array('label'=>'Create Account',
'attr'=>array('class'=>'btn btn-primary')))
->setMethod('POST')
->getForm();
}
public function getName() {
return 'signup';
}
the controller
public function indexAction() {
$signUp = new User();
$form = $this->createForm(new SignUpForm(), $signUp,
array('action'=>$this->generateUrl('accounts_signup')));
$request = $this->get('request');
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isValid()) {
$request = $this->get("request");
//do something
}else{
//do something else
}
}
return $this->render('AccountsBundle:Signup:index.html.twig',
array('form'=>$form->createView()));
}
Your input on this matter is greatly appreciated sirs :) thank you very much :)
The error bubbling is not needed. Here is a working example:
$builder->add('password', 'repeated', array(
'type' => 'password',
'label' => 'Zayso Password',
'required' => true,
'attr' => array('size' => 20),
'invalid_message' => 'The password fields must match.',
'constraints' => new NotBlankConstraint($constraintOptions),
'first_options' => array('label' => 'Zayso Password'),
'second_options' => array('label' => 'Zayso Password(confirm)'),
'first_name' => 'pass1',
'second_name' => 'pass2',
));
# twig
{{ form_row(form.password.pass1) }}
{{ form_row(form.password.pass2) }}

Categories