我目前正在处理一个symfony2表单,该表单允许用户在创建文章时添加图片。我创建了一个看起来像这样的表单:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('price')
->add('size')
->add('description')
->add('pictures', 'collection', array(
'type' => new PictureType(),
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
'prototype' => true
));
}
事情是,当我使用这个时,我的表单不允许上传任何图片(我可以添加名称,价格,尺寸,描述,但是"添加文件"按钮无处可寻)。图片实体看起来像这样:
class Picture
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Assert\File(maxSize="6000000")
*/
public $file;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="path", type="string", length=255)
*/
private $path;
/**
* @ORM\ManyToOne(targetEntity="Article", inversedBy="pictures")
* @ORM\JoinColumn(name="property_id", referencedColumnName="id")
*/
protected $article;
表单显示如下:
<form method="post" {{ form_enctype(form) }}>
<br/>
<h1>NEW ARTICLE</h1>
{{ form_widget(form) }}
<input type="submit" class="btn btn-primary send_message" />
</form>
这是PictureType
class PictureType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name','text',array(
"label" => "Name",
"required" => TRUE,
));
$builder->add('description','textarea',array(
"label" => "Description",
"required" => FALSE,
));
$builder->add('files','file',array(
"label" => "Fichiers",
"required" => FALSE,
"attr" => array(
"accept" => "image/*",
"multiple" => "multiple",
)
));
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Dyma\DesignerBundle\Entity\Picture'
));
}
/**
* @return string
*/
public function getName()
{
return 'dyma_designerbundle_picture';
}
}
这是我第一次在表单中使用某个集合,所以我甚至不确定它应该是什么样子,但我很确定我的代码有问题。知道为什么我不能添加这些图片吗?
答案 0 :(得分:0)
您应该(如评论中所述)在表单中添加enctype="multipart/form-data"
。
除此之外,
<input type="file" name="file" />