我使用assert来检查我的表单的值。我无法在集合上使用assert。它的主要目的是检查每个值是否为空并且是否为数字。
我尝试使用this link来解决我的问题但没有成功。
以下是我的实体的一部分:
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
class Myclass
{
private $id;
/**
* @Assert\NotBlank()
* @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
*/
private $numbers;
...
public function __construct()
{
$this->numbers= new ArrayCollection();
}
...
public function addNumber($number)
{
$this->numbers[] = $number;
return $this;
}
public function removeNumber($number)
{
$this->numbers->removeElement($number);
}
public function getNumbers()
{
return $this->numbers;
}
}
这是我表格的一部分:
namespace MyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MyclassType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('numbers',"Symfony\Component\Form\Extension\Core\Type\CollectionType",array(
'required'=>true,
'prototype' => true,
'allow_add' => true,
'allow_delete' => true,
'entry_type'=>"Symfony\Component\Form\Extension\Core\Type\TextType",
'entry_options' => array(
'required' => true,
'attr' => array('class' => 'form-control'),
)
)
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Myclass'
));
}
public function getBlockPrefix()
{
return 'mybundle_myclass';
}
}
答案 0 :(得分:1)
“所有”断言似乎是工作All (The Symfony Reference)
以下是解决方案:
/**
* @Assert\All({
* @Assert\NotBlank(),
* @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
* })
*/
private $numbers;
答案 1 :(得分:0)
您需要制作自定义 http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
这是我用来查找唯一实体的一个很好的示例:How to validate unique entities in an entity collection in symfony2您可以更改逻辑以检查值。