I'am working on symfony REST API and currently i stopped at PUT request to edit data. I don't know where either search for bug.
My code look like this.
Controller.php
/**
* User update
*
* @Rest\Put("/users/{id}", name="user_update")
* @Rest\View()
* @param Request $request
* @param $id
* @param Users $restUser
*
*
*
* @return View
*/
public function updateUserAction( Request $request, $id, Users $restUser )
{
$results = [];
$user = $this->em->getRepository( User::class )
->find( $id )
;
/**
* Data to update user
*/
if ( ! $user )
{
$results[ 'message' ] = sprintf( 'No users found with {%s} ID', $id );
$results[ 'status' ] = 'failure';
return View::create( $results );
}
$results[ 'beforeUpdate' ] = $user;
$newData = $request->request->all();
/**
* Try to update
*/
try
{
$form = $this->createForm( UserType::class, $user );
$form->submit( $newData );
if ( $form->isValid() )
{
$results[ 'status' ] = 'success';
$results[ 'message' ] = 'Pomyślnie zaaktualizowsano użytkownika';
$this->em->persist( $user );
$this->em->flush();
}
$results[ 'errors' ] = $form->getErrors( FALSE, TRUE );
}
catch( \Exception $exception )
{
$results[ 'status' ] = 'failure';
$results[ 'message' ] = 'Wystąpił błąd przy aktualizacji';
$results[ 'message_exception' ] = $exception->getMessage();
}
/**
* Get BODY of request
*/
$results[ 'sentData' ] = $newData;
return View::create($results);
}
And UserFormType.php
class UserType extends AbstractType implements FormTypeInterface{
public function configureOptions( OptionsResolver $resolver )
{
$resolver->setDefaults( [
'data_class' => User::class,
'allow_extra_fields' => TRUE,
'csrf_protection' => FALSE,
] );
}
}
Basic question is that I do everything ok? Im new to Symfony and try my best everytime i try to do something i think i get each available error.
buildFormmethod. Also your blatant misuse of the form suggests, you only want the validator (which you could dependency-inject). the "allow_extra_fields" only avoids the error message when a form gets data for different fields than it expects.$newData? because I think that's probably the reason. I'm not sure what the@Rest/PutAnnotation does. If it doesn't contribute to this, then you're probably on the wrong track: apparently "PUT" data isn't read into theRequestas expected, but instead must be parsed by yourself, see: stackoverflow.com/questions/36858279/… and codereviewvideos.com/course/… (the second is for json though).