Symfony 3形成pre-populate集合字段类型

时间:2017-02-24 10:35:55

标签: php forms symfony

是否可以使用某些默认项目填充集合 假设您有价格集合,但每个价格可以是不同类型。我想要的是该集合总是有一些预定义的(生成某种方式)项目?

主要实体

<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\ManyToMany;

/**
 * Class Stamp
 * @package AppBundle\Entity
 *
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\StampRepository")
 * @ORM\Table(name="stamp")
 * @ORM\HasLifecycleCallbacks()
 */
class Stamp
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=512, nullable=true)
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Price", cascade={"persist", "remove"})
     * @ORM\JoinTable(name="stamps_prices",
     *     joinColumns={@ORM\JoinColumn(name="stamp_id", referencedColumnName="id", onDelete="CASCADE")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="price_id", referencedColumnName="id", onDelete="CASCADE")}
     *     )
     */
    private $prices;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

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

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param mixed $title
     *
     * @return Stamp
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getPrices()
    {
        return $this->prices;
    }

    public function addPrice(Price $price)
    {
        $this->prices->add($price);
    }

    /**
     * @param mixed $prices
     *
     * @return Stamp
     */
    public function setPrices(ArrayCollection $prices)
    {
        $this->prices = $prices;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param mixed $createdAt
     *
     * @return Stamp
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param mixed $updatedAt
     *
     * @return Stamp
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function updateTimestamps()
    {
        $this->setUpdatedAt(new \DateTime('now'));

        if (null == $this->getCreatedAt()) {
            $this->setCreatedAt(new \DateTime());
        }
    }
}

主要实体表格

<?php

namespace AppBundle\Form;

use AppBundle\Entity\Stamp;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AdminStampForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', null, [
                'label' => false,
                'attr' => [
                    'id' => 'stamp-title',
                    'class' => 'form-control input-md',
                    'placeholder' => 'Enter title',
                    'autocomplete' => 'off'
                ]
            ])
            ->add('prices', CollectionType::class, [
                'label' => false,
                'entry_type' => AdminStampPriceForm::class,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Stamp::class,
        ]);
    }

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

价格实体

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class Price
 * @package AppBundle\Entity
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PriceRepository")
 * @ORM\Table(name="price")
 */
class Price
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\PriceType")
     * @ORM\JoinColumn(name="type_id", nullable=false, referencedColumnName="id")
     */
    private $type;

    /**
     * @ORM\Column(type="string")
     */
    private $value;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $city;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $issueDate;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param mixed $type
     * @return Price
     */
    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param mixed $value
     *
     * @return Price
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * @param mixed $city
     *
     * @return Price
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getIssueDate()
    {
        return $this->issueDate;
    }

    /**
     * @param mixed $issueDate
     *
     * @return Price
     */
    public function setIssueDate($issueDate)
    {
        $this->issueDate = $issueDate;

        return $this;
    }
}

PriceType实体

<?php

namespace AppBundle\Entity;

use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class PriceType
 * @package AppBundle\Entity
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PriceTypeRepository")
 * @ORM\Table(name="price_type")
 * @ORM\HasLifecycleCallbacks()
 */
class PriceType
{
    const SECTION_UNUSED = 1;
    const SECTION_USED = 2;
    const SECTION_FDC = 3;
    const SECTION_CUSTOM = 4;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $section;

    /**
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @ORM\Column(type="boolean")
     */
    private $hasCityName = false;

    /**
     * @ORM\Column(type="boolean")
     */
    private $hasIssueDate = false;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isPredefined = false;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getSection()
    {
        return $this->section;
    }

    /**
     * @param mixed $section
     *
     * @return PriceType
     */
    public function setSection($section)
    {
        $this->section = $section;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     *
     * @return PriceType
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getHasCityName()
    {
        return $this->hasCityName;
    }

    /**
     * @param mixed $hasCityName
     *
     * @return PriceType
     */
    public function setHasCityName($hasCityName)
    {
        $this->hasCityName = $hasCityName;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getHasIssueDate()
    {
        return $this->hasIssueDate;
    }

    /**
     * @param mixed $hasIssueDate
     *
     * @return PriceType
     */
    public function setHasIssueDate($hasIssueDate)
    {
        $this->hasIssueDate = $hasIssueDate;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getIsPredefined()
    {
        return $this->isPredefined;
    }

    /**
     * @param mixed $isPredefined
     *
     * @return PriceType
     */
    public function setIsPredefined($isPredefined)
    {
        $this->isPredefined = $isPredefined;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $createdAt
     *
     * @return PriceType
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param \DateTime $updatedAt
     *
     * @return PriceType
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function updateTimestamps()
    {
        $this->setUpdatedAt(new \DateTime('now'));

        if (null == $this->getCreatedAt()) {
            $this->setCreatedAt(new \DateTime());
        }
    }
}

PriceType资料库

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class PriceTypeRepository
 * @package AppBundle\Entity
 */
class PriceTypeRepository extends EntityRepository
{

    public function getPredefinedPriceTypes($section)
    {
        return $this
            ->createQueryBuilder('pt')
                ->andWhere('pt.section = :section')
                ->setParameter('section', $section)
                ->andWhere('pt.isPredefined = :isPredefined')
                ->setParameter('isPredefined', true)
            ->getQuery()
            ->getResult()
        ;
    }
}

Priec表格

<?php

namespace AppBundle\Form;

use AppBundle\Entity\Price;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AdminStampPriceForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('value', null, [
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Price::class,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'app_bundle_admin_stamp_price_form';
    }
}

主要实体控制器newAction

/**
 * @Route("/new", name="admin_stamps_new")
 * @Template(engine="haml")
 */
public function newAction(Request $request)
{
    $stamp = new Stamp();

    $priceTypeRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:PriceType');
    $priceTypes = $priceTypeRepo->getPredefinedPriceTypes(PriceType::SECTION_UNUSED);
    /** @var PriceType $priceType */
    foreach ($priceTypes as $priceType) {
        $price = new Price();
        $price->setType($priceType->getId());
        $stamp->addPrice($price);
    }
    $form = $this->createForm(AdminStampForm::class, $stamp);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        /** @var Stamp $stamp */
        $stamp = $form->getData();

        $user = $this->getUser();
        $stamp->setUser($user);
        $stamp->setCountry($user->getAdminConfig()->getCountry());

        $em = $this->getDoctrine()->getManager();
        $em->persist($stamp);
        $em->flush();

        $this->addFlash('success', 'Successfully added a new stamp!');

        return $this->redirectToRoute('admin_stamps_list');
    }

    return [
        'form' => $form->createView(),
    ];
}

所以我试图填充Stamp实体本身。但我真正需要的是有4个单独的字段集价格(每个字段设置为价格类型)。并且(和)有一些预定义的 $ priceType-&gt; isPredefined()价格。我不确定你是否理解我想说的话。所以我会回答所有即将到来的问题。

0 个答案:

没有答案