简体   繁体   English

Symfony2:如何从Controller中的表单获取默认值?

[英]Symfony2 : How to get a default value from a form in Controller?

I want to get a default value from a form. 我想从表单获取默认值。 For example, I rendered a select box form by using the following code: 例如,我使用以下代码呈现了一个选择框表单:

$form = $this->createFormBuilder()
            ->add('patient', 'choice', array(
                'choices' => $patientArray,
                'required' => true,
                'label' => false
            ))
            ->getForm();

The patientArray values are composed of patient_id and patient_name : patientArray值由patient_idpatient_name组成:

array(
    '2' => 'John'
    '3' => 'Jane'
);

So, I would like to get the default value which is 2 => John without submit a button and without choosing the select form. 因此,我想获得默认值2 => John而无需提交按钮,也无需选择选择表单。 What is a proper way to achieve this in a controller? 在控制器中实现此目标的正确方法是什么?

You need to set default value in your entity . 您需要在您的entity设置默认值。 You can use __construct() method for it. 您可以使用__construct()方法。

    // create a task and give it some dummy data for this example
    $task = new Task();
    $task->setTask('Write a blog post');
    $task->setDueDate(new \DateTime('tomorrow'));

    $form = $this->createFormBuilder($task)
        ->add('task', 'text')
        ->add('dueDate', 'date')
        ->add('save', 'submit')
        ->getForm();

    return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));

In this example task field has Write a blog post value by default. 在此示例中, task字段默认具有“ Write a blog post值。 You also can do this in __construct() , and you don't need use setter, but it is't necessary. 您也可以在__construct()执行此操作,并且不需要使用setter,但这不是必需的。

But better use __construct instead setter like: 但最好使用__construct而不是setter例如:

// src/Acme/TaskBundle/Entity/Task.php
namespace Acme\TaskBundle\Entity;

class Task
{
    protected $task;

    protected $dueDate;

    public function __construct() {
        $this->task = 'Write a blog post';
    }

and you always have default value when create Task object 并且在创建Task对象时始终具有默认值

Ps You can find more examples in forms documentation Ps您可以在表单文档中找到更多示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM