Fahad Iqbal Ahmad Khan Fahad Iqbal Ahmad Khan - 6 days ago 6
PHP Question

Twig showing keys also instead of only values

I am using Laravel 5.3 along with Twig templating engine (Not Blade). I am trying to generate a list of drop-down list in the form. Instead of showing just the values. It is showing the keys as well.

For example:

{"display_name":"Admin"}


In my view the code is

{{ form_select('roles', roles, input_get('role'), {id:'user_type',class:'form-control'}) }}


In the controller

public function create()
{
$roles = Role::all('display_name');
return view('users.user-add')->with(['roles' => $roles]);
}


What am I missing?

Answer

I would suggest you to create a helper for this so that there is no requirement for you to pass roles from every controller to every view. Create a helper function like this :

if(!function_exists('getRoles'))
{
function getRoles()
{
    $roles = Role::get();
    foreach ($roles as $role)
    {
        $results[$role->id] = $role->name;
    }

    return $results;
}
}

and now in your template do :

{{ form_select('roles', getRoles(), input_get('role'), {id:'user_type',class:'form-control'}) }}

I hope I understood your question as intended and this helps you achieve what you are looking for.

Comments