首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony2:如何根据数据在bind PRE_SET_DATA中为字段添加表单约束

问Symfony2:如何根据数据在bind PRE_SET_DATA中为字段添加表单约束
EN

Stack Overflow用户
提问于 2012-11-29 03:48:11
回答 2查看 9.6K关注 0票数 5

我在Symfony 2中有一个表单,基本上有两个字段:

代码语言:javascript
复制
public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('contactType', 'select', array(  'choices' => $contactTypes ))
            ->add('value', 'text');
}

然后我添加了一个监听FormEvents::PRE_SET_DATA事件的EventSubscriber。我实际上想做的是根据contactType的值(从1到4的数值,代表电子邮件、移动电话、固定电话和传真)来改变验证的方式。

我遵循了这个教程http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

但是我不知道如何向value字段添加约束。

有谁可以帮我?在此之前非常感谢。

EN

回答 2

Stack Overflow用户

发布于 2013-02-03 02:23:20

您可以将组设置为字段的验证约束和determine validation groups based on submitted data,而不是在event subscriber中动态添加验证约束(甚至不确定这是否可能)。

票数 9
EN

Stack Overflow用户

发布于 2014-04-16 20:43:41

从控制器创建表单的函数:

代码语言:javascript
复制
<?php 

// ...

class DefaultController extends Controller
{
    /**
     * 
     * @param \Clicproxy\DeltadocCabBundle\Entity\Mark $mark
     * @param \Clicproxy\DeltadocCabBundle\Entity\Tag $tag
     * @return Form
     */
    private function createTagForm(Mark $mark, Tag $tag)
    {
        $form = $this->createForm(new TagType(), $tag, array(
            'action' => $this->generateUrl('tag_new', array('slug' => $this->slugify($mark->getName()))),
            'method' => 'POST',
        ));

        foreach ($mark->getFields() as $field)
        {
            $form->add($this->slugify($field->getName()), $field->getFormType(), $field->getOptions());
        }

        $form->add('submit', 'submit', array('label' => 'crud.default.save'));

        return $form;
    }

// ...

实体中的代码(类型、约束等):

代码语言:javascript
复制
<?php

// ...

/**
 * Field
 *
 * @ORM\Table()
 * @ORM\Entity
 * @UniqueEntity({"name", "mark"})
 */
class Field
{

   // ...

    /**
     * 
     * @return array
     */
    public function getOptions()
    {
        $options = array('label' => $this->getName(), 'mapped' => FALSE);

        $options['required'] = $this->getType() != 'checkbox';

        if ('date' == $this->getType())
        {
            $options['attr']['class'] = 'datepicker'; // 'input-group date datepicker';
            $options['attr']['data-date-format'] = 'dd/mm/yyyy';
            $options['attr']['data-date-autoclose'] = true;
        }

        if ('choice' == $this->getType())
        {
            $choices = array();
            foreach ($this->getChoices() as $choice)
            {
                $choices[$choice->getValue()] = $choice->getName();
            }
            asort($choices);
            $options['choices'] = $choices;
        }

        $options['constraints'] = $this->getValidationConstraint();

        return $options;
    }

    public function getValidationConstraint ()
    {
        $validation_constraint = array();
        if ('number' == $this->getType()) {
            if (0 < $this->getMaximum()) {
                $validation_constraint[] = new LessThanOrEqual (array(
                    'message' => 'entity.field.number.lessthanorequal', // {{ compared_value }}
                    'value' => $this->getMaximum()
                ));
            }
            if (0 < $this->getMinimum()) {
                $validation_constraint[] = new GreaterThanOrEqual(array(
                    'message' => 'entity.field.number.greaterthanorequal', // {{ compared_value }}
                    'value' => $this->getMinimum()
                ));
            }
        } elseif ('text' == $this->getType ()) {
            if (0 < $this->getMaximum()) {
                $validation_constraint[] = new Length(array(
                    'min' => $this->getMinimum() > 0 ? $this->getMinimum() : 0,
                    'max' => $this->getMaximum() > 0 ? $this->getMaximum() : 0,
                    'minMessage' => 'entity.field.text.minMessage', // {{ limit }}
                    'maxMessage' => 'entity.field.text.maxMessage',
                    'exactMessage' => 'entity.field.text.exactMessage',
                ));
            }
        } elseif ('date' == $this->getType()) {

        }

        return $validation_constraint;
    }

// ...

实际上,所有这些代码都是有效的。

有了这个,您就有了一个使用约束动态生成表单的解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13613227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档