[英]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)。
我的問題是,在我的自定義Validator“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,不包含任何表單數據,但是此時發現的所有約束違規的集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.