Search code examples
phpsymfonywebcontrollers

Passing objects through controllers in symfony2


I am very puzzled.. I am running Symfony2.3.

I have a controller that forwards to a separate controller if a form is submitted.

   if ($form->isValid()) {
         $response = $this->forward('MusicMBundle:Song:addTrackToSong', array(
            'Track'=>$Track,
            ));
         return $response;
   }

However, as can be seen, the Track parameter is passed through this forward to the following (simplified) controller, with another form.

    public function addTrackToSongAction(Request $request, $Track){
          if ($form->isValid()) {   
                //LOGIC
                return $this->redirect($this->generateUrl('MusicMBundle_homepage'));
          }
          return $this->render('MusicMBundle:Song:addtracktosong.html.twig', array(
               'Track' => $Track, 'form' => $form->createView(),
          ));

If I var_dump($Track) anywhere in the function, it exists and is exactly what I want it to be.

However, when the second form is submitted, symfony2 throws the following error:

Controller "Music\MBundle\Controller\SongController::addTrackToSongAction()" requires 
that you provide a value for the "$Track" argument (because there is no default value 
or because there is a non optional argument after this one).

Quite frankly I am puzzled. I have access to everything I need, but symfony is getting very angry at me. The problem could be in my forwarding strategy I suppose?

Here is my routing file if the problem could be there:

MusicMBundle_Song_addTrackToSong:
pattern: /addTrackToSong
defaults: { _controller: MusicMBundle:Song:addTrackToSong }
requirements:
   _method: GET|POST

I am a beginner with the framework and I just don't know where to start and can't find anything on it.

If I can provide any other info let me know.

Thanks so much!


Solution

  • Your route might be incorrect, because it has no parameters. You can try adding a parameter for Track in your route, by changing your pattern in your routing file from this:

    pattern: /addTrackToSong
    

    to this:

    pattern: /addTrackToSong/{Track}
    

    If you visit the url /addTrackToSong/yourTrackValue, $Track in SongController::addTrackToSongAction method will equal yourTrackValue.

    Another way to resolve the problem, would be by setting a default value for $Track in your action method.

    public function addTrackToSongAction(Request $request, $Track = null) {