Php 使用ArrayCollection编辑表单

Php 使用ArrayCollection编辑表单,php,forms,symfony,symfony-forms,Php,Forms,Symfony,Symfony Forms,快速解释主题: 一个“项目”可以有几个“活动” 我必须根据需要同时创建尽可能多的“活动”(你点击一个按钮“添加活动”,你会得到一个新行,这意味着一个新活动)。我通过在我的字段上进行集合来做到这一点 以下是formBuilder的代码: (我知道我可以做得更短,但重构将在稍后进行。) 因此,这项工作目前正在进行,与他的关联控制器一起添加我的活动,如下所示: /** *@param integer$projectId *@param string$projectType *@param in

快速解释主题:

  • 一个“项目”可以有几个“活动”

  • 我必须根据需要同时创建尽可能多的“活动”(你点击一个按钮“添加活动”,你会得到一个新行,这意味着一个新活动)。我通过在我的字段上进行集合来做到这一点

以下是formBuilder的代码:

(我知道我可以做得更短,但重构将在稍后进行。)

因此,这项工作目前正在进行,与他的关联控制器一起添加我的活动,如下所示:

/**
*@param integer$projectId
*@param string$projectType
*@param integer$rdId
*
*@return\Symfony\Component\HttpFoundation\Response
*/
公共函数createNewActivityAction($projectId、$projectType、$rdId)
{
$activity=新活动();
$request=$this->get('request_stack')->getCurrentRequest();
$form=$this->createForm(CreateNewActivitiesType::class,$activity);
$form->handleRequest($request);
$em=$this->getDoctrine()->getManager();
如果($form->isSubmitted()&&&$form->isValid()){
$rdassociated=$em->getRepository('CoreBundle:DecisionStatement')->findOneBy(['id'=>$rdId]);
$formData=$form->getData();
$yearList=$formData->getYear();
$aeAmountList=$formData->getAeAmount();
$afNameList=$formData->getAfName();
$amountSpentList=$formData->getamountspend();
对于($i=0;$igetRepository('CoreBundle:Activities')->getExistingActivityWithoutIdentifier(
$yearDatetime,
美元
);
如果($existingActivity){
/**
*@var活动$currentActivity
*/
$currentActivity=$existingActivity[0];
$currentActivity->setAeAmount(
$currentActivity->getAeAmount()+$aeAmountList[$i]
);
$currentActivity->setamount花费(
$currentActivity->GetAmountSpend()+$amountSpentList[$i]
);
$em->persist($currentActivity);
}否则{
$newActivity=新活动();
$newActivity->setYear($yearDatetime)
->setAeAmount($aeAmountList[$i])
->setAfName($afNameList[$i])
->SetAmountExplored($amountSpentList[$i])
->setafreceivement(假)
->setDecisionStatement($rds)
->setPeopleByMonth(0);
$em->persist($newActivity);
}
}
$em->flush();
返回$this->redirectToRoute('rd\u show\u activities',数组(
“rdId”=>$rdId,
“projectType”=>$projectType,
“projectId”=>$projectId
));
}
返回$this->render('@Core/html/13 edit activite.html.twig',数组(
“页面”=>“活动创建”,
'createActivitiesForm'=>$form->createView(),
“projectParentId”=>$projectId,
“projectParentType”=>$projectType,
“rdId”=>$rdId
));
}
以下是提交活动表单时var_转储的屏幕截图:

但我的问题从哪里开始,就是我想编辑的时候,因为我的表单是基于实体“活动”的。但是我想编辑给定项目的所有现有“活动”,我将有一个包含我的“活动”对象的数组(由findBy方法找到),因此我无法将数组传递到表单中,这将导致错误。
如何将多个“活动”对象的数组转换为一个“活动”对象?

我不明白为什么只有一个包含多个集合的“活动”对象。 您应该创建一个包含多个活动的对象活动。 每个活动只有一个属性“年”、“花费金额”。。。 当您使用适当的表单编辑对象“活动”时,您将能够编辑与此对象链接的每个活动

