I'm creating a simple CRUD for managing users of one application. Users are created and managed by FOSUserBundle
. In addition I do not allow anyone to edit/change the username
and the email
so I do not show these fields in the form being edited. This is the code with which I'm handling the editing:
// Create the form and set the right data
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($id);
$form = $this->createForm(new UserType(), $user, array(
'action' => $this->generateUrl('update-user', array('id' => $id)),
'method' => 'POST',
));
return array(
'form' => $form->createView(),
'user' => $user
);
}
// Perform the update action and do the rest of the logic
public function updateAction(Request $request, $id = NULL)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository("UserBundle:User")->find($id);
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
$response = array();
$response['status'] = TRUE;
if ($form->isValid())
{
$userManager = $this->container->get('fos_user.user_manager');
$userManager->updateUser($user);
$response['message'] = $this->get('translator')->trans('update.success', array('%element%' => 'el usuario'));
}
else
{
$response['message'] = $this->get('translator')->trans('update.fail', array('%element%' => 'el usuario'));
$response['error'] = $this->getFormErrors($form);
$this->get('ladybug')->log($response['error']);
$response['status'] = FALSE;
}
return new JsonResponse($response);
}
But since username
and email
fields are not present and somehow they are getting to the update action, where these fields are updated with blank values. The only thing I can think to solve this problem is to delete this parameters from the request before making the handleRequest
but I have no idea how, any help?
PS: Any ideas better than mine or any suggestion on the code is welcome!!
1st test
I thought the problem is the fos_user.user_manager
. Why? Take a look at this:
// Unset non editable fields from $request
unset(
$request->get('user')['username'], $request->get('user')['email']
);
// Continue the flow
$form->handleRequest($request);
But surprisingly this throws this "weird" error:
An exception occurred while executing 'UPDATE fos_user SET username = ?, username_canonical = ?, email = ?, email_canonical = ?, password = ?, roles = ?, updatedAt = ? WHERE id = ?' with params [null, null, null, null, "tD9GEdMpFT3j75fPeoEkus00ge+xmrgQhaXntNstz7taSx4KAdqpKGhxfC3czHaNr17pGfrigylT29iyTfcZNA==", "a:1:{i:0;s:16:\"ROLE_PROFILE_TWO\";}", "2014-09-13 21:01:10", 4]:
Which leads to this:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'UNIQ_957A647992FC23A8'
Is the problem there? username
is unique and, I don't know why yet, still trying to set username
and email
with blank values causing the error above.
Any suggestions?