How to de-select a value from a multi-select field?

Jay_Jiang
Level 10

Re: How to de-select a value from a multi-select field?

<?php

if(isset($_POST['data']) && isset($_POST['var'])){

$data = $_POST['data'];                                 // e.g. ";;product a;product b;;product c;;;;product d;product c;;product a; product a"

$var = $_POST['var'];                                   // e.g. "product c"

$data = array_unique(array_filter(explode(";",$data))); // cleans up extra ; and duplicate values e.g. "product a;product b;product c;product d"

unset($data[array_search($var, $data)]);                // removes the option from the multi select data

echo json_encode(array("response"=>implode(";",$data)));// map 'response' to update multi select field

}
?>

SanfordWhiteman
Level 10 - Community Moderator

Re: How to de-select a value from a multi-select field?

Gettin' there.

<?php

$purchases = "39;44;21;0;89";

assert( implode(array_filter(explode(";",$purchases)),";") == "39;44;21;0;89" ); // assertion failed

No embedded string values should be special in parsing. "0" is coerced to boolean false in PHP.

Jay_Jiang
Level 10

Re: How to de-select a value from a multi-select field?

<?php

if(isset($_POST['data']) && isset($_POST['var'])){

function chkVar($value) { return ($value !== null && $value !== false && $value !== ''); }

$data = $_POST['data'];                                          // e.g. ";;product a;product b;;product c;;;;product d;product c;;product a; product a"

$var = $_POST['var'];                                            // e.g. "product c"

$data = array_unique(array_filter(explode(";",$data),'chkVar')); // cleans up extra ; and duplicate values e.g. "product a;product b;product c;product d"

if(in_array($var, $data)){unset($data[array_search($var, $data)]);}  // removes the option from the multi select data e.g. "product a;product b;product d"

echo json_encode(array("response"=>implode(";",$data)));         // map 'response' to update multi select field

}

?>

SanfordWhiteman
Level 10 - Community Moderator

Re: How to de-select a value from a multi-select field?

I'll trust ya that it's working now.

But this is a great case of PHP showing its clunkiness and lack of fluency (in both senses of the word!).

Which is why I'd do it like this:

pastedImage_1.png