好的,我的更新工作得很好,但我使用了获取的数据并传递给了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.
}
}
答案 0 :(得分:1)
当此Post实体传递给表单构建器(作为createForm的第二个参数)时,Symfony将自动绑定来自 AppBundle:Post 实体的值。请注意,表单字段必须与Post Entity属性具有完全相同的名称。 新值(来自POST / GET请求)symfony2将在调用 handleRequest 方法时绑定到Post Entity。
注意:请不要通过构造函数将参数传递给formType - 这是一种不好的做法(在symfony2中)。请使用第三个构建器参数(选项)
问题:$ post_update应该是$ postUpdate,对吗?