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
Related
I have a $ type boolean property, I need to differentiate my two types of posts I am trying to retrieve posts of type = true, (which are recipes) of a specific user for the user profile page.
/**
* #Route("/profil/{id}", name="profil", methods={"GET","POST"})
*
*/
public function index(User $user): Response
{
$em = $this->getDoctrine()->getManager();
$publications = $em->getRepository('App:Publication')->findBy(
array('users' => $user->getId()),
array('created_at' => 'Desc')
);
****// list the publication of recipes
$recette = $em->getRepository('App:Publication')->findBy(['type'=>true],['created_at' => 'desc']);****
// recuperar las 3 ultimas recetas para el sidebar rigth
$lastRecettes = $this->getDoctrine()->getRepository(Publication::class)->lastXRecette(4);
// lister les 9 dernières recettes
$recette = $this->getDoctrine()->getRepository(Publication::class)->lastPRecette(9);
return $this->render('profil/index.html.twig', [
'publications' => $publications,
'recettes' => $recette,
'user' => $user,
'lastRecettes' => $lastRecettes,
]);
}
the highlighted part allows me to retrieve all the recipes but I don't know how to add the user I tried this but it is not correct:
$recette = $em->getRepository('App:Publication')->findBy(['type'=>true], ['users' => $user->getId()],['created_at' => 'desc']);
Yes, as proposed (but maybe in a confused way) by #mustapha-ghlissi you have to include the test on your user on the first argument of the findBy method like this :
$recette = $em->getRepository('App:Publication')->findBy(['type' => true, 'users' => $user->getId()],['created_at' => 'desc']);
PublicationRepository.php
public function getRecettesUser(User $user)
{
return $this->createQueryBuilder('p')
->andWhere('p.users = :user')
->andWhere('p.type = :type')
->setParameter('user', $user)
->setParameter('type', true)
->getQuery()
->getResult();
}
create a folder src/Manager/PublicationManager.php
use App\Entity\Publication;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
class PublicationManager
{
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function getRecetteByUser(User $user)
{
return $this->em->getRepository(Publication::class)->findBy(
['type' => true, 'users' => $user->getId()],['created_at' => 'desc']
);
}
}
My Controller
/**
* #Route("/profil/{id}", name="profil", methods={"GET","POST"})
*
*/
public function index(User $user, PublicationManager $publicationManager): Response
{
$em = $this->getDoctrine()->getManager();
$publications = $em->getRepository('App:Publication')->findBy(
array('users' => $user->getId()),
array('created_at' => 'Desc')
);
// recuperer les 3 dernier recettes pour le sidebar right
$lastRecettes = $this->getDoctrine()->getRepository(Publication::class)
->lastXRecette(4);
return $this->render('profil/index.html.twig', [
'publications' => $publications,
'recettes' => $publicationManager->getRecetteByUser($user),
'lastRecettes' => $lastRecettes,
]);
}
I'm not sure if I well understood your problem
But may your code should look like this :
/**
* #Route("/profil/{id}", name="profil", methods={"GET","POST"})
*
*/
public function index(User $user): Response
{
$em = $this->getDoctrine()->getManager();
// First type
$truePublications = $em->getRepository(Publication::class)->findBy(
array('user' => $user->getId(), 'type' => true),
array('created_at' => 'DESC'),
);
// Second type
$falsePublications = $em->getRepository(Publication::class)->findBy(
array('user' => $user->getId(), 'type' => false),
array('created_at' => 'DESC'),
);
// recuperar las 3 ultimas recetas para el sidebar rigth
$lastRecettes = $this->getDoctrine()->getRepository(Publication::class)->lastXRecette(3);
// lister les 9 dernières recettes
$recette = $this->getDoctrine()->getRepository(Publication::class)->lastPRecette(9);
return $this->render('profil/index.html.twig', [
'trueTypePublications' => $truePublications,
'falseTypePublications' => $falsePublications,
'recettes' => $recette,
'user' => $user,
'lastRecettes' => $lastRecettes,
]);
}
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
public function contactAction(Request $request)
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$name = $form['name']->getData();
$email = $form['email']->getData();
$subject = $form['subject']->getData();
$message = $form['message']->getData();
$contact->setName($name);
$contact->setEmail($email);
$contact->setSubject($subject);
$contact->setMessage($message);
}
$message = \Swift_Message::newInstance()
->setSubject($subject) // here the error
->setFrom('jardisindustrie#gmail.com')
->setTo($email)
->setBody($this->renderView('sendmail.html.twig', array(
'name' => $name,
'message' => $message,
'email' => $email,
'subject' => $subject)), 'text/html');
$this->get('mailer')->send($message);
return $this->render('SDCoreBundle::contact.html.twig', [
'form' => $form->createView()
]);
}
I don't know why but it did work good and this afternoon I try again and I have the error message...
I want to make a contact form with swiftmailer, normally I do like that but here i don't know why there is a trouble.
Thanks for your help
You are missing the complete error message. But from the first look, the code that creates and sends a message should be inside the if($form->isSubmitted() && $form->isValid()) block, otherwise it will try to send a message when the form is not submited but only being displayed.
I'm just started working with Symfony2 and I have some problems with Pagination.
I have this code in my Account class:
public function indexAction($page)
{
$session = $this->get('session');
if ($session->get('valid')=='true') {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ProjectCRMBundle:Account')->findAll();
$user = new Account();
$form = $this->container->get('form.factory')->create(new AccountType());
$total = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->getQuery()->getResult();
/* total of résultat */
$total_users = count($total);
$users_per_page = 1;
$last_page = ceil($total_users / $users_per_page);
$previous_page = $page > 1 ? $page - 1 : 1;
$next_page = $page < $last_page ? $page + 1 : $last_page;
/* résultat à afficher*/
$entities = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->setFirstResult(($page * $users_per_page) - $users_per_page)->setMaxResults(1)->getQuery()->getResult();
return $this->render('ProjectCRMBundle:Account:index.html.twig', array(
'entities' => $entities,
'last_page' => $last_page,
'previous_page' => $previous_page,
'current_page' => $page,
'next_page' => $next_page,
'total_users' => $total_users,
'form' => $form->createView(),
'user' => $user,
));
return $this->render('ProjectCRMBundle:Account:index.html.twig');
} else {
return $this->redirect($this->generateUrl('user_login'));
}
}
/**
* Creates a new Account entity.
*
*/
public function createAction(Request $request)
{
$entity = new Account();
$form = $this->createForm(new AccountType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('account_show', array('id' => $entity->getId())));
}
return $this->render('ProjectCRMBundle:Account:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
without forgetting the path on account.yml
account:
pattern: /{page}
defaults: { _controller: "ProjectCRMBundle:Account:index" , page: 1 }
At first look, it seems to work, but after trying to add a new account, I got this message:
LIMIT argument offset=-1 is not valid
Can anyone solve my problem?