简体   繁体   中英

Symfony 2 validate a not required field but just has limited length

I tried to validate a not required field but just has limited length 0-50. But Symfony always generates required attribute as the following code. This makes user have to fill the required field. This is a server validation. Moreover, I also have a trouble with client validation because of the unwanted required attribute.

I wish a solution without using js. Does anybody know how to ignore attribute required that is generated by symfony? Please help me. Thank you

My case: I have a slug field. It is auto generated by field name (if slug is empty) or user can do that by himself. In loadMetadata method, only 1 constraint for property slug

$metadata->addPropertyConstraint('slug', new Length(array(
        'min' => 0, 'max' => 50
    )));

Html output

<textarea id="category_slug" 
name="category[slug]" required="required" class="form-control"></textarea>

Doctrine mapping

/**
 * @var string
 * @Gedmo\Slug(fields={"name"}, unique=false)
 * @ORM\Column(name="slug", type="string", length=100, nullable=true)
 */
private $slug;

If your form is described in a form class, you can include this in the class:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Your\Bundle\Entity\Whatever',
        'required' => false,
    ));
}

Edit:

If you only want to affect a single field, do something like this in your form class:

->add('slug', null, array(
    'required' => false,
)

To disable the "required" on the field you need...

On your javascript document ready you can use this code:

$('#category_slug').removeAttr('required');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM