Symfony2 Form: Automatically adds NotBlank constraint and bootstrap validation message for required fields

When creating a form in Symfony2 with validation and custom error messages for required fields, I need to manually specify NotBlank constraints and custom error message attributes for client side validation (using Bootstrap Validator). The code looks like this for each form field:

$builder->add('name', 'text', array(
    'required' => true,
    'constraints' => array(
      new NotBlank(array('message' => 'Bitte geben Sie Ihren Namen ein.')),
    ),
    'attr' => array(
      // This is for client side bootstrap validator
      'data-bv-notempty-message' => 'Bitte geben Sie Ihren Namen ein.'
    )
));

      

What I'm looking for is the ability to make it shorter by specifying required_requirement just once:

$builder->add('name', 'text', array(
    'required_message' => 'Bitte geben Sie Ihren Namen ein.'
));

      

and I would like the builder to create a NotBlank constraint and a data-bv-notempty-message attribute.

What's the best way to achieve this? By creating a form type extension?

+3


source to share


1 answer


The solution I'm currently using is this: In the type class of my form (or in the Controller class when creating forms on the fly without the Type class), I add a private function addRequired

that I use to add the required fields:

class MyFormWithRequiredFieldsType extends AbstractType
{
    private $builder;
    private function addRequired($name, $type = null, $options = array())
    {
        $required_message = 'Bitte fΓΌllen Sie dieses Feld aus';
        if (isset($options['required_message'])) {
            $required_message = $options['required_message'];
            unset($options['required_message']);
        }
        $options['required'] = true;
        $options['attr']['data-bv-notempty-message'] = $required_message;
        if (!isset($options['constraints'])) {
            $options['constraints'] = array();
        }
        $options['constraints'][] = new NotBlank(array(
            'message' => $required_message
        ));
        $this->builder->add($name, $type, $options);
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->builder = $builder;
        $this->addRequired('name', 'text', array(
            'required_message' => 'Bitte geben Sie Ihren Namen ein'
        ));
    }
}

      



This works, but what I don't like about this solution is that in order to add required fields, I have to call $this->addRequired()

instead $builder->add()

, and so I lose the ability to chain calls add()

. This is why I am looking for a solution to transparently override the method $builder->add()

.

+1


source







All Articles