我有一个表单类型类(让我们称之为" ClientType"),它包含另一个表单类型类(" PhoneType")。 PhoneType是ClientType的一部分,如下所示:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('phoneVoice', new PhoneType);
}
我想设置它,以便PhoneType的必填字段适用于IFF,至少填写一个PhoneType字段。例如,PhoneType可能包含国家/地区代码,编号和扩展名。如果填写了这些字段中的任何一个,我需要PhoneType的必填字段(国家代码和号码)。
我该如何设置?提前致谢!
编辑 - 添加表单类型
ClientType
<?php
namespace AppName\ClientBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use AppName\ClientBundle\Form\Type\PhoneType;
use Doctrine\ORM\EntityManager;
class ClientType extends AbstractType {
/**
* @var EntityManager
*/
protected $em;
public function __construct(EntityManager $em) {
$this->em = $em;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('phoneVoice', new PhoneType, ['required' => true]);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppName\ClientBundle\Entity\Client',
'cascade_validation' => true,
));
}
/**
* @return string
*/
public function getName()
{
return 'client';
}
}
PHONETYPE
<?php
namespace AppName\ClientBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class PhoneType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('countryCode', new PhoneCountryCodeType, [
'preferred_choices' => ['1'],
'empty_value' => '1'
])
->add('number', 'number', [
'required' => true,
'max_length' => 10
])
->add('extension', 'number')
->add('isPrimary');
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppName\ClientBundle\Entity\PhoneRecord'
));
}
/**
* @return string
*/
public function getName()
{
return 'phone';
}
}
答案 0 :(得分:0)
如我所见,您的PhoneType映射到PhoneRecord实体,因此您可以使用自定义validation mechanism。
你的案例:
//AppName\ClientBundle\Entity\PhoneRecord.php
public function isCreditsLegal()
{
if ($this->countryCode || $this->number || $this->extension) {
return $this->countryCode && $this->number;
}
return true;
}
#validation.yml
AppName\ClientBundle\Entity\PhoneRecord:
getters:
creditsLegal:
- "True": { message: "Invalid credits" }