我的项目中有三个文档:事件,OrganizerProfile和用户。
用户可以具有多个OrganizerProfile(类似于Facebook上的“页面”)和事件。
用户创建和事件时,他可以为事件分配“ OrganizerProfile”(用户Alberto为“公司A”创建一个事件,称为“事件X”)。
为此,我创建了以下表单:
OrganizerProfileType.php
class OrganizerProfileType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('email', EmailType::class)
->add('name', TextType::class)
->add('description', TextType::class, ['required' => false])
...
EventType.php
class EventType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$profileChoices = ... //List of existing profiles
$builder
->add('profile_list', ChoiceType::class, [
'choices' => $profileChoices,
'required' => false,
'mapped' => false,
])
->add('profile', OrganizerProfileType::class, [
'required' => true,
])
->add('title', TextType::class, ['required' => false])
->add('description', TextType::class, ['required' => false])
...
用户可以在“ profile_list”字段中找到其现有的OrganizerProfiles。如果用户未选择现有的配置文件,则用户可以选择其中之一并将其分配给事件BUT,他必须在“配置文件”表单中插入信息。
我想将个人资料表格设为“可选”,并且仅当用户未选择现有的个人资料时才要求填写该表格。
我怎样才能做到这一点?谢谢
因此,您的FormType应该如下所示:
class EventType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$profileChoices = [...];
$builder
->add('profile_list', ChoiceType::class, [
'choices' => $profileChoices,
'required' => false,
'mapped' => false,
])
->add('profile', OrganizerProfileType::class, [
'constraints' => [
new Valid()
]
])
->add('title', TextType::class, ['required' => false])
->add('description', TextType::class, ['required' => false]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'validation_groups' => function (FormInterface $form) {
if (null === $form->get('profile_list')->getData()) {
return ['without_profile'];
}
return ['with_profile']; // Or simply 'Default'
},
]);
}
}
更新:也使用另一个FormType中的验证组
然后,您需要使用验证组来处理子表单的验证,例如:
class OrganizerProfileType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('email', EmailType::class, [
'constraints' => [
new NotNull(
[
'groups' => ['without_profile', 'with_profile']
]
)
]])
->add('name', TextType::class, [
'constraints' => [
new NotNull(
[
'groups' => ['without_profile', 'with_profile']
]
)
]])
->add('description', TextType::class, ['required' => false])
希望这个帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句