1
votes

I have a php snippet in Symfony2 where I say: If the user exists -> return these data sets in an array to the template else -> return name=> 'user not found'. Below is the only way this can work if I have in my twig only the variable 'first_name' being used.

Clear Problem Explanation: If the user doesn't exist in the database, I cannot call user.name, user.username, user.password. Even if the if conditional isn't satisfied, twig still tries to evaluate that inside statement.

What I want to say is:

if (user) {

{{ user.name }}<br>
{{ user.username }}<br>
{{ user.password }} <br>

 }

else {
User not found
}

However, if the user isn't found, it will still try and execute the DB access from the variable user ... user.name.. etc. How can I fix this?

PHP Snippet

    /**
     * @Route("/login/{username2}/{password2}")
     * @Template()
     */
    public function indexAction($username2, $password2)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $respository = $em->getRepository("SchachteUserBundle:user");

        $username = $username2;
        $password = $password2;
        $user = $respository->findOneBy(array("username"=>$username, "password"=>$password));

        if ($user) {
            return array('exists'=>true, 'first_name' => $user->getName(), 'username' => $user->getUserName(), 'password'=>$user->getPassword());
        }

        return array('exists'=>false, 'first_name' => 'USER NOT FOUND', 'username' => 'USER NOT FOUND', 'password'=>'USER NOT FOUND');
    }
}

TWIG

{% if exists == true %}

    Hello {{ first_name }}!

{% else %}

    Sorry, that user does not exist!

{% endif %}
1
Your question is not clear can add some more details specific to your problem ?M Khalid Junaid
updated the issue explanationrern
Try doing a var_dump($user); die; right before you do the if($user){ in the controller. You can see what value it has. Most likely it is an object.MiltoxBeyond
$user->getPassword()-> no.moonwave99

1 Answers

2
votes

Why not simply inject the return of your findOneBy in the template :

$user = $respository->findOneBy(array("username"=>$username, "password"=>$password));
return array('user'=>user);

Then in the template

{% if user %}
    {{ user.name }}<br>
    {{ user.username }}<br>
    {{ user.password }}
{% else %}
    User not found
{% endif %}

Moreover if you query the database with a password it means you have stored the clear password. It is very bad practice.