Why my action is not loaded when I click on a button? - symfony

I wanted to create a button that delete a pupil. But I have a problem, my button doesn't launch the deleteAction in my controller.
My controller :
public function deleteAction(Eleve $id, $schoolId)
{
$repository = $this->getDoctrine()->getManager()->getRepository('WCSCantineBundle:Lunch');
$pupil = $repository->findOneBy(array(
'eleve' => $id
));
$em = $this->getDoctrine()->getManager();
$em->remove($pupil);
$em->flush();
return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}
My route :
delete_pupil:
path: /
defaults: { _controller: "WCSCantineBundle:CanteenManager:delete" }
My button (in my view) :
Désinscrire
Thank you for your help.

public function deleteAction(Eleve $id, $schoolId)
{
$em = $this->getDoctrine()->getManager();
$pupil = $em->getRepository('WCSCantineBundle:Lunch')->findOneBy(array('eleve' => $id));
$em->remove($pupil);
$em->flush();
return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}
your code fails because the doctrine entity manager has no clue about what $pupil is since there is two different instances of entity managers, the above code is short hand for removing pupil, but you can change it as needed as long as the entity manager 'knows' about the entity

I did it and it works.
My controller :
public function deleteAction($id, $schoolId)
{
$dateNow = new \DateTime();
$em = $this->getDoctrine()->getManager();
$lunches = $em->getRepository('WCSCantineBundle:Lunch')->findBy(array(
'eleve' => $id,
'date' => $dateNow
));
foreach ($lunches as $lunch) {
$em->remove($lunch);
}
$em->flush();
return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}
My route :
delete_pupil:
path: /todayList/{schoolId}/{id}
defaults: { _controller: "WCSCantineBundle:CanteenManager:delete" }
methods: [GET, DELETE]
And my view :
Désinscrire
I missed to pass my arguments in my route with slashes : /todayList/{schoolId}/{id}
I thank everybody for your help.

Related

In Symfony how do I redirect to route with datas from search form ? Error : Variable does not exist

I made a search form in order to get events list. This form is displayed in front/search.html.twig. When I submit the search form, I'd like it leads me to front/events.html.twig.
When I submitted it, it says "category" doesn't exist. I don't have this problem when I replaced
return $this->redirectToRoute('events', $data);
with
return $this->render('front/events.html.twig', $data);
but I wish to use to route "events"...
This is my EventsController.php file :
<?php
namespace App\Controller\Front;
use App\Form\SearchType;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class EventsController extends AbstractController
{
#[Route('/search', name: 'search')]
public function search(Request $request, SessionInterface $sessionInterface)
{
$data = $request->request->all();
$sessionSearchFormData = $sessionInterface->get('searchFormData');
$form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$sessionInterface->set('searchFormData', $data);
return $this->redirectToRoute('events', $data);
}
return $this->renderForm('front/search.html.twig', [
'form' => $form
]);
}
#[Route('/events', name: 'events')]
public function events(
EventsRepository $eventsRepository,
CategoriesRepository $categoriesRepository
){
$events = $eventsRepository->findAll();
$categories = $categoriesRepository->findAll();
return $this->render("front/events.html.twig", ['events' => $events, 'categories' => $categories]);
}
}
Bonjour Emilie,
Your route events does not have parameters. So you can't redirect it using parameters.
you can try something like this :
public function index($name)
{
return $this->redirectToRoute('events', ['max' => 10]);
}
You can forward to another Controller :
public function index($name)
{
$response = $this->forward('App\Controller\OtherController::fancy', [
'name' => $name,
'color' => 'green',
]);
// ... further modify the response or return it directly
return $response;
}
Regards,
hous has found the solution :
The second parameter must be an array :
return $this->redirectToRoute('events', [$data]);

JMS Serializer event is not working

I am sure it is a small error but I cannot find it.
I am trying to follow the official doc and implement an event listener on the pre_serialize event.
My service declaration:
<service id="app.question_serializer_subscriber" class="AppBundle\Serializer\QuestionSerializerSubscriber">
<tag name="jms_serializer.event_subscriber"/>
</service>
My subscriber:
<?php
namespace AppBundle\Serializer;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;
class QuestionSerializerSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
array(
'event' => 'serializer.pre_serialize',
'method' => 'onPreSerialize',
)
);
}
public function onPreSerialize(ObjectEvent $event)
{
die('in event');
}
}
And my controller:
$question = $repo->findLastVersionByQuestionId((int) $questionId);
$serializer = SerializerBuilder::create()->build();
$context = new SerializationContext();
return new JsonResponse(json_decode(
$serializer->serialize(
$question,
'json',
$context
),
true
));
When I access the route my entity Question is serialized and displayed, but why does the die('in event'); is not displayed ?
Maybe it has a relation with the fact that my object is a Doctrine entity (issue 666 or PR 677 )
I finally find the issue. The problem is
$serializer = SerializerBuilder::create()->build();
This does not work but this does:
$serializer = $this->get('jms_serializer');
Try adding the class attribute, as example:
public static function getSubscribedEvents()
{
return array(
array(
'event' => 'serializer.pre_serialize',
'class' => 'FQCN_class_name',
'method' => 'onPreSerialize',
)
);
}
Another difference regarding the doc is in the argument of the class method: you should use PreSerializeEvent instead of ObjectEvent:
So like this:
public function onPreSerialize(PreSerializeEvent $event)
{
// ...
}
Check your service is correctly load from the container as example with the console command:
php app/console debug:container --tag=jms_serializer.event_subscriber
Hope this help

Using Subscribing Handler Interface when Serialize te modify parameters in symfony

