Symfony 2以一种形式组合多个实体

时间:2014-08-21 21:17:44

标签: forms symfony collections

我有以下关系:

[实体] SesiuneUtilitati- | one_to_one | - > [实体] UtilitatiElectricitateCoeficient- | one_to_many | - > [实体] UtilitatiElectricitate

我想创建一个包含所有3个实体的表单

代码:

    <?php

namespace Mnv\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * UtilitatiElectricitateCoeficient
 *
 * @ORM\Table(name="utilitati_electricitate_coeficient")
 * @ORM\Entity(repositoryClass="Mnv\CoreBundle\Entity\Repository\UtilitatiElectricitateCoeficientRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class UtilitatiElectricitateCoeficient
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var decimal
     *
     * @ORM\Column(name="kwh", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $kwh;

    /**
     * @var decimal
     *
     * @ORM\Column(name="lei", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $lei;

    /**
     * @var decimal
     *
     * @ORM\Column(name="leikw", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $leikw;

    /**
     * @var decimal
     *
     * @ORM\Column(name="coeficient", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $coeficient;

    /**
     * @var string
     *
     * @ORM\Column(name="data_modificat", type="datetime", nullable=true)
     */
    private $dataModificat;

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

    /**
     * @ORM\OneToOne(targetEntity="SesiuneUtilitati", inversedBy="utilitatiElectricitateCoeficient")
     * @ORM\JoinColumn(name="id_sesiune", referencedColumnName="id_sesiune", onDelete="CASCADE")
     */
    protected $sesiuneUtilitati;

    /**
     * @ORM\ManyToOne(targetEntity="Clienti", inversedBy="utilitatiElectricitateCoeficient")
     * @ORM\JoinColumn(name="id_client", referencedColumnName="id_client")
     */
    protected $clienti;

    /**
    * @ORM\OneToMany(targetEntity="UtilitatiElectricitate", mappedBy="utilitatiElectricitateCoeficient", cascade={"persist", "remove"}, orphanRemoval=true)
    */
   private $utilitatiElectricitate;

    public function __construct() {
        $this->utilitatiElectricitate = new ArrayCollection();
    }

    ...


}


<?php

namespace Mnv\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * UtilitatiElectricitate
 *
 * @ORM\Table(name="utilitati_electricitate")
 * @ORM\Entity(repositoryClass="Mnv\CoreBundle\Entity\Repository\UtilitatiElectricitateRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class UtilitatiElectricitate
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var decimal
     *
     * @ORM\Column(name="kwh", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $kwh;

    /**
     * @var decimal
     *
     * @ORM\Column(name="pret", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $pret;

    /**
     * @var decimal
     *
     * @ORM\Column(name="total", type="decimal", precision=20, scale=2, nullable=true)
     */
    private $total;

    /**
     * @var string
     *
     * @ORM\Column(name="data_modificat", type="datetime", nullable=true)
     */
    private $dataModificat;

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

    /**
     * @ORM\ManyToOne(targetEntity="UtilitatiElectricitateCoeficient", inversedBy="utilitatiElectricitate")
     * @ORM\JoinColumn(name="id_coeficient", referencedColumnName="id")
     */
    protected $utilitatiElectricitateCoeficient;

    /**
     * @ORM\ManyToOne(targetEntity="dateClienti", inversedBy="utilitatiElectricitate")
     * @ORM\JoinColumn(name="id_contract", referencedColumnName="id")
     */
    protected $dateClienti;

    ...
}

<?php

namespace Mnv\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UtilitatiElectricitateCoeficientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lei','text', array('required' => false));
        $builder->add('coeficient','text', array('required' => false));
        $builder->add('kwh','text', array('required' => false));
        $builder->add('leikw','text', array('required' => false));  

        $builder->add('utilitatiElectricitate', 'collection', array(
                                                                    'type' => new UtilitatiElectricitateType(), 
                                                                    'allow_add' => true, 
                                                                    'prototype' => false, 
                                                                    'by_reference' => false
                                                                    ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mnv\CoreBundle\Entity\UtilitatiElectricitateCoeficient',
            'cascade_validation' => true,
        ));
    }

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

<?php

namespace Mnv\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UtilitatiElectricitateType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('kwh','text', array('required' => false));
        $builder->add('pret','text', array('required' => false));
        $builder->add('total','text', array('required' => false));

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mnv\CoreBundle\Entity\UtilitatiElectricitate',
            'cascade_validation' => true,
        ));
    }

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

 public function indexAction(Request $request, $idSocietate)
     {

         $societate = $this->getSocietate($idSocietate);
         $clienti = $this->getClienti($idSocietate);
         $sesiuneUtilitati = new SesiuneUtilitati();
         $dateClienti = new DateClienti();

         $utilitatiElectricitateCoeficient = new UtilitatiElectricitateCoeficient();
         $utilitatiElectricitate = new UtilitatiElectricitate();
         $utilitatiElectricitateCoeficient->getUtilitatiElectricitate()->add($utilitatiElectricitate);

         ...

         $form = $this->createForm(new SesiuneUtilitatiType(), $sesiuneUtilitati);
         $request = $this->get('request');

        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {
                // Persist objects to database
                $usr = $this->get('security.context')->getToken()->getUser();
                $now = new \DateTime();
                $date = $now->format("d-m-Y");
                $dt = explode('-', $date);

                $em = $this->getDoctrine()->getManager();
                $sesiuneUtilitati->setSocietati($societate);
                $sesiuneUtilitati->setAdaugataDe($usr->getUsername());
                $sesiuneUtilitati->setZiua($dt[0]);
                $sesiuneUtilitati->setLuna($dt[1]);
                $sesiuneUtilitati->setAnul($dt[2]);


                $em->persist($sesiuneUtilitati);
                $em->flush();
                $this->get('session')->getFlashBag()->set('tabel-util-notice', 'Datele au fost salvate cu succes.');

                // Redirect - This is important to prevent users re-posting
                // the form if they refresh the page
                return $this->redirect($this->generateUrl('tabel_utilitati',array('idSocietate' => $idSocietate)));
            }
        }
         return $this->render('MnvCoreBundle:Page:utilitati.html.twig', array(
             'societate' => $societate,
             'form' => $form->createView(),
             'clienti' => $clienti,
         ));
     }

