hello everyone i get this error message when using KnpPaginatorBundle and i can't find any solution : knp\Bundle\PaginatorBundle\Twig\Extension\PaginationExtension::render(): Argument #2 ($pagination) must be of type Knp\Bundle\PaginatorBundle\Pagination\SlidingPaginationInterface, array given, called in /home/yves/projects/www/symfony/planningagents/var/cache/dev/twig/b5/b577cc13428f6141409c675f78c76019.php on line 209
creneauRepository :
`` `public function findBySearch(SearchData $searchData): PaginationInterface ``
{
$data = $this->createQueryBuilder('c');
if(!empty($searchData->q)) {
$data = $data
->Join('c.agent', 'a')
->Where('a.nom LIKE :q')
->setParameter('q', "%{$searchData->q}%")
->addOrderBy('c.date', 'DESC');
}
$data = $data->getQuery()->getResult();
$creneaus = $this->paginatorInterface->paginate($data, $searchData->page, 8);
return $creneaus;
}`
CreneauxController
`` `#[Route('/creneaux/r/h')] ``
class CreneauxRHController extends AbstractController
{
#[Route('/', name: 'app_creneaux_r_h_index', methods: ['GET'])]
public function index(CreneauRepository $creneauRepository, Request $request): Response
{
$searchData = new SearchData();
$form = $this->createForm(SearchType::class, $searchData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$searchData->page = $request->query->getInt('page', 1);
$creneaus = $creneauRepository->findBySearch($searchData);
return $this->render('creneaux_rh/index.html.twig', [
'form' => $form->createView(),
'creneaus' => $creneaus,
]);
}
return $this->render('creneaux_rh/index.html.twig', [
'form' => $form->createView(),
'creneaus' => $creneauRepository->findBy([], ['date' =>'DESC']),
]);
}`
and my view
<div class="pagination position-absolute start-50 translate-middle fs-5 mt-4 navigation">{{ knp_pagination_render(creneaus) }}</div>
TY for help
Related
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(),
]);
}
I am getting the following error when adding the template Variable "addPostForm" does not exist.
I want to include in my main template another template with a form that will be shown in a modal window
This is my controller
#[Route('/post/{id}/add', name: 'add_post')]
public function addPost(Request $request, EntityManagerInterface $entityManager) : Response
{
$post = new Post();
$form = $this->createForm(PostFormType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$message = $form->get('message')->getData();
$post->setMessage($message);
$post->setAuthor($this->getUser());
$entityManager->persist($post);
$entityManager->flush();
return $this->redirectToRoute('app_home', ['id' => $this->getUser()->getId()]);
}
return $this->renderForm('post/post.html.twig', [
'addPostForm' => $form,
]);
}
And the template which is located at templates/post/post.html.twig
{{ form_start(addPostForm) }}
{{ form_row(addPostForm.message) }}
<button type="submit" class="btn btn-dark btn-sm">Register</button>
{{ form_end(addPostForm) }}
You need to connect to the template, which is here templates/home/index.html.twig
I used the include command for this {% include 'post/post.html.twig' %}, but it gives an error that the variable is not found
Thanks #DarkBee
I'm create form in my index controller
class HomeController extends AbstractController
{
#[Route('/home/{id}', name: 'app_home')]
public function index(User $user, Request $request, EntityManagerInterface $entityManager): Response
{
$post = new Post();
$form = $this->createForm(AddPostFormType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$message = $form->get('message')->getData();
$post->setMessage($message);
$post->setAuthor($this->getUser());
$entityManager->persist($post);
$entityManager->flush();
return $this->redirectToRoute('app_home', ['id' => $this->getUser()->getId()]);
}
return $this->render('home/index.html.twig', [
'addPostForm' => $form->createView(),
'user' => $this->getUser(),
]);
}
}
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,
]);
}
Based on documentation: http://symfony.com/doc/2.8/form/dynamic_form_modification.html#form-events-submitted-data
I prepared dynamic generated form. And everything works properly but only when I use form for adding new data (/new) when I use the same form for editing existing data - not working
Simple form for "Appointment". It should work like that: User select client and then second "select" is filling proper data - depends on each client from first select. And this works ok but only when I try add new Appointment. When I try edit no.
class AppointmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('client', EntityType::class, array(
'class' => 'SystemAdminBundle:Client',
'placeholder' => '',
));
$formModifier = function(\Symfony\Component\Form\FormInterface $form, Client $client)
{
$diseases = array();
if($client !== null) {
$diseases = $client->getDiseases();
}
$form->add('disease', EntityType::class, array(
'class' => 'SystemAdminBundle:Disease',
'placeholder' => '',
'choices' => $diseases,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getClient());
}
);
$builder->get('client')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$client = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $client);
}
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'System\AdminBundle\Entity\Appointment'
));
}
}
Appointment controller - here is function for add new appointment and edit. For "new" my code works, for "edit" no.
public function newAction(Request $request)
{
$appointment = new Appointment();
$form = $this->createForm(AppointmentType::class, $appointment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $request->request->get('appointment');
if(array_key_exists('name', $data)) {
$em = $this->getDoctrine()->getManager();
$em->persist($appointment);
$em->flush();
return $this->redirectToRoute('appointment_show', array('id' => $appointment->getId()));
}
}
return $this->render('appointment/new.html.twig', array(
'appointment' => $appointment,
'form' => $form->createView(),
));
}
public function editAction(Request $request, Appointment $appointment)
{
$deleteForm = $this->createDeleteForm($appointment);
$appointment = new Appointment();
$editForm = $this->createForm('System\AdminBundle\Form\AppointmentType', $appointment);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$data = $request->request->get('appointment');
if(array_key_exists('name', $data)) {
$em = $this->getDoctrine()->getManager();
$em->persist($appointment);
$em->flush();
return $this->redirectToRoute('appointment_show', array('id' => $appointment->getId()));
}
return $this->redirectToRoute('appointment_edit', array('id' => $appointment->getId()));
}
return $this->render('appointment/edit.html.twig', array(
'appointment' => $appointment,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
View for "new" appointment
{% block content %}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
window.onload = function() {
var $sport = $('#appointment_client');
$sport.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$sport.attr('name')] = $sport.val();
data['appointment[_token]'] = $('#appointment__token').val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#appointment_disease').replaceWith(
$(html).find('#appointment_disease')
);
}
});
});
};
{% endblock %}
View for "edit" appointment - it's almost the same as for "new" appointment
{% block content %}
{{ form_start(edit_form) }}
{{ form_widget(edit_form) }}
{{ form_end(edit_form) }}
window.onload = function() {
var $sport = $('#appointment_client');
$sport.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$sport.attr('name')] = $sport.val();
data['appointment[_token]'] = $('#appointment__token').val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#appointment_disease').replaceWith(
$(html).find('#appointment_disease')
);
}
});
});
};
{% endblock %}
You create a new Appointment in your editAction and then persist it. You should take the one that's in your function parameters, handle the request and just flush, since your object is already persisted.
So remove these lines :
$appointment = new Appointment();
// ...
$em->persist($appointment);
I hope to use a form inside my controller,but I get everytime the following error :
Could not load type "locality"
and here is ly form class :
class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$factory = $builder->getFormFactory();
$builder->add('province','entity',array(
'class' => 'Acme\DemoBundle\Entity\Province',
'property' => 'name'));
$refreshLocality = function ($form, $province) use ($factory) {
$form->add($factory->createNamed('entity','locality',null, array(
'class' => 'Acme\DemoBundle\Entity\Locality',
'property' => 'name',
'label' => 'Locality',
'query_builder' => function (EntityRepository $repository) use ($province) {
$qb = $repository->createQueryBuilder('locality')
->innerJoin('locality.province', 'province');
if($province instanceof Province) {
$qb = $qb->where('locality.province = :province')
->setParameter('province', $province);
} elseif(is_numeric($province)) {
$qb = $qb->where('province.id = :province_id')
->setParameter('province_id', $province);
} else {
$qb = $qb->where('province.id = 1');
}
return $qb;
}
)));
};
$builder->add('address','text',array(
'required' => false));
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($refreshLocality) {
$form = $event->getForm();
$data = $event->getData();
if($data == null)
$refreshLocality($form, null); //As of beta2, when a form is created setData(null) is called first
if($data instanceof Location) {
$refreshLocality($form, $data->getLocality()->getProvince());
}
});
$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) use ($refreshLocality) {
$form = $event->getForm();
$data = $event->getData();
if(array_key_exists('province', $data)) {
$refreshLocality($form, $data['province']);
}
});
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Location'
));
}
public function getName()
{
return 'acme_demobundle_locationtype';
}
}
Then I called this class in my controller :
public function indexAction()
{
$form = $this->get('form.factory')->create(new \Acme\DemoBundle\Form\LocationType());
$request = $this->get('request');
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
}
}
return array('form' => $form->createView());;
}
and here my twig :
<form action="{{ path('_demo') }}" method="POST" id="contact_form">
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" value="Send" class="symfony-button-grey" />
</form>
when I had the error above I tried to register your form in the section services in service.xml :
<service id="form.type.acme_demobundle_locationtype" class="Acme\DemoBundle\Form\LocationType">
<tag name="form.type" alias="acme_demobundle_locationtype" />
</service>
but I get the same error,any idea?
You need to swap the arguments that you passed to createNamed():
$form->add($factory->createNamed('entity','locality',null, array(
should be
$form->add($factory->createNamed('locality', 'entity', null, array(
In fact, you can even simplify your code to
$form->add('locality', 'entity', array(