i do this steps:
1.) I call my api endpoint: http://localhost:8000/api/addrole
2.) This is the controller called:
/**
* #Rest\Post("/addrole")
*/
public function addRoleAction(Request $request)
{
$userid = $request->get('userid');
$assignedRole = $request->get('role');
$assignedRoleName = $request->get('role_name');
// Obtain the User
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->find($userid);
// If the user gives not exists, throw error
if (!$user) {
throw new HttpException (400,"No se ha encontrado el usuario solicitado: " .$userid);
}
// obtain present user roles
$presentRoles = $user->getRoles();
$role_length = count($presentRoles);
$role_list = array();
for ($i=0; $i <$role_length ; $i++) {
array_push($role_list,$presentRoles[$i]->getRole());
}
if(!in_array($assignedRole,$role_list)){
$role = $em->getRepository('AppBundle:Role')
->findOneBy(array('role' => $assignedRole));
$user->addRole($role);
$em->persist($user); // persisting only the user.
$em->flush();
$data = array(
'result' => 'Rol asignado',
'user' => $user,
'assignedRole' => $assignedRole
);
return $data;
} else {
throw new HttpException (400,"El usuario ya posee el rol solicitado");
}
}
3.) The data on this step:
$user->addRole($role);
$em->persist($user); // persisting only the user.
$em->flush();
is saving the data on the DB.
4.) this is the response:
{
"error": {
"code": 500,
"message": "Internal Server Error",
"exception": [
{
"message": "A circular reference has been detected (configured limit: 1).",
"class": "Symfony\\Component\\Serializer\\Exception\\CircularReferenceException",...
5.) if i comment this line:
//$em->flush();
the data obviosly don't save, but the error is not throwed.
Any clue about this?
Finally i found the error.
The problem is on this code:
...
post $em->flush();
this: $data = array('result' => 'Rol asignado', 'user' => $user, 'assignedRole' => $assignedRole );
return $data;
After the flush i called the $user object. This generate the problem.
Thanks to all.
Related
I tested my code in production mode and I am facing a 500 error which I don't understand since it occurs in production mode only and not in dev mode, moreover I have no error logs that occur manifest… from what I could tell it would come from $read since when I comment out the manager->flush(); the error disappears. However, the site database table is identical locally or on my server… here is the code in question (I leave the github link of the project below so that you can browse the different files in case it comes from elsewhere)
#[Route('/forum/topic/{id}', name: 'forum.topic', methods: ['GET', 'POST'])]
public function index(
ForumTopic $topic,
MemberRepository $memberRepository,
ReadingRepository $readingRepository,
ForumForumRepository $repositoryCategory,
ForumForumRepository $repositoryForum,
ForumTopicRepository $repositoryTopic,
ForumPostRepository $repositoryPost,
PaginatorInterface $paginator,
EntityManagerInterface $manager,
Request $request
): Response
{
if($this->getUser())
{
$user = $this->getUser();
$reading = $readingRepository->findOneBy(['user' => $user, 'topic' => $topic]);
if ($reading === null) {
$reading = new Reading();
$reading->setUser($user);
$reading->setTopic($topic);
}
$reading->setReadAt((new \DateTimeImmutable()));
$manager->persist($reading);
$manager->flush();
$roles = $this->getUser()->getRoles();
if (in_array('ROLE_MODERATOR', $roles)) {
$categories = $repositoryCategory->findAll();
$forums = $repositoryForum->findAll();
}
}
/**
* On récupère la liste des topics dans un arrray en fixant une limite à 20
* #var array
*/
$categories = null;
$forums = null;
$topic = $repositoryTopic->find(['id' => $topic]);
// t = topic m = member mi = member_item
$posts = $paginator->paginate(
$repositoryPost
->createQueryBuilder('t')
->select('t', 'mi', 'm')
->leftJoin('t.author', 'm')
->leftJoin('m.item', 'mi')
->orderBy('t.createAt')
->where('t.topic = :id')
->setParameter('id', $topic->getId())
->getQuery()
->getResult(),
$request->query->getInt('page', 1), 20);
// Sanitize each ForumPost object in the paginated results
foreach ($posts as $key => $post) {
$posts[$key] = $this->htmlSanitizer->sanitizeObj($post);
}
$new_post = new ForumPost();
$form = $this->createForm(PostType::class, $new_post);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$new_post = $form->getData();
$new_post->setAuthor($this->getUser());
$new_post->setTopic($topic);
$manager->persist($new_post);
$topic->setUpdateAt(new \DateTimeImmutable());
$manager->persist($topic);
$memberRepository = $this->getUser();
$memberRepository->setExperience($memberRepository->getExperience() + 5);
$manager->persist($memberRepository);
$this->addFlash(
'info-rpg',
'+5xp (post forum)'
);
$manager->flush();
$this->addFlash(
'success',
'Message créer avec succès'
);
return $this->redirectToRoute('forum.topic', ['id' => $topic->getId()]);
}
return $this->render($this->theme . '/forum/posts_list.html.twig', [
'categories' => $categories,
'forums' => $forums,
'topic' => $topic,
'posts' => $posts,
'form' => $form,
]);
}
link github project : https://github.com/MrToine/v2.univers-toine
thank's
i have testing on dev and on prod mode
I am writing a method to request a password reset in symfony
I get the email of the user from the posted value
$data = $form->getData();
$email = $data['email'];
It seems that I get the good email value and I can verify it by a
dump($email);
that returns
"firstname.name#domain.ext"
Then I try to fetch a user in the database with
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
but the result is null.
After that I try 2 different ways and both of them work perfectly i.e. give a valid user.
1- I replace
$email = $data['email'];
with
$email = "firstname.name#domain.ext";
2-
I change the line that fetches the user with:
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => "firstname.name#domain.ext"]);
Obviously the trouble comes from the way the value is passed to the findOneBy method, not because the user is not in the database.
I would like to know what I should do to use the value I got from the Post ?
Here is my controller
/**
* #Route("/passforgotten", name="app_forgotten_password", methods="GET|POST")
*/
public function askResetPass(
Request $request,
UserPasswordEncoderInterface $encoder,
ManagerRegistry $managerRegistry,
\Swift_Mailer $mailer,
TokenGeneratorInterface $tokenGenerator
): Response {
$defaultData = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($defaultData)
->add('email', EmailType::class)
->add('send', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$email = $data['email'];
//alternative that works of course with a real email
//$email="firstname.name#domain.ext";
dump($email);
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
dump($email);
dump($user);
if ($user === null) {
$this->addFlash('danger', 'Email Inconnu, recommence !');
return $this->redirectToRoute('app_register');
}
$token = $tokenGenerator->generateToken();
$manager = $managerRegistry->getManager();
try {
$user->setResetPasswordToken($token);
$manager->flush();
} catch (\Exception $e) {
$this->addFlash('warning', $e->getMessage());
return $this->redirectToRoute('home');
}
//this has not been tested yet
$url = $this->generateUrl('security/ask_reset_password', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new \Swift_Message('Rénitialisation du mot de pass'))
->setFrom(array('symfony#domain.ext'))
->setTo($user->getEmail())
->setBody('hello ask for reset pass!'
);
$mailer->send($message);
$this->addFlash('notice', 'Mail correctement envoyé !');
//this is not finished
return $this->redirectToRoute('a_route');
}
return $this->render('security/ask_reset_password.html.twig', [
'form' => $form->createView()
]);
}
Sorry but I was passing a misspelled email a letter l just before a b was missing and I used the form memorization of it each time. In fact it works in every case.
I'm stuck. I'm using mailer from symfony with gmail generated password, and i keep on getting this error.
Would anyone have an idea as of why?
here's my controller:
public function new(Request $request): Response
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($contact);
$entityManager->flush();
$name = ($form['Name']->getData());
$email = ($form['Email']->getData());
$subject = ($form ['Subject']->getData());
$content = ($form['Content']->getData());
$transport = new GmailTransport('******#*********.org', '******************');
$mailer = new Mailer($transport);
$entityManager = $this->getDoctrine()->getRepository(Subject::class);
$toEmail = $subject -> getEmail();
$realSubject = $subject -> getName();
$message = (new TemplatedEmail())
->from($email)
->to($toEmail)
->subject($content)
// path of the Twig template to render
->htmlTemplate('mail/newContact.html.twig')
/* pass variables (name => value) to the template
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',*/
;
$mailer->send($message);
return $this->redirectToRoute('home');
}
return $this->render('contact/new.html.twig', [
'contact' => $contact,
'form' => $form->createView(),
]);
}
and i've got this in the .env
###> symfony/mailer ###
MAILER_DSN=smtp://******#*********.org:******************#gmail
###< symfony/mailer ###
does anyone have an idea?
Thank you
I am trying to update two records/rows of same table in AJAX
public function reorderApplications(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$from = $request->request->get('from');
$to = $request->request->get('to');
$em = $this->getDoctrine()->getManager();
/** #var Application $fromApplication */
$fromApplication = $em->getRepository('IndexBundle:Application')->find($from['application']);
/** #var Application $toApplication */
$toApplication = $em->getRepository('IndexBundle:Application')->find($to['application']);
try {
$fromApplication->setOrder($to['position']);
$toApplication->setOrder($from['position']);
$em->flush();
$response = array(
'response' => 'success',
'message' => 'Applications were reordered successfully.'
);
} catch (\Exception $e) {
$response = array(
'response' => 'error',
'message' => $e->getMessage()
);
}
return new JsonResponse($response, 200);
}
Eventually, try fails at $em->flush() and I get error:
An exception occurred while executing 'UPDATE application SET order =
? WHERE id = ?' with params ["3", 4]:↵↵SQLSTATE[42000]: Syntax error
or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near 'order = '3' WHERE id = 4' at line 1
Anyone knows what could be the problem?
order is a reserved keyword in SQL.
To use it in column name, you must put backquotes in the definition:
#Column(name="`order`")
order is a reserved keyword in mysql. Try renaming the field.
http://dev.mysql.com/doc/refman/5.7/en/keywords.html
I want do one functional test over on service Symfony2. The idea is call before to the controller and after that, load the service with the function. The function is this one:
function save($title,$description,$setId,$html,$validate,$articles){
$articles = explode(',', $articles);
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
}else{
$profileId = $this->container->get('security.context')->getToken()->getUser()->getId();
$userName = $this->container->get('security.context')->getToken()->getUser()->getUserName();
}
}
and now my test code is :
$client = static::createClient();
$crawler = $client->request('GET','/sets/save',
array(
"title"=>"rtyui",
"description"=>"aksdjhashdkjahskjdh",
"set_id"=>"",
"html"=>"",
"validate"=>1,
"articels"=>"3,4"
)
);
but doesn't work already that I have this lines:
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
Now, the question is, how i can do the validation process? I've tried to do this validation process as show the documentation:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pa$$word',
));
but I got the same error.
Also you can login user by Security Token:
$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
new UsernamePasswordToken(
$user, null, 'main', $user->getRoles()
)
);
Where:
$user - instance of User entity with role ROLE_USER,
main - your security provider name