根据从实体提取的数据设置默认表单字段


Set default form fields based on fetched data from entity

好的,我的更新运行得很好,但我使用了提取的数据并将其传递给formclass构造函数,在类中我使用了"data",这样当我想进行更新时,我可以在表单中设置默认值。这是有效的,但不是应该做的。。。这是我的密码。。

控制器:

/**
 * @Route("/post/{slug}/update", name="update_post")
 */
public function updatePostAction(Request $request, $slug) {
    if(!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
        throw $this->createAccessDeniedException();
    }
    $em = $this->getDoctrine()->getManager();
    $postUpdate = $em->getRepository('AppBundle:Post')
        ->findOneByName($slug);
    $name = $post_update->getName();
    $content = $post_update->getContent();
    $visible = $post_update->getVisible();
    $form = $this->createForm(new PostForm($name, $content, $visible), $postUpdate, array(
        'action' => 'update',
        'method' => 'POST'
    ));
    $form->handleRequest($request);
    if($form->isValid()) {
        $em->flush();
    }
    return $this->render (
      'create/post.html.twig', array(
         'form' => $form->createView()
        ));
}

表单类别:

class PostForm extends AbstractType {
private $name;
private $content;
private $visible;
private $button = "Create Post";
public function __construct($name="", $content="", $visible=array(1,0)) {
    $this->name = $name;
    $this->content = $content;
    $this->visible = $visible;
    if ($this->name!="") {
        $this->button = "Update Post";
    }
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text', array(
            'data' => $this->name
        ))
        ->add('content', 'textarea', array(
            'data' => $this->content
        ))
        ->add('visible', 'choice', array(
            'choices' => array(
                1 => 1,
                0 => 0
            )
        ))
        ->add('publishDate', 'date', array(
            'input' => 'datetime',
            'widget' => 'choice'
        ))
        ->add('belongToPage', 'entity', array(
            'class' => 'AppBundle:Page',
            'property' => 'name',
            'choice_label' => 'getName', //getName is function from class Page which returns name of page(s)
        ))
        ->add('save', 'submit', array('label' => $this->button));
}
public function getName()
{
    // TODO: Implement getName() method.
}
}

Symfony将在将此Post实体传递给表单生成器时(作为createForm的第二个参数)自动绑定AppBundle:Post实体中的值。请注意,表单字段的名称必须与Post Entity属性完全相同。在handleRequest方法的调用过程中,新值(来自POST/GET请求)symfony2将绑定到POST实体。

注意:请不要通过构造函数将参数传递给formType-这是一种糟糕的做法(在symfony2中)。请使用第三个生成器参数(选项)

问题:$post_update应该是$postUpdate,对吗?