参数的自定义验证器

参数的自定义验证器

本文介绍了Symfony 2 中带有参数/参数的自定义验证器/约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类似于 GitHub 处理删除存储库的方式的验证器.要确认删除,我需要输入回购名称.这里我想通过输入实体属性名称"来确认删除.我需要将名称传递给约束或以某种方式访问​​它,我该怎么做?

I want to create a validator similar to the way GitHub handles deleting repositories. To confirm the delete, I need to enter the repo name. Here I want to confirm delete by entering the entity property "name". I will either need to pass the name to the constraint or access it in some way, how do I do that?

推荐答案

你确实可以使用验证器约束来做到这一点:

you could indeed use a validator constraint to do that:

1:创建删除表单(直接或使用类型):

    return $this->createFormBuilder($objectToDelete)
        ->add('comparisonName', 'text')
        ->setAttribute('validation_groups', array('delete'))
        ->getForm()
    ;

2:将公共属性 comparisonName 添加到您的实体中.(或使用代理对象),将映射到上面相应的表单字段.

2: Add a public property comparisonName into your entity. (or use a proxy object), that will be mapped to the corresponding form field above.

3:定义一个类级别,回调验证器约束来比较两个值:

/**
 * @Assert\Callback(methods={"isComparisonNameValid"}, groups={"delete"})
 */
class Entity
{
    public $comparisonName;
    public $name;

    public function isComparisonNameValid(ExecutionContext $context)
    {
        if ($this->name !== $this->comparisonName) {
            $propertyPath = $context->getPropertyPath() . '.comparisonName';
            $context->addViolationAtPath(
                $propertyPath,
                'Invalid delete name', array(), null
            );
        }
    }
}

4:在视图中显示表单:

<form action="{{ path('entity_delete', {'id': entity.id }) }}">
   {{ form_rest(deleteForm) }}
   <input type="hidden" name="_method value="DELETE" />
   <input type="submit" value="delete" />
</form>

5:要验证删除查询是否有效,请在您的控制器中使用:

    $form    = $this->createDeleteForm($object);
    $request = $this->getRequest();

    $form->bindRequest($request);
    if ($form->isValid()) {
        $this->removeObject($object);
        $this->getSession()->setFlash('success',
            $this->getDeleteFlashMessage($object)
        );
    }

    return $this->redirect($this->getListRoute());

这篇关于Symfony 2 中带有参数/参数的自定义验证器/约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:16