在基于ArrayCollection()的Symfony2中填充复选框

时间:2012-10-16 20:47:22

标签: symfony

编辑 - 重新定义的问题并包含其他特定代码

在我的Symfony2项目中,我有一个实体(配置),其中包含与另一个实体( ConfigurationsFeatures )的OneToMany关系。我正在尝试构建一个表单,允许用户更改Configurations实体中的值,并选择要持久保存到ConfigurationsFeatures实体的值。有两种情况使用表单:

1)创建新配置 - >呈现一个空白表单,其中包含Configurations中值的字段以及ConfigurationsFeatures中潜在值的复选框集合;潜在价值的来源实际上是第三个实体, CoreCodes 。验证后,表单的Configurations-values将持久保存到Configurations实体,并且所选复选框将持久保存到ConfigurationsFeatures。

2)更新现有配置 - >使用字段中显示的配置的现有值呈现表单,并为所有可能的ConfigurationsFeatures值呈现复选框的集合但是已经选择了现有值。

我为场景#1构建了表单类型和控制器操作,对其进行了测试,一切正常。但是,我似乎无法在表单的复选框部分解决“已经选择了现有值”。我意识到,由于我目前正在设置我的控制器,我基本上将苹果与橙子进行比较,因为$ entity-> getFeatures()返回ConfigurationsFeatures实体的ArrayCollection,并且在表单中没有任何要映射的内容,因为表单使用CoreCodes实体的集合。

那么如何弥合这一差距?


实体\配置(存储各个配置)

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

/**
 * Lynux\AssetBundle\Entity\Core\Configurations
 * ... ORM declarations ...
 */
class Configurations
{
    // ... plain old properties, nothing fancy here... 

    /**
     * @ORM\OneToMany(targetEntity="Lynux\AssetBundle\Entity\Core\ConfigurationsFeatures", mappedBy="configurationFk")
     */
    private $features;

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

    // getters and setters

    /**
     * Set features
     */
    public function setFeatures(ArrayCollection $features)
    {
        $this->features = $features;
    }

    /**
     * Get features
     */
    public function getFeatures()
    {
        return $this->features;
    }
}

实体\ ConfigurationsFeatures (按配置存储所选功能)

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

/**
 * Lynux\AssetBundle\Entity\Core\ConfigurationsFeatures
 * ... ORM declarations ...
 */
class ConfigurationsFeatures
{
    /**
     * @var Codes
     *
     * @ORM\ManyToOne(targetEntity="Lynux\AssetBundle\Entity\Core\Codes")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="feature_fk", referencedColumnName="id")
     * })
     */
    private $featureFk;

    /**
     * @var Configurations
     *
     * @ORM\ManyToOne(targetEntity="Lynux\AssetBundle\Entity\Core\Configurations", inversedBy="features")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="configuration_fk", referencedColumnName="id")
     * })
     */
    private $configurationFk;

    /**
     * Set featureFk
     *
     * @param Lynux\AssetBundle\Entity\Core\Codes $featureFk
     * @return ConfigurationsFeatures
     */
    public function setFeatureFk(\Lynux\AssetBundle\Entity\Core\Codes $featureFk = null)
    {
        $this->featureFk = $featureFk;

        return $this;
    }

    /**
     * Get featureFk
     *
     * @return Lynux\AssetBundle\Entity\Core\Codes
     */
    public function getFeatureFk()
    {
        return $this->featureFk;
    }

    /**
     * Set configurationFk
     *
     * @param Lynux\AssetBundle\Entity\Core\Configurations $configurationFk
     * @return ConfigurationsFeatures
     */
    public function setConfigurationFk(\Lynux\AssetBundle\Entity\Core\Configurations $configurationFk = null)
    {
        $this->configurationFk = $configurationFk;

        return $this;
    }

    /**
     * Get configurationFk
     *
     * @return Lynux\AssetBundle\Entity\Core\Configurations
     */
    public function getConfigurationFk()
    {
        return $this->configurationFk;
    }
}

实体\ CoreCodes (ConfigurationsFeatures-> featureFk的潜在价值来源)

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

/**
 * Lynux\AssetBundle\Entity\Core\Codes
 *
 * @ORM\Table(name="core_codes")
 */
