Symfony2 - 设置嵌入表单的最小数量

时间:2012-09-03 07:51:17

标签: symfony

使用How to Embed a Collection of Forms中的方案,我想确保Task始终至少有一个Tag。但就我而言,TaskTag的关系是1:n而不是n:m

我特别关注所有Tags被移除的情况(我想阻止这种情况)。如何确保Task表单始终至少有一个Tag

3 个答案:

答案 0 :(得分:2)

正如m0c所指出的,解决方案确实是利用自定义验证约束。但是,我发现Symfony2.1中已存在这样的约束验证器,因此我冒昧地将其移植到2.0(因为2.1中的一些接口显然已经改变)。

以下是Bernhard Schussek's Count.phpCountValidator.php的移植版本(适用于2.0),用于计算集合(请参阅https://github.com/symfony/Validator/tree/master/Constraints)。

Count.php

namespace MyVendor\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\MissingOptionsException;

/**
 * @Annotation
 *
 * @api
 */
class Count extends Constraint
{
    public $minMessage = 'This collection should contain {{ limit }} elements or more.';
    public $maxMessage = 'This collection should contain {{ limit }} elements or less.';
    public $exactMessage = 'This collection should contain exactly {{ limit }} elements.';
    public $min;
    public $max;

    public function __construct($options = null)
    {
        if (null !== $options && !is_array($options)) {
            $options = array(
                'min' => $options,
                'max' => $options,
            );
        }

        parent::__construct($options);

        if (null === $this->min && null === $this->max) {
            throw new MissingOptionsException('Either option "min" or "max" must be given for constraint ' . __CLASS__, array('min', 'max'));
        }
    }
}

CountValidator.php

namespace MyVendor\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class CountValidator extends ConstraintValidator
{
    /**
     * {@inheritDoc}
     */
    public function isValid($value, Constraint $constraint)
    {
        if (null === $value) {
            return false;
        }

        if (!is_array($value) && !$value instanceof \Countable) {
            throw new UnexpectedTypeException($value, 'array or \Countable');
        }

        $count = count($value);

        if ($constraint->min == $constraint->max
                && $count != $constraint->min) {
            $this->setMessage($constraint->exactMessage, array(
                '{{ count }}' => $count,
                '{{ limit }}' => $constraint->min,
            ));

            return false;
        }

        if (null !== $constraint->max && $count > $constraint->max) {
            $this->setMessage($constraint->maxMessage, array(
                '{{ count }}' => $count,
                '{{ limit }}' => $constraint->min,
            ));

            return false;
        }

        if (null !== $constraint->min && $count < $constraint->min) {
            $this->setMessage($constraint->minMessage, array(
                '{{ count }}' => $count,
                '{{ limit }}' => $constraint->min,
            ));

            return false;
        }

        return true;
    }
}

答案 1 :(得分:1)

我将创建一个自定义Validator,它检查在关系实体级别上映射到的属性是否在集合中有一些元素。

验证器失败了:

   public function isValid($value, Constraint $constraint)
    {
        if (count($value) <1 ) {
            //also define a message for your custom validator
            $this->setMessage($constraint->message, array('%string%' => $value));
            return false;
        }
        return true;
    }

有关如何实施此自定义验证程序的说明:http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

答案 2 :(得分:1)

你想在发布时进行验证,不管是否存在至少1个标签,

或者您希望表单在加载时实际上已经有1个空标记吗? (我假设因为你说“如何确保任务表格总是至少有1个标签?”

如果你需要第二个,只需

$tag1 = new Tag();
$tag1->name = 'tag1';
$task->getTags()->add($tag1);

之前

$form = $this->createForm(new TaskType(), $task);
像文档说的那样..