- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我需要一个带有 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.
这是编辑项目时表单当前呈现的方式:
我需要这样填充它:
任何关于我如何解决这个问题的想法/建议/示例都将不胜感激。
谢谢
附言。如果我遗漏了什么,请告诉我,我会更新我的问题。
感谢 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 个字段(update
、every
和 on
) 选项 '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/
我在 mongodb 中的玩家和锦标赛之间存在多对多关系。 我希望能够一次将许多玩家添加到锦标赛中。如果没有 ajax,这很简单,但我们有一个包含数千名玩家的数据库,因此表单选择变得巨大。 我们想为此
这个问题已经有答案了: When should I use html's and when spring's in Spring MVC web app? (3 个回答) 已关闭 6 年前。 我正
我正在 C++ Builder XE4 上使用 VCL。 我有以下组件。 FormMain 具有 TButton *B_select; FormSelect(或DialogSelect)具有 TCom
如何在不影响表单控件的情况下更改表单的 alphablend? 德尔福XE7 最佳答案 此问题的一个解决方案是使用多设备应用程序(如果无法使用VCL)。 如果您需要保留透明的TForm,只需更改属性T
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我正在尝试扩展 Django 注册以包含我自己的注册表单。原则上这是相当简单的。我只需要编写自己的表单( CustomRegistrationForm ),它是原始表单( RegistrationFo
我正在尝试为我的网站实现聊天功能。为了做到这一点,我遵循了以下教程:https://channels.readthedocs.io/en/latest/tutorial/ 然后我稍微更改了代码以实现它
有一个问题,我需要用一个 html 表单提交两个相互关联的模型表单。我知道如何提交两个单独的表格,但是在相关模型表格的情况下外键让我发疯。 问题是,第二个表单应该用外键填充字段到第一个表单的实例。 在
我正在创建一个工具,允许某人输入食谱,然后将其保存为 XML 文件,我已经创建了 XSD,但我想知道如何在我的网页上制作一个表单以允许用户输入他们的食谱并遵守模式。我一直在研究 Ajax 和 Jque
在 .net win 表单(如 asp.net web 表单)中是否有可用的验证控件? 因为很难为我的每个控件设置正确的条件,所以我的表单中也有很多重复的代码。 正确的做法是什么? 最佳答案 看看这个
我有一个简短的问题。我正在学习如何使用 javascript 制作注册表,发现此链接非常有用。 http://www.w3resource.com/javascript/form/javascript
我正在开发一个项目,该项目将使用循环将许多表单添加到 mysql 数据库中。在 javascript 部分中,我无法让 var i 在函数 updatesum() 中工作。有人可以帮我吗? 我试图避免
在我的应用程序上有一个包含 2 个字段和一个保存按钮的表单。 在我的 onClick 结束时我需要什么来将光标返回到第一个字段。 我有这个来清除它们 txtData.setText("
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
<input type="text" name="textfield" onKeyPress="javascript:alert(event.
我正在构建的网站有一个登录表单,作为所有其他模板扩展的 base.html 模板的一部分;因此,我需要以某种方式处理每个页面上的登录/注销逻辑。 目前每个页面都在单独的 View 中加载,那么实现它的
我有一个表单类,看起来像.. #forms.py class ExampleForm(forms.Form): color = forms.CharField(max_length=25)
有没有办法在表单定义中给表单一个特殊的错误渲染函数?在 customizing-the-error-list-format 下的文档中它展示了如何为表单提供特殊的错误呈现函数,但似乎您必须在实例化表单
我正在处理由多个页面组成的表单,我想解决验证问题。 当我点击提交按钮时,当前页面上的所有字段都会在下方显示错误消息,但是如果我更改页面,那么我需要再次点击提交,因为这些字段未设置为已触摸。 如果我可以
是否可以附加到继承表单的 exclude 或 widgets 变量? 到目前为止,我有以下设置。 class AddPropertyForm(forms.ModelForm): num_mon
我是一名优秀的程序员,十分优秀!