嵌入表单集合 要正确处理此类问题,您需要在Symfony中构建一个

  • 一个“项目”可以有几个“活动”
  • 我必须根据需要同时创建尽可能多的“活动”[…]
  • 首先,您需要构建一个项目实体,该实体将包含作为条令阵列集合的所有活动,如下所示:

    src/AppBundle/Entity/Project.php

    src/AppBundle/Form/Type/ProjectType.php


    然后,您需要使用Twig和JavaScript,让用户能够动态地将活动添加到项目中,以利用
    prototype
    变量。

    我已经考虑了您所做的所有评论,并决定回顾整个过程

    DecisionStatement.php:

    • 在u_construct()方法中添加了一个新的ArrayCollection,用于与给定DecisionStatement关联的活动
    • 返回关联活动的方法已经在这里了
    文档=新的ArrayCollection(); $this->activitiesassociated=newarraycollection(); }

    /**
     * Get activitiesAffiliated
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getActivitiesAffiliated()
    {
        return $this->activitiesAffiliated;
    }
    
    我已经创建了一个新的表单类型(DecisionStatementType.php),以拥有我的表单集合:

    下面是“子表单”,newActivityType.php:

    在我的视图的DOM中,我现在有:

    那么,这有点干净吗?

    请提供
    /**
         * @param integer $projectId
         * @param string $projectType
         * @param integer $rdId
         *
         * @return \Symfony\Component\HttpFoundation\Response
         */
        public function createNewActivityAction($projectId, $projectType, $rdId)
        {
            $activity = new Activities();
            $request = $this->get('request_stack')->getCurrentRequest();
    
            $form = $this->createForm(CreateNewActivitiesType::class, $activity);
            $form->handleRequest($request);
            $em = $this->getDoctrine()->getManager();
    
    
            if ($form->isSubmitted() && $form->isValid()) {
                $rdAffiliated = $em->getRepository('CoreBundle:DecisionStatement')->findOneBy(['id' => $rdId]);
    
                $formData = $form->getData();
                $yearList = $formData->getYear();
                $aeAmountList = $formData->getAeAmount();
                $afNameList = $formData->getAfName();
                $amountSpentList = $formData->getAmountSpent();
    
                for ($i = 0; $i < count($yearList); $i++) {
                    $yearDatetime = new DateTime($yearList[$i] . '-01-01 00:00:00');
                    $existingActivity = $em->getRepository('CoreBundle:Activities')->getExistingActivityWithoutIdentifier(
                        $yearDatetime,
                        $rdAffiliated
                    );
    
                    if ($existingActivity) {
                        /**
                         * @var Activities $currentActivity
                         */
                        $currentActivity = $existingActivity[0];
                        $currentActivity->setAeAmount(
                            $currentActivity->getAeAmount() + $aeAmountList[$i]
                        );
                        $currentActivity->setAmountSpent(
                            $currentActivity->getAmountSpent() + $amountSpentList[$i]
                        );
    
                        $em->persist($currentActivity);
                    } else {
                        $newActivity = new Activities();
                        $newActivity->setYear($yearDatetime)
                            ->setAeAmount($aeAmountList[$i])
                            ->setAfName($afNameList[$i])
                            ->setAmountSpent($amountSpentList[$i])
                            ->setAfReception(false)
                            ->setDecisionStatement($rdAffiliated)
                            ->setPeopleByMonth(0);
    
                        $em->persist($newActivity);
                    }
                }
    
                $em->flush();
    
                return $this->redirectToRoute('rd_show_activities', array(
                    'rdId'          => $rdId,
                    'projectType'   => $projectType,
                    'projectId'     => $projectId
                ));
            }
    
            return $this->render('@Core/html/13-edit-activite.html.twig', array(
                'page'                 => 'activities_creation',
                'createActivitiesForm' => $form->createView(),
                'projectParentId'      => $projectId,
                'projectParentType'    => $projectType,
                'rdId'                 => $rdId
            ));
        }
    
    namespace AppBundle\Entity;
    
    use Doctrine\Common\Collections\ArrayCollection;
    
    class Project
    {
    
        protected $activities;
    
        public function __construct()
        {
            $this->activities = new ArrayCollection();
        }
    
        public function getTags()
        {
            return $this->tags;
        }
    }
    
    namespace AppBundle\Form\Type;
    
    use AppBundle\Entity\Project;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    
    class ProjectType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('tags', CollectionType::class, array(
                'entry_type' => ActivitiesType::class,
                'allow_add'    => true,
            ));
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => Project::class,
            ));
        }
    }
    
    /**
     * Get activitiesAffiliated
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getActivitiesAffiliated()
    {
        return $this->activitiesAffiliated;
    }
    
    use CoreBundle\Entity\DecisionStatement;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    
    class DecisionStatementType extends AbstractType
    {
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add(
                    'activitiesAffiliated',
                    CollectionType::class,
                    array(
                        'entry_type'    => NewActivityType::class,
                        'allow_add'     => true,
                        'allow_delete'  => true
                    )
                )
            ;
        }
    
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => DecisionStatement::class
            ));
        }
    
        /**
         * {@inheritdoc}
         */
        public function getBlockPrefix()
        {
            return 'corebundle_collection_decisionstatement';
        }
    }
    
    use CoreBundle\Entity\Activities;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\DateType;
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    
    class NewActivityType extends AbstractType
    {
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add(
                    'aeAmount',
                    TextType::class,
                    array(
                        'label'         => 'Montant de l\'AE',
                        'label_attr'    => array(
                            'class'     => 'aeAmount visuallyhidden'
                        ),
                        'attr'      => array(
                            'placeholder'   => '80 000 €'
                        ),
                        'required'      => true
                    )
                )
                ->add(
                    'amountSpent',
                    TextType::class,
                    array(
                        'label'         => 'RDP : ',
                        'label_attr'    => array(
                            'class'     => 'amountSpent visuallyhidden'
                        ),
                        'attr'      => array(
                            'placeholder'   => '35 000 €'
                        ),
                        'required'      => true,
                    )
                )
                ->add(
                    'afName',
                    TextType::class,
                    array(
                        'required'      => true,
                        'label'         => 'AF : ',
                        'label_attr'    => array(
                            'class'     => 'afName visuallyhidden',
                        ),
                        'attr'      => array(
                            'placeholder'   => 'AERT-496'
                        )
                    )
                )
            ;
        }
    
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'CoreBundle\Entity\Activities'
            ));
        }
    
        /**
         * {@inheritdoc}
         */
        public function getBlockPrefix()
        {
            return 'corebundle_collection_activities';
        }
    }