Symfony 3 - 编辑表单 - 使用db数据(数组)填充字段

时间:2016-12-07 10:49:29

标签: php forms symfony symfony-forms

我需要一个包含3个动态选择框(choicetypes)的表单,在表单提交后,它将作为序列化数组保存在数据库中。

我最终设法让它工作,但现在我在编辑项目时难以用数据库值填充下拉列表。

项目实体

<?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="projects")
 */
class Projects
{
    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $projectName;
    /**
     * @ORM\Column(type="array")
     */
    protected $frequency;
    /**
     * No database fields for these.
     * They are used just to populate the form fileds
     * and the serialized values are stored in the frequency field
     */
     protected $update;
     protected $every;
     protected $on;

    /*
     * Project Name
     */
    public function getProjectName()
    {
        return $this->projectName;
    }
    public function setProjectName($projectName)
    {
        $this->projectName = $projectName;
    }
    /*
     * Frequency
     */
    public function getFrequency()
    {
        return $this->frequency;
    }
    public function setFrequency($frequency)
    {
        $this->frequency = $frequency;
    }
    /*
     * Update
     */  
    public function getUpdate()
    {
        return $this->update;
    }
    public function setUpdate($update)
    {
        $this->update = $update;
    }
    /*
     * Every
     */  
    public function getEvery()
    {
        return $this->every;
    }
    public function setEvery($every)
    {
        $this->every = $every;
    }
    /*
     * On
     */  
    public function getOn()
    {
        return $this->on;
    }
    public function setOn($on)
    {
        $this->on = $on;
    }
}

项目控制器

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Projects;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

/**
 * Projects controller.
 */
class ProjectsController extends Controller
{
    /**
     * @Route("/projects/new", name="projects_new")
     */
    public function newAction(Request $request)
    {
        $project = new Projects();
        $form = $this->createForm('AppBundle\Form\ProjectsType', $project);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            // This is where the data get's saved in the frequency field
            $frequency = array(
                "update" => $project->getUpdate(),
                "every" => $project->getEvery(),
                "on" => $project->getOn()
            );
            $project->setFrequency($frequency);

            $em->persist($project);
            $em->flush($project);

            return $this->redirectToRoute('projects_show', array('id' => $project->getId()));
        }

        return $this->render('projects/new.html.twig', array(
            'project' => $project,
            'form' => $form->createView(),
        ));
    }

    /**
     * @Route("/projects/edit/{id}", name="projects_edit", requirements={"id": "\d+"})
     * @ParamConverter("id", class="AppBundle:Projects")
     */
    public function editAction(Request $request, Projects $project)
    {
        $editForm = $this->createForm('AppBundle\Form\ProjectsType', $project);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            // This is where the data get's saved in the frequency field
            $frequency = array(
                "update" => $project->getUpdate(),
                "every" => $project->getEvery(),
                "on" => $project->getOn()
            );
            $project->setFrequency($frequency);

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('projects_edit', array('id' => $project->getId()));
        }

        return $this->render('projects/edit.html.twig', array(
            'project' => $project,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
}

ProjectsType表格

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use AppBundle\Entity\Projects;

class ProjectsType extends AbstractType
{
    private function setUpdateChoice(Projects $project)
    {
        return $project->getFrequency()['update'];
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('projectName', null, array());

        $builder->add('update', ChoiceType::class, array(
                'label'         => 'Update',
                'attr'          => array(
                    'class' => 'update_selector',
                ),
                'choices' => array(
                    'Daily' => 'Daily',
                    'Weekly' => 'Weekly',
                    'Monthly' => 'Monthly'
                ),
                'data' => $this->setUpdateChoice($builder->getData())
            )
        );

        $addFrequencyEveryField = function (FormInterface $form, $update_val) {
            $choices = array();
            switch ($update_val) {
                case 'Daily':
                    $choices = array('1' => '1', '2' => '2');
                    break;

                case 'Weekly':
                    $choices = array('Week' => 'Week', '2 Weeks' => '2 Weeks');
                    break;

                case 'Monthly':
                    $choices = array('Month' => 'Month', '2 Months' => '2 Months');
                    break;

                default:
                    $choices = array();
                    break;
            }
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($addFrequencyEveryField) {
                $update = $event->getData()->getUpdate();
                $update_val = $update ? $update->getUpdate() : null;
                $addFrequencyEveryField($event->getForm(), $update_val);
            }
        );
        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) use ($addFrequencyEveryField) {
                $data = $event->getData();
                $update_val = array_key_exists('update', $data) ? $data['update'] : null;
                $addFrequencyEveryField($event->getForm(), $update_val);
            }
        );

        $addFrequencyOnField = function (FormInterface $form, $every_val) {
            $choicesOn = array();
            switch ($every_val) {
                case 'Week':
                    $choicesOn = array(
                        'Monday' => 'Monday',
                        'Tuesday' => 'Tuesday',
                        'Wednesday' => 'Wednesday',
                        'Thursday' => 'Thursday',
                        'Friday' => 'Friday',
                        'Saturday' => 'Saturday',
                        'Sunday' => 'Sunday',
                    );
                break;

                case 'Month':
                    $choicesOn = array(
                        '1' => '1',
                        '2' => '2',
                        '3' => '3',
                        '4' => '4',
                        '5' => '5',
                        '6' => '6',
                        '7' => '7',
                    );
                break;

                default:
                    $choicesOn = array();
                break;
            }

            $form->add('on', ChoiceType::class, array(
                'choices'     => $choicesOn,
            ));

        };
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($addFrequencyOnField) {
                $every = $event->getData()->getEvery();
                $every_val = $every ? $every->getEvery() : null;
                $addFrequencyOnField($event->getForm(), $every_val);
            }
        );
        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) use ($addFrequencyOnField) {
                $data = $event->getData();
                $every_val = array_key_exists('every', $data) ? $data['every'] : null;
                $addFrequencyOnField($event->getForm(), $every_val);
            }
        );
    }
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Projects'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_projects';
    }
}

