看起来symfony试图通过验证来帮助你,但我有点困惑。我有一个看起来像这样的地址对象
/**
* @ORM\Entity
* @ORM\Table(name="address")
*/
class Address {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
* @var int $id
*/
private $id;
/**
* @ORM\Column(name="street1", type="string", nullable=true)
* @var string $street1
*/
private $street1;
/**
* @ORM\Column(name="street2", type="string", nullable=true)
* @var string $street2
*/
private $street2;
/**
* @ORM\Column(name="street3", type="string", nullable=true)
* @var string $street3
*/
private $street3;
/**
* @ORM\Column(name="city", type="string", nullable=true)
* @var string $city
*/
private $city;
/**
* @ORM\Column(name="state", type="string", nullable=true)
* @var string $state
*/
private $state;
/**
* @ORM\Column(name="zip", type="integer", nullable=true)
* @var integer $zip
*/
private $zip;
/**
* @var AddressType
* This is only used for previous addresses
* @DoctrineAssert\Enum(entity="RLD\AppBundle\DBAL\AddressType")
* @ORM\Column(name="address_type", type="AddressType", nullable=true)
*/
private $addressType;
}
我两次使用这个对象。一次为当前地址,另一次为先前地址。问题是,如果用户未在当前地址超过5年,我只需要以前地址的信息。我怀疑我需要扩展课程以获得我想要的工作。但即使在扩展后我也不确定如何进行条件验证。
如何进行条件验证?
if(currentAddress < 5)
validate previous address;
任何人都有这方面的想法?这个表单似乎带有一个需要此功能的共同主题。任何帮助/建议将不胜感激。
答案 0 :(得分:1)
使用Traits怎么样?
http://php.net/manual/de/language.oop5.traits.php
为默认属性定义特征,然后创建2个类:
班级地址
类PreviousAddress
类PreviousAddress具有addiotional属性。
然后您可以通过instanceof验证:
if ($object instanceof PreviousAddress) {
// has type
}
答案 1 :(得分:1)
您可以使用验证组有选择地激活验证回调。例如:
地址实体
/**
*
* @Assert\Callback(methods={"validateCurrentAddress"}, groups={"currentAddress"})
* @Assert\Callback(methods={"validatePreviousAddress"}, groups={"previousAddress"})
*/
class Address
{
....
public function validatePreviousAddress(ExecutionContextInterface $context)
{
if (/* is not valid */)
{
$context->addViolationAt('/*your field*/','error.previous_address_invalid');
}
}
}
<强> CurrentAddressFormType 强>
class CurrentAddressFormType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class'=> 'Acme\DemoBundle\Entity\Address',
'validation_groups' => array('currentAddress')
));
}
}
<强> PreviousAddressFormType 强>
class PreviousAddressFormType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class'=> 'Acme\DemoBundle\Entity\Address',
'validation_groups' => array('previousAddress')
));
}
希望这个帮助