Symfony - 控制器编辑操作



我在控制器中定义了表单,并设置了编辑/更新我可以通过ID找到的特定字段的功能。我找不到我做错了什么。

public function getUserEdit(Request $request)
{
$form = $this->createFormBuilder()
->add('firstName', TextType::class, array('label' => 'First Name*', 'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array('label' => 'Send', 'attr' => [
'class' => 'btn btn-primary action-save'
]))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$firstName = $data['firstName'];
$this->container->get('user')->editUser($firstName);
}
return $this->success();
}

服务

public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if(empty($editUsers)) {
$editUsers = new User();
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
}

>Symfony在按主键(通常id(搜索时returns单个对象find,然后您可以检查是否存在返回单个Entity(在本例中为User(,以便使用insteance进行检查。

public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if($editUsers insteance User) { // here just check 
//$editUsers = new User(); // here You don't need create new object of class User, just remove
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
else {
// do something if you need
}
}

相关内容

  • 没有找到相关文章

最新更新