symfony 2 , pagination - symfony

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?

Related

Error 500 on pord mode but no on dev mode

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

Symfony 6 App\Entity\Question object not found by the #ParamConverter annotation

I try to make answers for question.
Here is my AnswerController:
#[Route('/{slug}/{name}/answer/{question}', name: 'answer_question')]
public function answer(Question $q, QuestionRepository $questionRepository, string $question, Request $request, EntityManagerInterface $entityManager, string $slug, string $name, AnswerRepository $answerRepository): Response
{
$questions = $questionRepository->findOneBySlug($question);
$answers = $answerRepository->findAnswers($question);
$form = $this->createForm(AnswerType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$answer = new Answer();
$answer->setContent($data->getContent());
$answer->setAnsweredAt(new \DateTime);
$answer->setQuestion($q);
$entityManager->persist($answer);
$entityManager->flush();
return $this->redirectToRoute('show_question', [
'slug' => $slug,
'name' => $name,
'question' => $question,
]);
}
return $this->render('answer/index.html.twig', [
'questions' => $questions,
'answers' => $answers,
'answer' => $form->createView(),
]);
}
I have problem with
App\Entity\Question object not found by the #ParamConverter annotation
EDIT:
Still I have a little problem with wildcards,
for example when i put address "/audi-a3/8v/answer/question" it's ok, but when i put "/audi-a4/8v/answer/question" ( there isn't audi-a4 with model 8v but this address gives me correct page for "8V" model. It doesn't match ).
Can someone explain me how to do it right?
I did some changes in AnswerController and now it's working.
Set ParamConverter manually.
#[Route('/{car}/{name}/answer/{slug}', name: 'answer_question')]
#[ParamConverter('question', class: Question::class, options: ['mapping' => ['slug' => 'slug']])]
public function answer(Question $question, QuestionRepository $questionRepository, Request $request, EntityManagerInterface $entityManager, string $slug, string $name, string $car, AnswerRepository $answerRepository): Response
{
$questions = $questionRepository->findOneBySlug($slug);
$answers = $answerRepository->findAnswers($slug);
$form = $this->createForm(AnswerType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$answer = new Answer();
$answer->setContent($data->getContent());
$answer->setAnsweredAt(new \DateTime);
$answer->setQuestion($question);
$entityManager->persist($answer);
$entityManager->flush();
return $this->redirectToRoute('show_question', [
'slug' => $slug,
'name' => $name,
'car' => $car,
]);
}
return $this->render('answer/index.html.twig', [
'questions' => $questions,
'answers' => $answers,
'answer' => $form->createView(),
]);
}

Retrieve posts created by a specific Symfony user

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,
]);
}

Symfony and Doctrine - displaying data from database in controller method

This is my code. I want to set default value from database in the form. I want to set value in form which i create in this method.
public function updateBlogAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('AppBundle:Blog\Post')->find($id);
$blogs = new Post();
$form = $this->createFormBuilder($blogs)
->add('title', TextType::class, array('attr'=>array( 'class'=>'form-control','placeholder'=>'Blog title')))
->add('description', TextareaType::class, array('attr'=>array('class'=>'form-control','placeholder'=>'Blog description')))
->add('submit',SubmitType::class, array('label'=>'Add Blog', 'attr'=> array('class'=>'btn btn-primary pull-right')))
->getForm();
$form->handleRequest($request);
if( $form->isSubmitted() && $form->isValid() ){
$data->setTitle($blogs);
$em->flush();
return $this->redirectToRoute('blog');
}
return $this->render('blog/update_blog.html.twig', array(
'form' => $form->createView()
));
}
It is as easy as
$em = $this->getDoctrine()->getManager();
$blogs= $em->getRepository('AppBundle:Blog\Post')->find($id);
$form = $this->createFormBuilder($blogs)
/* ... */

Updating entity in Doctrine takes too much time

I have the following code that updates SalesOrder Entity.
public function updateAction($id)
{
$securityContext = $this->get('security.context');
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:SalesOrder')->find($id);
$editForm = $this->createForm(new SalesOrderType($securityContext), $entity);
$currentTotal = $entity->getTotal();
$currentStatus = $entity->getStatus();
try {
$entity->isEditable();
} catch (\Exception $e){
$this->get('session')->setFlash('alert-error', $e->getMessage());
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $entity->getId())));
}
$originalItems = array();
foreach ($entity->getItems() as $item) {
$originalItems[] = $item;
}
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
try {
$entity->validateStatusChange($currentStatus, $currentTotal);
} catch (\Exception $e) {
$this->get('session')->setFlash('alert-error', $e->getMessage());
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $id)));
}
foreach ($entity->getItems() as $item) {
//adjust the reserved in the inventory
$item->adjustReserved();
foreach ($originalItems as $key => $toDel) {
if ($toDel->getId() === $item->getId()) {
unset($originalItems[$key]);
}
}
}
foreach ($originalItems as $item) {
$em->remove($item);
}
$entity->setUpdatedAt(new \DateTime('now'));
$em->persist($entity);
$em->flush();
$this->get('session')->setFlash('alert-success', 'Record has been updated successfully!');
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $id)));
} else {
$this->get('session')->setFlash('alert-error', 'Please fill in the correct values.');
$variantForm = $this->createForm(new AddVariantSalesOrderType());
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'variant_form' => $variantForm->createView(),
);
}
When i run this code i got ""maximum execution time exceeded". I already changed the maximum execution time in php.ini to 2 minutes.
Is there anyway i can optimize my codes ?
Thanks!

Resources