I've made search functionality in symfony, which works.
public function forSaleAction(Request $request)
{
$data = array();
$form = $this->createFormBuilder($data)
->add('searchText')
->getForm();
$form->handleRequest($request);
$ads = $this->getDoctrine()
->getRepository('ParkResortBundle:Ad')
->findAll();
if ($form->isSubmitted()) {
$data = $form->getData();
$SearchKeyword = $data['searchText'];
$qb = $this->getDoctrine()->getEntityManager()->getRepository('ParkResortBundle:Ad')->createQueryBuilder( 'p' );
$qb->add( 'where',
$qb->expr()->orX(
$qb->expr()->like( 'p.adTitle', "'%{$SearchKeyword}%'" ),
$qb->expr()->like( 'p.address', "'%{$SearchKeyword}%'" )
)
)
->addOrderBy('p.price', 'ASC');
$ads = $qb->getQuery()->getResult();
}
if ($request->isXmlHttpRequest()) {
return $this->render('ParkResortBundle:Pages:_ad.html.twig',
array('ads' => $ads));
}
$paginator = $this->get('knp_paginator');
$paginated = $paginator->paginate(
$ads, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
2/*limit per page*/
);
return $this->render('ParkResortBundle:Pages:forSale.html.twig',
array('ads' => $paginated,
'form'=>$form->createView()));
}
I want when the search area is empty(after user presses backspace or delete all) the list should appear all in for_sale twig template.
How can I do that?
You need to use entity manager with findAll()
$ads = $this->getDoctrine()->getEntityManager()
->getRepository('ParkResortBundle:Ad')
->findAll();
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 need of you for helping to resolve my problem.
I use Symfony 4 for display some charts with the bundle google charts
Thanks you a lot
This is my function controller
/**
* #Route("/admin/test", name="statsTest")
*/
public function statsTest(){
$results = $this->getDoctrine()->getRepository(IssueNubitalk::class)
->CountIssueByPartenaire('Canal');
dump($results);
// $results = [];
foreach ($results as $key => $val) {
// dump($results);
$results[] = [
'campaign' => $val->getCampaign(),
'total' => $val->getTotal(),
];
}
dump($results);
$data = json_decode(json_encode($results), true);
$pieChart = new PieChart();
$pieChart->getData()->setArrayToDataTable($data);
$pieChart->getOptions()->setHeight(250);
$pieChart->getOptions()->setWidth(400);
$pieChart->getOptions()->getTitleTextStyle()->setBold(true);
$pieChart->getOptions()->getTitleTextStyle()->setColor('#009900');
$pieChart->getOptions()->getTitleTextStyle()->setItalic(true);
$pieChart->getOptions()->getTitleTextStyle()->setFontName('Arial');
$pieChart->getOptions()->getTitleTextStyle()->setFontSize(20);
return $this->render('backend/test.html.twig', [
'piechart' => $pieChart,
]);
}
this is my repository
public function CountIssueByPartenaire($partenaire){
return $this->createQueryBuilder('i')
->select('i.campaign')
->addSelect('COUNT(DISTINCT i.sessionId) as total')
->where('i.campaign LIKE :campaign')
->setParameter('campaign', $partenaire.'_%')
->groupBy('i.campaign')
->getQuery()
->getResult();
}
this is the output
Call to a member function getCampaign() on array
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)
/* ... */
I have a working queryBuilder that gets posts by category and excludes the one being shown and sets a max limit.
Question: How can I simplify this queryBuilder?
In the query, I am pretty sure I don't need to join the 2 tables (category/post connected with a OneToMany/ManyToOne relationship) and am setting $category in the controller, is there a better way of refactoring this?
queryBuilder
public function getRelatedPosts($exceptPost, $limit, $category)
{
return $this
->createQueryBuilder('post')
->leftJoin('post.category','category')
->where('post != :exceptPost')
->setParameter('exceptPost', $exceptPost)
->andWhere('category = :category')
->setParameter('category', $category)
->orderBy('post.createdAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->execute();
}
controller
public function showAction($slug)
{
$post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->findOneBy(array(
'slug' => $slug
));
if (null === $post) {
throw $this->createNotFoundException('Post was not found');
}
$category = $post->getCategory();
$posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->getRelatedPosts($post, 4, $category);
return array(
'post' => $post,
'posts' => $posts
);
}
updated queryBuilder
public function getRelatedPosts($exceptPost, $limit, $category)
{
return $this
->createQueryBuilder('post')
->where('post != :exceptPost')
->andWhere('post.category = :category')
->setParameter('exceptPost', $exceptPost)
->setParameter('category', $category)
->orderBy('post.createdAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->execute();
}
I am not sure if this is what you are looking for but you may want something like this:
Controller
public function showAction($slug)
{
$post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->findOneBy(array(
'slug' => $slug
));
if (null === $post) {
throw $this->createNotFoundException('Post was not found');
}
$posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
->getRelatedPosts($post, 4);
return array(
'post' => $post,
'posts' => $posts
);
}
Repository
public function getRelatedPosts($exceptPost, $limit)
{
return $this
->createQueryBuilder('post')
->where('post.id != :exceptPost')
->andWhere('post.category = :category')
->setParameter('exceptPost', $exceptPost->getId())
->setParameter('category', $exceptPost->getCategory()->getId())
->orderBy('post.createdAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
You can also build this in a join query of post table with itself or SELECT ... IN (...); if you are interested
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?