gpt4 book ai didi

forms - 使用获取数据来预填表单

转载 作者:行者123 更新时间:2023-12-04 18:19:29 25 4
gpt4 key购买 nike

我想在 symfony2 中预填表单域。网址看起来像这样

http://localhost/Symfony/web/app_dev.php/clearance/new?projectId=6

我现在想将表单中的 projectId 设置为 6。

这是我的 Controller 代码
 public function newclearanceAction(){
$request = $this->getRequest();
$id = $request->query->get('projectId');

echo $id; //this works, but how to send it to the form?????

$clearance = new Clearance();
$form = $this->createForm(new ClearanceType(), $clearance);

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

if($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($clearance);
$em->flush();
return $this->redirect($this->generateUrl('MyReportBundle_project_list'));
}
}
return $this->render('MyReportBundle:Clearance:new.html.twig',array('form'=>$form->createView()));

这是表单 View 的代码
<form action="{{ path('MyReportBundle_clearance_new') }}" method="post" >
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" />
</form>

谢谢你的帮助!

最佳答案

这取决于您的清关实体是否有与之相关的项目。如果是这样,您可以执行以下操作:

$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();
$project = $em->getRepository("MyReportBundle:Project")->find($id)
$clearance = new Clearance();
$clearance->setProject($project);
$form = $this->createForm(new ClearanceType(), $clearance);

这将在清除对象上设置项目并将其传递给表单。

目前,您无法在 Symfony2 中为实体创建隐藏字段,因此我当前的解决方法是创建一个查询构建器实例并将其传递给表单,这样当您拥有 100 个项目时,项目的表单选择不会变得荒谬。要在我添加的操作中执行此操作:
$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();

$repo = $em->getRepository("MyReportBundle:Project");
$project = $repo->find($id)
//create the query builder
$query_builder = $repo->createQueryBuilder('p')
->where('p.id = :id')
->setParameter('id', $project->getId());

$clearance = new Clearance();
$clearance->setProject($project);
//pass it through
$form = $this->createForm(new ClearanceType($query_builder), $clearance);

并在表单类中:
protected $query_builder;

public function __construct($query_builder)
{
$this->query_builder = $query_builder;
}

public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('Your field')
// all other fields
// Then below the query builder to limit to one project
->add('project', 'entity', array(
'class' => 'MyReportBundle:Project',
'query_builder' => $this->query_builder
))
;
}

关于forms - 使用获取数据来预填表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10979135/

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