Find by User ID - MiguelFieira/AMO-HANDBOEK GitHub Wiki
Symfony is a PHP framework for web applications and a set of reusable PHP components. Symfony is used by thousands of web applications (including BlaBlaCar.com and Spotify.com) and most of the popular PHP projects (including Drupal and Magento).
In cases that you have to find multiple rows of an entity that is from a specific user
Importing the entity
- Go to the controller where you want the 'function' in and add the following line underneath the other use statements at the top of the file:
use App\Entity\Post;// In this case we used the entity post to find posts from a specific user.
Use the 'function'
- Go to the function for the page in the same file and add the following line:
$userPost = $this->getDoctrine()->getRepository(Post::class)->findBy(['user' => $this->getUser()]);// In this case it depends how you called your attribute to link the user in the entity
- Go to the return of the function and add the following line:
'userPost' => $userPost,Controller result
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Post;
class PostStatusController extends AbstractController
{
/**
* @Route("/poststatus", name="post_status")
*/
public function index()
{
$userPost = $this->getDoctrine()->getRepository(Post::class)->findBy(['user' => $this->getUser()]);
return $this->render('post_status/index.html.twig', [
'userPost' => $userPost,
'controller_name' => 'PostStatusController',
]);
}
}In twig
- Add the forloop like this and call other attributes too:
{% for userPost in userPost %}
<td>{{ userPost.id }}</td>
<td>{{ userPost.title }}</td>
<td>{{ userPost.content }}</td>
<td>{{ userPost.approved ? 'Yes' : 'No' }}</td>
<td>{{ userPost.rejectionComment }}</td>
{% else %}
<tr>
<td colspan="4">no records found</td>
</tr>
{% endfor %}