多个未映射的隐藏输入symfony2

时间:2015-02-25 17:22:11

标签: symfony twig hidden-field

我有一个文章实体。当我创建一篇文章时,我希望能够为其添加零到n个图像。 为此,我在临时目录中上传带有jQuery插件的文件,并在表单中添加<input type=hidden>,文件的完整路径为值。 没有验证错误时,它可以正常工作。但是当有,我得到一个错误说:

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in form_div_layout.html.twig at line 13

我很确定这是因为它试图这样做:

ErrorHandler ->handleError ('8', 'Array to string conversion', '/var/www/project/app/cache/dev/twig/47/a4/ac9a00176739f843e919f5f89883191930038a6e0aaa218869e4966ab7c6.php', '175', array('context' => array('value' => array('njm4uqsa9y6@54edfdaedd0736w3wstk.jpeg'),...

这是我的formType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('content')
        ->add('maxVote')
        ->add('expireAt', 'datetime', array(
                'widget' => 'single_text',
                'input' => 'string',
                'format' => 'dd-mm-yyyy',
            )
        )
        ->add('category', 'entity', array(
                'class' => 'AppBundle:StoryCategory',
                'required' => true
            )
        )
        ->add('answers', 'collection', array(
                'type' => new AnswerType()
            )
        )
        ->add('visibility', 'choice', array(
                'choices'   => array(1 => "label.public", 2 => "label.semiprivate", 3 => "label.private"),
                'expanded' => false,
                'multiple' => false
            )
        )
        ->add('attachment', 'hidden', array(
                'mapped' => false,
                'required' => false
            )
        )
        ->add('save', 'submit')
    ;
}

你知道发生了什么,或者我该怎么办?

编辑:

表单为空。我创建了一个新的Story实例

$story = new Story();
$form = $this->createForm(new StoryType(), $story);

当我提交表格时,

$form->handleRequest($request);

编辑2: Story.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Story
 *
 * @ORM\Table(name="story")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\StoryRepository")
 */
class Story
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text")
     * @Assert\NotBlank()
     */
    private $content;

    /**
     * @var string
     *
     * @ORM\Column(name="token", type="string", length=70, unique=true)
     */
    private $token;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime")
     */
    private $updatedAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="expire_at", type="datetime")
     * @Assert\NotBlank()
     */
    private $expireAt;

    /**
     * @var string
     *
     * @ORM\Column(name="author_ip", type="string", length=50, nullable=true)
     */
    private $authorIp;

    /**
     * @var integer
     *
     * @ORM\Column(name="max_vote", type="integer", nullable=true)
     * @Assert\Type(type="integer")
     * @Assert\Range(
     *      min = 0,
     *      max = 20000,
     *      minMessage = "validation.story.maxvote.min",
     *      maxMessage = "validation.story.maxvote.max"
     * )
     */
    private $maxVote;

    /**
     * @var integer
     *
     * @ORM\Column(name="nb_vote", type="integer")
     */
    private $nbVote;

    /**
     * @var integer
     * 1 = public, 2 = semi-private, 3 = private (only invited members)
     *
     * @ORM\Column(name="visibility", type="integer")
     *
     */
    private $visibility;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
    * @var StoryCategory
    *
    * @ORM\ManyToOne(targetEntity="StoryCategory", inversedBy="stories")
    * @ORM\JoinColumns({
    *   @ORM\JoinColumn(name="category_id", referencedColumnName="id")
    * })
    * @Assert\NotNull()
    */
    private $category;

    /**
    * @ORM\OneToMany(targetEntity="Answer", mappedBy="story", cascade={"persist", "remove"})
    * @Assert\Count(
    *      min = "2",
    *      max = "4",
    *      minMessage = "validation.story.answer.min",
    *      maxMessage = "validation.story.answer.max",
    *      groups={"premium"}
    * )
    * @Assert\Count(
    *      min = "2",
    *      max = "2",
    *      minMessage = "validation.story.answer.min",
    *      maxMessage = "validation.story.answer.max",
    * )
    */
    private $answers;

    /**
    * @ORM\OneToMany(targetEntity="Attachment", mappedBy="story", cascade={"persist", "remove"})
    */
    private $attachments;

    /**
    * @var User
    *
    * @ORM\ManyToOne(targetEntity="User", inversedBy="stories")
    * @ORM\JoinColumns({
    *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
    * })
    */
    private $author;


    public function __construct()
    {
        $datetime = new \DateTime();
        $this->createdAt = $datetime;
        $this->updatedAt = $datetime;
        $this->token     = base_convert(time(), 10, 36).\AppBundle\Library\StringHelper::randomString();
        $this->isActive  = false;
        $this->nbVote    = 0;
    }
}

Twig视图:

{% extends '::base.html.twig' %}

{% block basecontent %}
    {{ form_errors(form) }}
    {{ form_start(form, {attr: {id: 'story-form', novalidate: 'novalidate'}}) }}
    {{ form_row(form.title) }}
    {{ form_row(form.content) }}
    {{ form_row(form.category) }}
    <h3>Les choix de réponses possibles</h3>
    {% for answer in form.answers %}
        {{ form_widget(answer) }}
    {% endfor %}
    {{ form_row(form.visibility) }}
    {{ form_row(form.expireAt) }}
    {% for attachement in form.attachment %}
        {{ form_row(attachment) }}
    {% endfor %}
    {{ form_end(form) }}

    {# upload zone #}
    <div class="upload-block">
        <form action='{{ path('story_file_upload') }}' id="dropzone" class="dropzone">
        </form>
    </div>

{% endblock basecontent %}

这是我用javascript添加的内容:

$("#story-form").append('<input type="hidden" name="story_form[attachment][]" value="'+response.filename+'"/>');

所以我尝试没有它是一个数组(我删除了名称中的结尾[]),它的工作原理。所以我假设问题来自于此,我必须告诉formType它是一个数组。但是如何?

谢谢

2 个答案:

答案 0 :(得分:1)

我无法使其工作,所以我从formType中删除了“附件”字段。 当我上传文件时,我使用javascript和<input type="hidden">添加一个名称与formType中的字段不匹配的名称。 例如,Symfony生成的字段名为story_form['name']。我刚刚命名为attachments[]。这样Symfony就不会告诉我有一个额外的字段。 在我的控制器中,我使用$request->request->get('attachments')获取值。 可能有更好的方法,但我还没有找到它。

答案 1 :(得分:0)

你正在使用你的视频:

{% for attachement in form.attachment %}
    {{ form_row(attachment) }}
{% endfor %}

attachment声明为隐藏字段的地方:

->add('attachment', 'hidden', array(
        'mapped' => false,
        'required' => false
    )
)

隐藏字段只不过是存储在<input type="hidden">中的字符串,您无法迭代它。