gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:01:38 24 4
gpt4 key购买 nike

我需要一个带有 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(),
));
}
}

项目类型表格

<?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() 在更新字段中设置选定值并将返回值赋给 ChoiceType::class data在项目类型中。但是,这对 every select 没有任何影响。或者另一个,PRE_SET_DATA听众返回 null .

我也对其他两个字段进行了与上述相同的尝试,但是在监听器中呈现这些字段会导致错误 no such field (或类似的东西)

我还尝试从 Controller 中的频率获取值并使用 setUpdate() , setEvery()setOn()在呈现表单之前,导致 You can't modify a form that has already been submitted.

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

initial render

我需要这样填充它:

enter image description here

任何关于我如何解决这个问题的想法/建议/示例都将不胜感激。

谢谢

附言。如果我遗漏了什么,请告诉我,我会更新我的问题。

更新

感谢 Constantin 的回答,我已经设法在 Controller 中设置字段数据,执行以下操作:

  public function editAction(Request $request, Projects $project)
{
$project->setUpdate($project->getFrequency()['update']);
$project->setEvery($project->getFrequency()['every']);
$project->setOn($project->getFrequency()['on']);

$editForm = $this->createForm('AppBundle\Form\ProjectsType', $project);
$editForm->handleRequest($request);

if ($editForm->isSubmitted() && $editForm->isValid()) {
$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(),
));
}

最佳答案

不确定这是否对您有帮助,因为我没有足够的时间阅读您所有的帖子。

首先(仅供引用),您可以在表单中使用 3 个字段(updateeveryon) 选项 'mapped' => false 并从您的实体中删除这 3 个字段(这是与您的实体而非数据库的映射)。

然后您可以在您的 Controller 中使用

访问它们
$editForm->get('update')->getData(); //or setData( $data );

当然,如果您愿意并且对您来说更方便的话,您可以保留这些属性。但如果您保留它们,请确保它们始终反射(reflect)您的频率属性中的数据。

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

希望对您有所帮助!

关于php - Symfony 3 - 编辑表单 - 用数据库数据(数组)填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com