Question

Using Symfony2.3.4

As the title quite explains it I need to bind an error message to an embedded form field and preferably in the controller. I'm thinking maybe similar to how I do it with single forms:

use Symfony\Component\Form\FormError;
//....
public function createAction(){
//.....
$postData = current($request->request->all());

if ($postData['field_name'] == '') {
            $error = new FormError("Write some stuff in here");
            $form->get('field_name')->addError($error);
        }
//.....
}

or maybe it's got to be done differently, either way I need help,

thank$

Was it helpful?

Solution

I see, that you are trying to display a message when a form field does not contain any value. You can do this easily in your form class, like this:

buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('field_name', 'text', array(
        'label' => 'Field label',
        'required' => true,
        'constraints' => array(
            new NotBlank(array('message' => 'Write some stuff in here.'))
         ),
    ));
}

If you need to inject some other kind of constraint to your form which is not part of Symfony2 framework, you can create your own validation constraint.

If you want to add some options to your form in controller, it can be done in the method where you create the form by setting your own options:

class YourController {
    public function createForm(YourEntity $yourEntity){
        $form = $this->createForm(new YourFormType(), $yourFormType, array(
            'action' => $this->generateUrl('your_action_name', 
            array('your_custom_option_key' => 'Your custom option value')),
            'method' => 'POST',
        ));

        return $form;
    }

    // Rest of code omitted.
}

After that you need to add an option in setDefaultOptions(OptionsResolverInterface $resolver) method, in your form class, like this:

public function setDefaultOptions(OptionsResolverInterface $resolver){
    $resolver->setDefaults(array(
        'your_custom_option_key' => '',
    ));
}

And then access it in buildForm(FormBuilderInterface $builder, array $options) method, like this:

buildForm(FormBuilderInterface $builder, array $options) {
    $options['your_custom_option_key']; // Access content of your option

    // The rest of code omitted.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top