Add or remove items from a comma separated list
I am having problems adding and / or removing items from a comma separated list. I am using a form field <select>
to select which elements to add and / or remove.
<select name="choices[]" multiple>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
// explode list from database (choices column)
$array = explode(',', $row->choices);
// loop through html select options
foreach(Input::get('choices') as $value)
{
// add selected items
if($value && !in_array($value, $array))
{
$array[] = $value;
}
// remove deselected items
if(!$value && in_array($value, $array))
{
$index = array_search($value, $array);
unset($array[$index]);
}
}
// re-delimit list; update database
$row->choices = trim(implode(',', $array), ',');
The function of adding items to the list works as intended. However, when you deselect items, it does not remove them from the list.
Any ideas?
source to share
As you step through Input::get('choices')
, this array only provides the user-selected items (which you would see if you printed it out). Input::get
doesn't know what possible values were in your HTML; it only knows what values were sent via HTTP GET.
So, your check for !$value
nothing - unselected values just won't be processed at all. If the values of the unselected values started in the database, they will remain there.
Isn't it better to start from scratch $array
? Then just copy the elements into it Input::get('choices')
? Then save this to the database.
source to share
Values that are not selected will not be present Input::get('choices')
, so if you choose option 2 and option 3 Input::get('choices')
would only contain them: ["2", "3"]
. All you have to do is concatenate and store the values from the query:
$choices = join(',', Input::get('choices'));
$row->choices = $choices;
$row->save();
source to share