Symfony2 - 保存表单集合字段

时间:2013-09-17 15:05:39

标签: forms symfony collections types

我在表单中有收集字段时遇到一些问题。我是Symfony的新人,所以也许这就是问题。我希望你能帮助我。

我有一个名为'TrOrder'的实体:

/**
* @ORM\Entity(repositoryClass="projectName\TrOrderBundle\Entity\TrOrderRepository")
*/
class TrOrder
{
    /**
     *  @ORM\Id
     *  @ORM\Column(type="integer")
     *  @ORM\GeneratedValue
     *  @Assert\NotBlank()
    */
    protected $id;

    /**
     *  @ORM\ManyToOne(targetEntity="projectName\UserBundle\Entity\Client", inversedBy="trOrders")
     *  @ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=false)        
     *  @Assert\NotBlank(message = "Por favor, selecciona el cliente tramitador.")
    */
    protected $client;

    /**
     * @ORM\OneToMany(targetEntity="projectName\TrOrderBundle\Entity\TrOrderAttachment", mappedBy="trOrder")
     */
    protected $attachments;

    ...

}

正如您所看到的,“附件”字段与另一个名为“TrOrderAttachment”的实体具有OneToMany关系:

/**
* @ORM\Entity(repositoryClass="projectName\TrOrderBundle\Entity\TrOrderAttachmentRepository")
* @ORM\HasLifecycleCallbacks
*/
class TrOrderAttachment
{
    /**
     *  @ORM\Id
     *  @ORM\Column(type="integer")
     *  @ORM\GeneratedValue
    */
    protected $id;

    /**
     *  @ORM\ManyToOne(targetEntity="projectName\TrOrderBundle\Entity\TrOrder", inversedBy="attachments")
     *  @ORM\JoinColumn(name="trorder_id", referencedColumnName="id")
    */
    protected $trOrder;

    /**
     *  @ORM\ManyToOne(targetEntity="projectName\TrOrderBundle\Entity\AttachmentType")
     *  @ORM\JoinColumn(name="attachmenttype_id", referencedColumnName="id")
    */
    protected $attachmentType;

    /** @ORM\Column(type="string", length=255) */
    protected $fileName;

    public $file;  

    ...
}   

我为TrOrder创建了一个表单,其中创建了一个Collection字段:

class TrOrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {   
        // Crea un array con los subordinados del cliente registrado
        $subordinates = $this->subordinates;        
        $sub = array();        
        foreach ($subordinates as &$subord)
            $sub[$subord->getId()] = $subord->getAdminName() . " (" . $subord->getId() . ")";

        // Crea los campos del formulario
        $builder    
            ...
            ->add('attachments', 'collection', array(
                                                   'required' => false,
                                                    'type'           => new               TrOrderAttachmentType(),
                                                    /*'allow_delete'   => true,*/
                                                    'allow_add' => true,
                                                    'prototype' => true,
                                                    'by_reference' => false,
                                                    ))
            ...
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'projectName\TrOrderBundle\Entity\TrOrder'/*,
            'csrf_protection' => false*/
        ));
    }

    public function getName()
    {
        return 'nencargo';
    }
}

TrOrderAttachment的形式是:

class TrOrderAttachmentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('attachmentType', 'entity', array( 'label' => 'Tipo de adjunto',
                                                     'class' => 'TrOrderBundle:AttachmentType'))
            ->add('file', 'file', array('label' => 'Archivo', 'required' => false))
            ;
    }
    public function setDefaultOptions(OptionsResolverInterface $resolve)
    {
        $resolve->setDefaults(array(
            'data_class' => 'projectName\TrOrderBundle\Entity\TrOrderAttachment'
        ));
    }
    public function getName()
    {
        return 'attachment';
    }
}

在我的TrOrder的html.twig中,我已经包含了这样的附件字段:

{{ form_widget(formulario.attachments) }}
<input class="jslink" type="submit" value="Add new file" />

还有一些js代码:

function add() {
            var collectionHolder = $('#nencargo_attachments');
            var prototype = collectionHolder.attr('data-prototype');
            // Sustituye __name__ con el número de hijos que tiene el div #nencargo_attachments, es decir, la cantidad de archivos adjuntos que hay.
            var form = prototype.replace(/__name__/g, collectionHolder.children().length);
            $(form).filter('div').first().html($(form).html() +'<a class="delete_link" href="#">Remove</a>');
            collectionHolder.append(form);
        }

        $('input.jslink').click(function(event){
            event.preventDefault();
            add();
        });

        $(document).on('click', 'a.delete_link',function(event){
            $(event.currentTarget).parent().remove();
        });

我的问题是如何将附加文件保存到TrOrder中的字段附件?它们也必须保存在TrOrderAttachment中。我不明白它是如何完成的。

我很感激很多答案。

1 个答案:

答案 0 :(得分:1)

您必须在trorder实体的附件属性上级联持久性。 More info here

提交表单后,使用getData方法检索实体。然后只需坚持下去。

对不起,简短的回答,但我在打电话。