PHP Symfony:如何在表单模板中访问getter-Constraint?

时间:2014-01-15 19:16:01

标签: php forms validation symfony

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

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中,或者我需要做些什么才能使表单在验证数据并将结果公开给控制器或模板时考虑此约束?

1 个答案:

答案 0 :(得分:0)

您实际上可以直接在实体中使用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