This is a solution in my project:
In edit.php file:
solution 1 (cate id is single number):
<?php
$cate_row = $db->fetchRow("SELECT cate_id, cate_name FROM categories WHERE cate_id=".$editdata[cate_id]." AND cate_status='Active'");
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
solution 2 (cate id is array: 12,4,5,6 or ,12,4,5,6,):
<?php
$cate_q = $db->query("SELECT cate_id, cate_name FROM categories WHERE cate_status='Active' ORDER BY cate_name ASC");
// array: ,12,4,5,6,
$editcate_array = explode(",", substr($editdata[cate_id], 1, $editdata[cate_id] - 1));
// or array 12,4,5,6
// $editcate_array = explode(",", $editdata[cate_id]);
while($cate_row = $db->fetch_array($cate_q)){
if(in_array($row['cate_id'], $editcate_array)) {
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
}
}
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
In JS global.js:
function AjaxCombo(elm, url, multiple) {
$(document).ready(function() {
$(elm).select2({
multiple: multiple,
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return {results: data};
}
},
// Add new category if no exist
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
$(elm).select2("data", JSON.parse($(elm).val()));
});
}
Default if form edit have cate data select2 init "id - Name category".
in file getCategories.php : from select you get $q = $input->gc['q']
and mysql is cate_name LIKE '%" . $q . "%';
while($row = $db->fetch_array($result)){
$dataArray[] = array("id"=>$row['cate_id'], "text"=>$row['cate_id']." - ".$row['cate_name']);
}
header('Content-Type: application/json');
echo json_encode($answer);
when get value form select2 you can try:
foreach ($_GET['select2'] as $value) {
echo $value;
}
done!