我目前正在开发一个使用最新版本的Symfony2的应用程序。验证包含文件上传字段的表单时遇到一些问题。如何在Symfony2(ImageValidator)中验证文件上传?
我的表单代码看起来像这样(缩短):
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\Collection;
class EventEditForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add("name", "text", array("required" => true));
//....
$builder->add("image", "file", array("property_path" => false, "required" => false));
}
public function getDefaultOptions(array $options)
{
$collectionConstraint = new \Symfony\Component\Validator\Constraints\Collection(array(
'image' => new \Symfony\Component\Validator\Constraints\Image()
));
$options["validation_constraint"] = $collectionConstraint;
return $options;
}
public function getName()
{
return 'editeventform';
}
}
正如你可以看到在这里我要确保上传的文件是一个图像。我用的形式是这样的:
$form = $this->createForm(new \Trancefans\AdminBundle\Form\EventEditForm(), $event);
但运行此代码我收到以下错误时:
Expected argument of type array or Traversable and ArrayAccess, object given
我真的不知道我的故障。我完全按照文档中的描述进行操作。有人能帮助我吗? :-)
顺便说一句:图像不是由事件entitiy表示的,而是表单的其他所有字段。我使用教条。