whitebear
whitebear

Reputation: 12423

Using controller class's method in other class

I want to use renderView() in other class than Controller.

class RegistrationFormHandler extends BaseRegistrationFormHandler  
{

    protected function onSuccess(UserInterface $user, $confirmation)
    {
            $messaggio = \Swift_Message::newInstance()
    ...
        ->setBody($this->renderView('AcmeMemberBundle:Default:firstemailtocustomer.txt.twig',array('user' => $user)));

it shows

FatalErrorException: Error: Call to undefined method Acme\UserBundle\Form\Handler\RegistrationFormHandler::renderView() in 

but if you try same method in controller class.

class DefaultController extends Controller
{

public function mainAction(){
    $messaggio = \Swift_Message::newInstance()
    ...
        ->setBody($this->renderView('AcmeMemberBundle:Default:firstemailtocustomer.txt.twig',array('user' => $user)));

it works well.

I think I should get instance of controller class.

How can I solove this?


Thanks to tim's answer.

I add this to services.xml

    <service id="acme.default.controller" class="Acme\MemberBundle\Controller\DefaultController" public="false">
        <argument>acme.controller.default.class</argument>
     </service>

and use like this

->setBody($this->forward('acme.controller.default.class')->renderView('AcmeMemberBundle:Default:firstemailtocustomer.txt.twig',array('user' => $user)));

but it says,

FatalErrorException: Error: Call to undefined method Acme\UserBundle\Form\Handler\RegistrationFormHandler::forward() in 

Upvotes: 1

Views: 1767

Answers (3)

Gromov
Gromov

Reputation: 1

You should use this

$this->container->get('templating')->renderResponse('AcmeMemberBundle:Default:firstemailtocustomer.txt.twig',array('user' => $user))->getContent();

Upvotes: 0

Udan
Udan

Reputation: 5599

When you use

$this->renderView();

in a controller, you are using a shortcut for

$this->container->get('templating')->renderView();

So if you just inject symfony's templating serice in another class you can use renderView from there.

In more detail right in the symfony docs: http://symfony.com/doc/current/book/templating.html

Upvotes: 2

Tim
Tim

Reputation: 6441

Create a Controller you can use as a Service.

# src/Acme/UserBundle/Resources/config/services.yml
parameters:
    # ...
    acme.controller.default.class: Acme\HelloBundle\Controller\UserController

services:
    acme.hello.controller:
        class:     "%acme.controller.default.class%"

And then call:

$this->forward('acme.hello.controller:mainAction');

from RegistrationFormHandler.

Upvotes: 2

Related Questions