user1098965
user1098965

Reputation:

Custom single form field type ignores validation in Symfony 2?

I've a reusable (here simplified) custom field type that inherits from textarea type. As default, content can't be empty, so i specified validation_constraint as default option:

namespace Acme\HelloBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Validator\Constraints\NotBlank;

class SmsContentType extends AbstractType
{

    public function getDefaultOptions(array $options)
    {
        return $options + array(
            'label'                 => 'Testo *',
            'validation_constraint' => new NotBlank()
        );
    }

    public function getParent(array $options) { return 'textarea'; }

    public function getName() { return 'sms_content'; }

}

But leaving the content empty doen't show any error. Not near the field itself and not as bubbled error using form_errors(form).

Where i'm wrong? Oh, i'm using this custom type inside another form:

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('sms_birthday_template', new SmsContentType(), array(
                'label' => 'SMS compleanno',
            ))
        ;
    }
}

Upvotes: 1

Views: 1149

Answers (1)

Bernhard Schussek
Bernhard Schussek

Reputation: 4841

This is a limitation of Symfony 2.0. There the "validation_constraint" option only works on the root form.

In Symfony 2.1, "validation_constraint" was renamed to "constraints" and does exactly what you want:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'label'       => 'Testo *',
        'constraints' => new NotBlank()
    ));
}

Upvotes: 2

Related Questions