【问题标题】:PHP Symfony: How to access a getter-Constraint in a form template?PHP Symfony:如何在表单模板中访问 getter-Constraint?
【发布时间】:2014-01-15 19:16:00
【问题描述】:

我创建了一个简单的实体类,它包含一些属性和一个公共 getter 方法,它执行一些东西并返回真或假。

class Item {
    public prop1;
    public prop2;

    public function isGetterConstraint() {
        return true // or false based on some calculations
    }
}

然后我在validation.yml中为那个类定义了约束:

Foo\MyBundle\Entity\Item:
    properties:
        prop1:
            - NotBlank: ~
        prop2:
            - NotBlank: ~
    getters:
        getterConstraint:
            - "True": { message: "zu" }

这就是您在许多示例中看​​到的内容,但我还没有找到如何在控制器或 twig 模板中以表单形式访问此 getter-constraint。就我而言,我确实需要在模板中使用它。

如果我这样定义我的 FormType

class ClientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('prop1', 'text')
            ->add('prop2', 'text');
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Foo\MyBundle\Entity\Item',
        ));
    }
}

和我的控制器一样

class ItemController extends Controller {
    public function createAction(Request $request) {
        $item = new Item();

        $form = $this->buildForm($item);
        $form->handleRequest($request);

        if ($form->isValid()) {
            // do some nice things like saving the data
        }
        return $this->render('FooMyBundle:Item:form.html.twig', array('form' => $form->createView());
    }
}

表单不知道 getter-constraint,我无法像以前使用属性约束那样访问它:

// form.html.thwig

{% if form.prop1.vars.errors %}{% endif %} // works

{% if form.getterConstraint.vars.errors %}{% endif %} // doesnot work

有没有办法将 getter 约束添加到 FormType 或者我必须做些什么来让表单在验证数据并将结果公开给控制器或模板时考虑这个约束?

【问题讨论】:

    标签: php forms validation symfony


    【解决方案1】:

    您实际上可以在实体中直接使用 getter 约束

    // src/Acme/BlogBundle/Entity/Author.php
    
    // ...
    use Symfony\Component\Validator\Mapping\ClassMetadata;
    use Symfony\Component\Validator\Constraints\True;
    
    class Author
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addGetterConstraint('passwordLegal', new True(array(
                'message' => 'The password cannot match your first name',
            )));
        }
    public function isPasswordLegal()
    {
        return $this->firstName != $this->password;
    }
    }
    

    演示代码取自Symfony Validation

    或者您可以使用注释在实体中定义回调

    // src/Acme/BlogBundle/Entity/Author.php
    
    // ...
    
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Validator\ExecutionContextInterface;
    
    /**
     * @Assert\Callback(methods={"isPasswordLegal"})
     */
    class Author
    {
    public function isPasswordLegal(ExecutionContextInterface $context)
    {
        $context->addViolationAt('password', 'wrong password');
    }  
    }
    

    在控制器中你可以这样做

    // src/KnpU/QADayBundle/Controller/EventController.php
    
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Validator\ExecutionContextInterface;
    use KnpU\QADayBundle\Entity\Event;
    // ...
    public function newAction(Request $request)
    {
        $form = $this->createFormBuilder(null, array(
            'data_class' => 'KnpU\QADayBundle\Entity\Event',
            'constraints' => array(
                new Assert\Callback(array(array($this, 'validateEventDates')))
            )
        ))
            ->add('name', 'text')
            ->add('startDate', 'datetime')
            ->add('endDate', 'datetime')
            ->getForm()
        ;
    
        // ...
    }
    
    public function validateEventDates(Event $event, ExecutionContextInterface $context)
    {
        $context->addViolationAt('startDate', 'There is already an event during this time!');
    }
    

    Custom Validation, Callback and Constraints

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多