最后,编辑模板包含ajax

{% extends 'base.html.twig' %}
{% block body %}
    {% block content %}
      <h1>Edit Project</h1>

      {{ form_start(edit_form) }}
          {{ form_widget(edit_form) }}
          <input type="submit" value="Edit" />
      {{ form_end(edit_form) }}
    {% endblock content %}


    {% block javascripts %}
        <script>
          var $update =       $('#appbundle_projects_update');
          var $every =        $('#appbundle_projects_every');
          var $on_selector =  $('#appbundle_projects_on');

          // When update gets selected ...
          $update.change(function() {
            $every.html('');
            // ... retrieve the corresponding form.
            var $form = $(this).closest('form');
            // Simulate form data, but only include the selected update value.
            var data = {};
            data[$update.attr('name')] = $update.val();
            // Submit data via AJAX to the form's action path.
            $.ajax({
              url : $form.attr('action'),
              type: $form.attr('method'),
              data : data,
              success: function(html) {
                var options = $(html).find('#appbundle_projects_every option');
                for (var i=0, total = options.length; i < total; i++) {
                    $every.append(options[i]);
                }
              }
            });
          });
          // // When every gets selected ...
          $every.change(function() {
            $on_selector.html('');
            // ... retrieve the corresponding form.
            var $form = $(this).closest('form');
            // Simulate form data, but only include the selected every value.
            var data = {};
            data[$every.attr('name')] = $every.val();
            // Submit data via AJAX to the form's action path.
            $.ajax({
              url : $form.attr('action'),
              type: $form.attr('method'),
              data : data,
              success: function(html) {
                  var options = $(html).find('#appbundle_projects_on option');
                  for (var i=0, total = options.length; i < total; i++) {
                      $on_selector.append(options[i]);
                  }
              }
            });
          });
        </script>
    {% endblock javascripts %}
{% endblock %}

我可以使用setUpdateChoice()在更新字段中设置所选值,并将返回值分配给ProjectsType中的ChoiceType::class data。但是,这对every select或另一个PRE_SET_DATA听众返回null没有任何影响。

我也尝试过与上面相同的其他两个字段,但是在监听器中呈现的字段导致错误no such field(或类似的东西)

我还尝试从控制器中的频率中获取值,并在呈现表单之前使用setUpdate()setEvery()setOn(),从而生成{{1} }

这是编辑项目时当前呈现的表单的方式:

initial render

我需要像这样填充:

enter image description here

我将非常感谢任何有关如何解决这个问题的想法/建议/示例。

谢谢

PS。如果我省略了某些内容,请告诉我,我会更新我的问题。

更新

感谢 Constantin&#39> 答案,我设法在控制器中设置字段数据,执行以下操作:

You can't modify a form that has already been submitted.

1 个答案:

答案 0 :(得分:2)

由于我没有足够的时间阅读您的所有帖子,因此不确定这会对您有所帮助。

首先(仅供您参考),您可以在表单中使用3个字段(更新,每个及以上)选项'mapped'=&gt; false并从您的实体中删除这3个字段(这是与您的实体而不是DB的映射)。

然后,您可以在控制器中访问它们 $ editForm-&GT;获得( '更新') - &GT;的getData(); //或setData($ data);

但是,如果你愿意,你可以保留这些属性,如果它对你来说更方便的话。  但是如果你保留它们,请确保它们始终反映你的频率属性中的数据。

接下来,我在您的编辑控制器中看到,在创建表单之前,您不会设置3个字段的值。 由于这些字段未映射(这次使用数据库),因此在获取实体时它们将为null(这是在编辑控制器中使用paramConverter完成的)。 因此,在将$ project作为创建表单中的参数传递之前,必须设置它们(反序列化或其他)。

希望这对你有帮助!