I have a REST API and have an Entity Userwith field called Avatar, in DB I save name XXXX.jpg but when I return I want to add a url in this field Avatar, for example www.mylink.com/XXXX.jpg.
I'm trying with a service implements SubscribingHandlerInterfacebut I don't know how I can use it.
I have this method in this service:
class UrlManager implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'AppBundle/Entity/User',
'method' => 'serializeUrlAvatar',
),
);
}
public function serializeUrlAvatar(User $user)
{
$url = 'www.mylink.com';
return array(
"avatar" => $url . $user->getAvatar()
);
}
}
but how can I call this service to modify url when I serialize.
Now I do this:
$_format = 'json';
$json = $this->get('jms_serializer')->serialize($user, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);
In service.yml:
app.url_converter_service:
class: AppBundle\Service\UrlManager
tags:
- { name: jms_serializer.subscribing_handler }
Update
In my controller I call this function like this:
$result = $this->get('app.url_converter_service')->serializeUrlAvatar($user);
$json = $this->get('jms_serializer')->serialize($result, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);
So my question is, exists a way to remove the first line and serialize correctly (add the url) when I serialize?
Have you registered your service like this?
# app/config/services.yml
avatar_url_handler:
class: YourBundle\Serializer\Handler\AvatarUrlHandler
tags:
- { name: jms_serializer.subscribing_handler }
I found a solution. I create a service which implements EventSubscriberInterface like this:
class UserSerializeHandler implements EventSubscriberInterface
{
private $user_uploads;
public function __construct($user_uploads){
$this->user_uploads = $user_uploads;
}
public static function getSubscribedEvents()
{
return array(
array(
'event' => 'serializer.pre_serialize',
'class' => User::class,
'method' => 'onPreSerializeUser'
));
}
public function onPreSerializeUser(PreSerializeEvent $event)
{
/** #var User $user */
$user = $event->getObject();
$avatar = $user->getAvatar();
$user->setAvatar($this->user_uploads . "/" . $avatar);
}
}
In service.yml:
app.serializer_user_service:
class: AppBundle\Service\UserSerializeHandler
arguments: ['%user_uploads%']
tags:
- { name: jms_serializer.event_subscriber }
I have user_uploads in parameters.yml like this:
user_uploads: 'https://myUrl.com'
And in any Controller that I serialize a User, I add the url in the Avatar paramter.
$json = $this->get('jms_serializer')->serialize($user, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);

How to recover data from database using symfony2

i need to display information of a product from my database but i have an
error: Controller
"UserBundle\Controller\DefaultController::profileAction()" requires
that you provide a value for the "$id" argument (because there is no
default value or because there is a non optional argument after this
one).
This is the profileAction:
public function profileAction($id)
{
$product = $this->getDoctrine()
->getRepository('UserBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
return $this->render('UserBundle:Default:profile.html.twig', array('product' =>$product));
}
please someone help me.
You need to provide $id as argument.
Change the return to something like that:
return $this->render('UserBundle:Default:profile.html.twig', ['product' => $product, 'id' => $id]);
You need a route like that :
_my_route:
path: /my_path/{id}
defaults: {controller: AcmeBundle:Default:profile}
requirements:
id: \d+
Action in your controller :
public function profileAction($id)
{
$product = $this->getDoctrine()
->getRepository('UserBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
return $this->render('UserBundle:Default:profile.html.twig', array('product' =>$product));
And a link or something else in your view like that (Hope you use Twig):
Lorem ipsum
It should be work.
EDIT :
For you search feature, i will do a route like that
_profile:
path: /profile
defaults: {_controller:AcmeBundle:Default:profile}
Controller :
public function profileAction(Request $request){
$form = $this->createForm(new SearchType());
$products = null ;
if($request->isMethod('POST')){
$form->handleRequest($request);
$value = ($form['search']->getData());// change de 'search' according to your form
$em = $this->getDoctrine()->getManager() ;
$product = $em->getRepository('UserBundle:Product')->find($value) ;
}
if(!$product) throw $this->createNotFoundException('your message');
return $this->render('UserBundle:Default:profile.html.twig',array(
'product' => $product
));
}
And finally, your form in the view :
<form method="POST" action="{{ path('_profile') }}">
//your code
</form>
Well i think that here $id become null and it causes error because $id is used to fetch data from your db, so set default value for $id check $id will never become null or empty. All the best.

Symfony2 - Generate CRUD

I am trying to generate CRUD of the entities but i have a few questions, i don't know if it's a normal comportment or an error.
I apply the command :
I am adding the route in routing.yml like asking.
Now, when i am testing this crud , just create party work.
Update doesn't working, it's updateAction :
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('IFppoGestionPersonnelBundle:TableTest')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find TableTest entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('tabletest_edit', array('id' => $id)));
}
return $this->render('IFppoGestionPersonnelBundle:TableTest:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
I don't know why it doesn't add "em->persist($entity)", but if i add this line , it does not update ...
I have same errors with deleteAction.
And when i am creating a new tuple, and back to list , the last tuple is not displaying.
It's maybe an error to the class :
IFppo\GestionPersonnelBundle\Entity\TableTest:
type: entity
table: tabletest
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
nom:
type: string
length: 255
column: nom
prenom:
type: string
length: 255
column: prenom
lifecycleCallbacks: { }
In log, i don't have any trace of update ...
[EDIT] When writing to the log for any errors, return an empty array with $editForm->getErrors() and with $editForm->getErrorsAsString() return :
nom: No errors prenom: No errors submit: No errors [] []
Thanks a lot.

Resources