1

I'm trying to return html, to my ajax request. The ajax request requests a controller method to create a view according to what is clicked.

It's a simple form. But it should have a <select> tag in it. The <select> tag should display different roles, with one role already selected. which can be assigned to different users.

So I tried creating an object as so:

 $roles = $this->database->GetAllRoles();
 $selectedRole = $this->database->GetAllRoles()->where('id', '=', $user->roles_id)->first();
 foreach($roles as $role){
    $selectObject = 
    '
    <option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>
    <option value="' . $roles->id . '">"' . $roles->name . '"</option>
    ';
 }
 $htmlFinal = 
 '
  <form>
  <!-- Form labels and inputs ... -->
  <select class="form-control" type="text">
     "' . $selectObject . '"
 ';

It should be

This is what it should look like, with a selected option in the form select tag, and more options when opened.

Obviously the above code doesn't work ofcourse, I tried alot of different approaches but I'm kind of stuck right now.

2 Answers 2

1

You are using = on the $selectObject variable inside the loop, so, the variable is overriden each iteration. You could use .= to append the HTML in the variable. Then, you shouldn't write the selected option inside the loop, because you will add it several times. Also, you use $roles but in your foreach, the current element is $role.

$selectObject = '<option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>';
foreach ($roles as $role) {
    $selectObject .= '<option value="' . $role->id . '">"' . $role->name . '"</option>';
}

Finally, to avoid a duplicate of the selected role, you could add a if to add only other roles.

$selectObject = '<option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>';
foreach ($roles as $role) {
    if ($role->id != $selectedRole['id']) {
        $selectObject .= '<option value="' . $role->id . '">"' . $role->name . '"</option>';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked! I see now how easy this was. I think I didn't see the bigger picture.
1

Make your foreach loop looklike this:

if(array_key_exists('id',$selectedRole) &&  $selectedRole['id']==$roles->id)
     <option value="' . $roles->id . '" selected >"' . $roles->name . '"</option>
else
   <option value="' . $roles->id . '">"' . $roles->name . '"</option>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.