This topic is locked

Create a multiselect control with indented group options

8/27/2012 9:08:21 PM
PHPRunner Tips and Tricks
F
FunkDaddy author

So, if you are interested in adding a control like this: http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_optgroup
Follow these steps:

  1. In the add or edit page where you want to add a optgroup go ahead and insert a PHP Snippet using visual editor next to the control that holds that value in your database (for whatever field you want to have the multiple selection options). Note, this works for simple single line dropdown control or multiple line option select control.
  2. Insert the following code (replace :



Global $conn;

$strSQL = "SELECT * FROM whatever_table_you_want_to_populate_control_data_with";

$result = db_query($strSQL,$conn);

$group = array();
$str = "";

$str.= "<select multiple=\"multiple\" size=\"20\" id=\"give_your_control_a_name\" style=\"width:200px;white-space:nowrap;\">";

$str .= "<option value=\"\">Select Category</option>";

while ($row = mysql_fetch_assoc($result))

{

$group[$row['Your_Grouping_Column_Name']][] = $row;

}

foreach ($group as $key => $values_mbr)

{

$str.= '<optgroup label="'.$key.'">';

foreach ($values_mbr as $value_mbr)

{

$str.= '<option value="'.$value_mbr['Value_You_Want_Stored_In_DB'].'">'.$value_mbr['Your_Column_Display_Name'].'</option>';

}

$str.= '</optgroup>';

}

$str.="</select>";

echo $str;


3. Now if you compile your app you should see the dropdown (in this example I actually used the multiple select option instead) control.
4. Now you must bind the selection made by your user in that control to the field you want to store in your database, thus add some JS to the JavaScrip onLoad event of that form and use JQuery to help out as follows:



//hide default PHPR field to receive multiselect input value

//Using Jquery with wildcard selector in case this is displayed in popup

$("[id^=value_Purchase_Categories_]").css('display','none');
//Grab existing value on load and populate multiselect (only for edit forms of course)

//Need this so stored values shows up in the php snippet control you created

var existing_value = $("[id^=value_Purchase_Categories_]").val();

var arrayArea = existing_value.split(',');

$('#select_CategoryID').val(arrayArea);
//Populate hidden field with values from php snippet conrol

$('#select_CategoryID').change(function() {

var current_value = $('#select_CategoryID').val();

$("[id^=value_Purchase_Categories_]").val(current_value);

});


5.That it, you are done. Of course if you want to tweak things you can always alter your $strSQL query to populate different results for specific users, etc. Lastly I must give credit for inspiration from this forum //http://www.webdesignerforum.co.uk/topic/23899-looping-mysql-records-in-php-for-optgroup-lists/
Cheers,