这是我的数组$data
:
array(7) {
["form[username]"]=>
string(4) "test"
["form[email]"]=>
string(11) "test@123.sw"
["form[is_active]"]=>
string(1) "1"
["form[plainPassword][first]"]=>
string(0) ""
["form[plainPassword][second]"]=>
string(0) ""
["form[id]"]=>
string(1) "9"
["form[_token]"]=>
string(43) "A"
}
我将数据存储到我现有的实体User
中,如下所示:
$entity = $this->getDoctrine()->getRepository(User::class)->find($data['form[id]']);
$em = $this->getDoctrine()->getManager();
$entity->setUsername($data['form[username]']);
$entity->setEmail($data['form[email]']);
$em->flush();
这很好!
但是现在我实际上不想更新吸引用户,我想创建一个新用户。这是我的方法:
$entity = new User();
$entity = $data;
$em = $this->getDoctrine()->getManager();
$entity->setUsername($data['form[username]']);
$entity->setEmail($data['form[email]']);
$em->flush();
我得到了错误:
在数组上调用成员函数setUsername()
答案 0 :(得分:2)
删除$entity = $data;
并保留实体。
$user = new User();
$em = $this->getDoctrine()->getManager();
$user->setUsername($data['form[username]']);
$user->setEmail($data['form[email]']);
$em->persist($user);
$em->flush();
答案 1 :(得分:1)
建议使用symfony表单类型,而不是直接使用原始数据。这将使您免于噩梦。控制器中的newAction()和editAction()将使用相同的表单类型。
我在下面为您发布了一个示例:
class UserType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('username')
->add('email');
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'your User entity reference'
));
}
}
public function newAction(Request $request)
{
try
{
$user = new User();
$form = $this->createForm('path to your UserType', $user);
$form->handleRequest($request);
$form->submit($request->request->all());
if ($form->isSubmitted())
{
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
//your code
}
catch (\Exception $exception)
{
// return your exception
}
}
这样,您无需显式设置任何内容。数据会自动处理并提交。
此处的更多信息:https://symfony.com/doc/current/best_practices/forms.html