Fahad Iqbal Ahmad Khan Fahad Iqbal Ahmad Khan - 1 year ago 74
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:


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 Source

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 :

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download