我在这里做错了什么?字段utilitatiElectricitate的字段在树枝中不可用。 例如,如果我尝试form.utilitatiElectricitateCoeficient.utilitatiElectricitate [0] .kwh我得到一个错误,键0不存在。

创建SesiuneUtilitatiType以包含所有其他形式:

<?php


namespace Mnv\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;


class SesiuneUtilitatiType extends AbstractType
{


    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('utilitatiTotal', new UtilitatiTotalType());

        $builder->add('utilitatiElectricitateCoeficient', new UtilitatiElectricitateCoeficientType());

           .
           .
           .

       $builder->add('Salveaza datele si genereaza facturi', 'submit');

    }



    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mnv\CoreBundle\Entity\SesiuneUtilitati',
            'cascade_validation' => true,
        ));
    }

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

和UtilitatiElectricitateCoeficientType:

<?php

namespace Mnv\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UtilitatiElectricitateCoeficientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lei','text', array('required' => false));
        $builder->add('coeficient','text', array('required' => false));
        $builder->add('kwh','text', array('required' => false));
        $builder->add('leikw','text', array('required' => false));  

        $builder->add('utilitatiElectricitate', 'collection', array(
                                                                    'type' => new UtilitatiElectricitateType(), 
                                                                    'allow_add' => true, 
                                                                    'prototype' => true, 
                                                                    'by_reference' => false
                                                                    ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mnv\CoreBundle\Entity\UtilitatiElectricitateCoeficient',
            'cascade_validation' => true,
        ));
    }

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

和UtilitatiElectricitateType:

<?php

namespace Mnv\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UtilitatiElectricitateType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('kwh','text', array('required' => false));
        $builder->add('pret','text', array('required' => false));
        $builder->add('total','text', array('required' => false));

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mnv\CoreBundle\Entity\UtilitatiElectricitate',
            'cascade_validation' => true,
        ));
    }

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

1 个答案:

答案 0 :(得分:-1)

您必须创建一个SesiuneUtilitatiType,您将其嵌入UtilitatiElectricitateCoeficientType,现在最后一个将嵌入UtilitatiElectricitateType。您应该阅读embedded forms的文档,以清楚地了解要遵循的规则