Symfony2:如何在自定义验证器中从未映射的字段(集合内)获取数据


Symfony2: how to get data from unmapped field (within collection) in custom validator

我有一个表单,看起来大致像这样:首先有ItemType:

class ItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, array())
            ->add('item_user_role', CollectionType::class, array(
                'entry_type' => 'MyBundle'Form'ItemUserRoleType',
                'allow_add'    => true,
                'mapped' => false,
                'constraints' => array(
                    new ItemUserRole()
                )
            ))
        ;
    }
    ... 
}

还有ItemUserRoleType:

class ItemUserRoleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'id',
                TextType::class,
                array(
                    'mapped' => false,
                    'constraints' => array(),
                )
            )
            ->add('roleid',  EntityType::class, array(
                'class' => 'MyBundle'Entity'Role',
                'placeholder' => 'Select Role',
                'required' => false,
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false,
                'constraints' => array(
                    new NotNull(),
                    new NotBlank()
                )
            ))
            ->add('userid',  EntityType::class, array(
                'class' => 'MyBundle'Entity'User',
                'required' => false,
                'choice_label' => 'LastName',
                'multiple' => false,
                'expanded' => false,
                'constraints' => array(
                    new NotNull(),
                    new NotBlank()
                )
            ))
        ;
    }
}

我想要实现的是,提交的表单可以只包含userid和roleid(用于创建新的ItemUserRole),也可以包含id(用于编辑现有的ItemUserRole)。

我的问题是,现在在我的自定义验证器"ItemUserRole"我需要访问ID,以确保如果ID设置,那么用户被允许修改它。但由于它没有映射,我还没有找到如何做到这一点。

我尝试的是:

class ItemUserRoleValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $tmp = $this->context->getRoot()->get('item_user_role')->getData()[0];
        var_dump($tmp->getId());
        return;
    }
}

但是返回NULL。有提示吗?提前感谢。

使用$value变量

class ItemUserRoleValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $tmp = $value[0];
        var_dump($tmp->getId());
        return;
    }
}

$this->context,不包含任何表单数据,但包含所有此时发现的违反约束的集合。