Milo
Milo

Reputation: 13

Pass render to my new created service - Symfony

Please, I am new to symfony, I can't seem to make this work. I created a simple service that will check if the user status is active or deleted, and if they are, log them out from application. I have created the code that works, and then I wanted to be a badass and create a service that will do this. But nooo. So, I created a service and it prints out the result, so it is registered and it is working. The problem is I guess that I cannot approach the same variables as I did in Controllers to my service class. Here is the code:

<?php

namespace WebBundle\Roles;

class Roles
{

public function getApplicationId($loggedUser, $request)
{
    // Get the current user role
    /** @var $userRole array */
    $userRole = $loggedUser->getRoles();

    // Check if the user role is super admin or admin - client
    /** @var $superAdmin bool */
    $superAdmin = in_array('ROLE_SUPER_ADMIN', $userRole) ? true : false;
    $admin = in_array('ROLE_ADMIN', $userRole) ? true : false;
    if ($superAdmin) {
        /** @var $application int */
        $application = $request->get('application');
    } elseif ($admin) {
        /** @var $application int */
        $application = $loggedUser->getAppClient()->getId();
    }
    return $application;
}

public function logoutInactiveAndDeletedUsers($loggedUser)
{
    // Log out inactive or deleted users.
    if ($loggedUser->getStatus()->getStatus() == 'inactive' || $loggedUser->getStatus()->getStatus() == 'deleted' ) {

        //$this->get('security.context')->setToken(null);
        //var_dump('test');exit;
        return $this->container->render('WebBundle:Default:login.html.twig', array('last_username' => null, 'error' => null,));
    }
}
}

So, this first service getApplicationId is working fine. But the other one is causing me real trouble. So the serivce is breaking when I call both:

$this->get('security.context')->setToken(null);

and

 return $this->container->render('WebBundle:Default:login.html.twig', array('last_username' => null, 'error' => null,));

But If I put this code in Controller, it works perfectly. It destroys the token and redirect the user to the login page. Please, help me understand how to make it work as a service to.

Upvotes: 0

Views: 36

Answers (1)

Milo
Milo

Reputation: 13

Ok, I figure out how to call a view:

In services.yaml add templating as an argument

    arguments: [@templating]

Then create a property and assign it to a constructor:

private $templating;

public function __construct($templating)
{
    $this->templating = $templating;
}

And call it like $this:

$this->templating->render('WebBundle:Default:login.html.twig', array('last_username' => null, 'error' => null,));

Now I need to find a solution how to disable token for the user. If anybody know help me out dude (I am not stoner anymore).

Upvotes: 0

Related Questions