class Codes
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false, unique=true)
     * @ORM\Id
     * @Assert\NotBlank(message="ID cannot be blank!")
     * @Assert\Regex(pattern="/^\d+$/", match=true, message="ID must be an integer!")
     * @Assert\MinLength(limit=8, message="ID must be 8 digits in length!")
     * @Assert\MaxLength(limit=8, message="ID must be 8 digits in length!")
     */
    private $id;

    // ... various properties, not applicable to question ...

    /**
     * Set id
     *
     * @param integer $id
     * @return Codes
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

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

    // ... getters and setters for other properties ...
}

类型\ FormConfigurations

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FormConfigurations extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $features = $this->features;

        // ... builders for other properties ...

        $builder->add(
            'features',
            'entity',
            array(
                'class'         => 'LynuxAssetBundle:Core\Codes',
                'property_path' => false,
                'query_builder' => function(EntityRepository $er) use ($features)
                    {
                        return $er->createQueryBuilder('u')
                            ->where('u.submodule = :submodule')
                            ->setParameter('submodule', 'feature');
                    },
                'expanded' => true,
                'multiple' => true,
                'property' => 'title',));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'Lynux\AssetBundle\Entity\Core\Configurations',));
    }
}

控制器\ ConfigurationsController :: createAction()

public function createAction(Request $request)
{
    $config = $request->getSession()->get('configuration');
    $manage = $this->getDoctrine()->getEntityManager();

    $entity = new Configurations();
    $form   = $this->createForm(new FormConfigurations($features), $entity);
    $failed = null;

    $features = $manage
        ->getRepository('LynuxAssetBundle:Core\Codes')
        ->findBySubmodule('feature');

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

        if ($form->isValid()) {
            $status = $manage
                ->getRepository('LynuxAssetBundle:Core\Codes')
                ->findOneById(10103022);

            $entity->setToken($entity->getName());
            $entity->setStatusFk($status);
            $entity->setCreateAccountFk($this->getUser());

            $features = $form->get('features')->getData();
            foreach($features as $feature) {
                $addFeature = new ConfigurationsFeatures();
                $addFeature->setConfigurationFk($entity);
                $addFeature->setFeatureFk($feature);
                $manage->persist($addFeature);
            }
            $manage->persist($entity);
            $manage->flush();

            return $this->redirect($this->generateUrl(
                'CoreConfigurationsConfirm',
                array(
                    'code'  => 'create',
                    'token' => $entity->getToken(),)));
        } else {
            $failed = true;
        }
    }

控制器\ ConfigurationsController :: updateAction()

public function updateAction(Request $request, $token)
{
    $manage = $this->getDoctrine()->getEntityManager();
    $entity = $manage
        ->getRepository('LynuxAssetBundle:Core\Configurations')
        ->findOneByToken($token);

    $form   = $this->createForm(new FormConfigurations($features), $entity);

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

        if ($form->isValid()) {
            $currentFeatures = $manage
                ->getRepository('LynuxAssetBundle:Core\ConfigurationsFeatures')
                ->findByConfigurationFk($entity);
            foreach($currentFeatures as $currentFeature) {
                $manage->remove($currentFeature);
            }

            $features = $form->get('features')->getData();
            foreach($features as $feature) {
                $addFeature = new ConfigurationsFeatures();
                $addFeature->setConfigurationFk($entity);
                $addFeature->setFeatureFk($feature);
                $manage->persist($addFeature);
            }

            $manage->flush();
        }
    }

1 个答案:

答案 0 :(得分:4)

啊耐心和持久性......我想到,当我持久存储到数据库时,我正在将CoreCodes的集合转换为ConfigurationsFeatures的集合。同样,在显示表单时从ConfigurationsFeatures转换为CoreCodes是有意义的。

// ConfigurationsController::updateAction()

$formFeatures    = new ArrayCollection();
$currentFeatures = $entity->getFeatures();
foreach($currentFeatures as $feature) {
    $formFeatures->add($feature->getFeatureFk());
}

if ('POST' != $request->getMethod()) { // first time the form is loaded
    $form->get('features')->setData($formFeatures);
}