The following code works. However I was wondering if there was a way to clean up the top part where the columns are outputted as an array.
I didn't include the full script because it is too long, but basically I have three different queries and I want to match the values from the table (resultInput...textarea...images) with the editable values I defined.
In order for me to do this I need to have the columns outputted as an array.
I was wondering if there was a cleaner way of doing this? (top-part until //end output as array)?
$ArrayResultInput = array();
while ($row = mysql_fetch_array($resultInput)) {
$ArrayResultInput[] = $row['Field'];
}
$inArrayResultInput = $ArrayResultInput;
//
$ArrayResultTextarea = array();
while ($row = mysql_fetch_array($resultTextarea)) {
$ArrayResultTextarea[] = $row['Field'];
}
$inArrayResultTextarea = $ArrayResultTextarea;
//
$ArrayResultImages = array();
while ($row = mysql_fetch_array($resultImages)) {
$ArrayResultImages[] = $row['Field'];
}
$inArrayResultImages = $ArrayResultImages;
// end output as array
while ($row = mysql_fetch_assoc($resultUpdate)) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $inArrayResultInput)) {
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ', $fieldname)) . '<br><input name="' . $fieldname . '" type="text" class="input" value="' . $value . '"><br></label></div>';
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $inArrayResultTextarea)) {
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ', $fieldname)) . '<br><textarea name="' . $fieldname . '">' . $value . '</textarea><br></label></div><script type="text/javascript">CKEDITOR.replace(\'' . $fieldname . '\',{toolbar:\'Basic\'});</script>';
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $inArrayResultImages)) {
echo '<div class="wrapper"><span class="form-file">' . ucfirst(str_replace('_', ' ', $fieldname)) . '</span><input id="' . $fieldname . '" name="' . $fieldname . '" type="input" class="input" value="' . $value . '"><input type="button" value="Browse" onclick="CKFinder.popup(\'../\', null, null, SetFileField_' . $fieldname . ');" class="button browsebttn medium"><br></div><script type="text/javascript">function SetFileField_' . $fieldname . '(fileUrl){document.getElementById(\'' . $fieldname . '\').value=fileUrl;}</script>';
}
}
}
Related
I have a form that sends customer data to the database, I added a choice of another category of customers through the input, and instead of sending the data in text, a number is sent.
db
In View
<?php echo render_select('sellers',get_sellers(),array('articleid','subject'),''); ?>
echo render_select helper:
function render_select($name, $options, $option_attrs = [], $label = '', $selected = '', $select_attrs = [], $form_group_attr = [], $form_group_class = '', $select_class = '', $include_blank = true)
{
$callback_translate = '';
if (isset($options['callback_translate'])) {
$callback_translate = $options['callback_translate'];
unset($options['callback_translate']);
}
$select = '';
$_form_group_attr = '';
$_select_attrs = '';
if (!isset($select_attrs['data-width'])) {
$select_attrs['data-width'] = '100%';
}
if (!isset($select_attrs['data-none-selected-text'])) {
$select_attrs['data-none-selected-text'] = _l('dropdown_non_selected_tex');
}
foreach ($select_attrs as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_select_attrs .= $key . '=' . '"' . $val . '" ';
}
$_select_attrs = rtrim($_select_attrs);
$form_group_attr['app-field-wrapper'] = $name;
foreach ($form_group_attr as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_form_group_attr .= $key . '=' . '"' . $val . '" ';
}
$_form_group_attr = rtrim($_form_group_attr);
if (!empty($select_class)) {
$select_class = ' ' . $select_class;
}
if (!empty($form_group_class)) {
$form_group_class = ' ' . $form_group_class;
}
$select .= '<div class="select-placeholder form-group' . $form_group_class . '" ' . $_form_group_attr . '>';
if ($label != '') {
$select .= '<label for="' . $name . '" class="control-label">' . _l($label, '', false) . '</label>';
}
$select .= '<select id="' . $name . '" name="' . $name . '" class="selectpicker' . $select_class . '" ' . $_select_attrs . ' data-live-search="true">';
if ($include_blank == true) {
$select .= '<option value=""></option>';
}
foreach ($options as $option) {
$val = '';
$_selected = '';
$key = '';
if (isset($option[$option_attrs[0]]) && !empty($option[$option_attrs[0]])) {
$key = $option[$option_attrs[0]];
}
if (!is_array($option_attrs[1])) {
$val = $option[$option_attrs[1]];
} else {
foreach ($option_attrs[1] as $_val) {
$val .= $option[$_val] . ' ';
}
}
$val = trim($val);
if ($callback_translate != '') {
if (function_exists($callback_translate) && is_callable($callback_translate)) {
$val = call_user_func($callback_translate, $key);
}
}
$data_sub_text = '';
if (!is_array($selected)) {
if ($selected != '') {
if ($selected == $key) {
$_selected = ' selected';
}
}
} else {
foreach ($selected as $id) {
if ($key == $id) {
$_selected = ' selected';
}
}
}
if (isset($option_attrs[2])) {
if (strpos($option_attrs[2], ',') !== false) {
$sub_text = '';
$_temp = explode(',', $option_attrs[2]);
foreach ($_temp as $t) {
if (isset($option[$t])) {
$sub_text .= $option[$t] . ' ';
}
}
} else {
if (isset($option[$option_attrs[2]])) {
$sub_text = $option[$option_attrs[2]];
} else {
$sub_text = $option_attrs[2];
}
}
$data_sub_text = ' data-subtext=' . '"' . $sub_text . '"';
}
$data_content = '';
if (isset($option['option_attributes'])) {
foreach ($option['option_attributes'] as $_opt_attr_key => $_opt_attr_val) {
$data_content .= $_opt_attr_key . '=' . '"' . $_opt_attr_val . '"';
}
if ($data_content != '') {
$data_content = ' ' . $data_content;
}
}
$select .= '<option value="' . $key . '"' . $_selected . $data_content . $data_sub_text . '>' . $val . '</option>';
}
$select .= '</select>';
$select .= '</div>';
return $select;
}
get sellers arrays in db functions
function get_sellers()
{
$CI = & get_instance();
return $CI->db->get(db_prefix() . 'sellers')->result_array();
}
I have created a column "sellers" in my table but it sends numbers and not text.
I need it so that when the form is saved it will submit the title and display it in the selection.
Thanks you
View form:
click
I am nearing completion of this code / plugin and I just have one bit to finish up before we make it all pretty and presentable; I am attempting to get my PHP file to re-load/re-fresh with the POST variables sent from the AJAX file, all from the response of the AJAX send:
$("#CategoryTree").load("poster.php #CategoryTree");
Right now on clicking a list item the CSS fires, the ajax fires and responds, variables are sent (checked them in the action registry as well all good there) but the area I call to re-load with the poster.php #CategoryTree does not react, error 500 is thrown.
Here is my full Javascript code:
jQuery(document).ready(function($) {
$('#CategoryTree').on('click', 'input[type=checkbox]', function() {
var $this = $(this);
var data = '';
if ($this.is(":checked")) {
$this.addClass('selectCheckbox');
//$this.val("1");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 1
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
//alert('Got this from the server: ' + response);
$("#CategoryTree").load("poster.php #CategoryTree");
//alert( "Load was performed." );});
console.log(response);
});
} else {
$this.removeClass('selectCheckbox');
//$this.val("0");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 0
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
// alert('Got this from the server: ' + response);
console.log(response);
});
}
});
});
And here is the PHP code (Line 55 is where the check starts):
<?php
//$message = "Started";
//echo "<script type='text/javascript'>alert('$message');</script>";
$thearray = [];
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories = $term->name;
array_push($thearray, $categories);
}
$categoryLines = $thearray;
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '/');
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '/', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$thelink = '';
$opener = 0;
if (substr_count($currentPath, '/')==5){
$patterns = array(" ", "/", ".");
$thelink = 'http://caap.co.nz/?pa_mymelp=' . strtolower(str_replace($patterns, '-', $currentPath));
$str .= '<li title="' . $currentPath . '">' . '<input value ="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . '' . $node . '</label>' .
/*displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
*/'</li>';}
else
{
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
}
}
$str .= '</li></ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "CategoryTree", '/');
/*
function add_query_vars_filter( $vars ){
foreach (array_keys(Contracts::$query_params) as $name)
$vars[] = $name;
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
*/
?>
Here is the pertinent code from the PHP file
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
Remove semicolon after if curly braces. if{}; to if{}
if (isset($_POST['catID'])){$cat = $_POST['catID'];};
replace it to
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
Now your code looks like.
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1){
$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);
}
In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
In my foreach loop I want the item that comes in the IF not te be outputted anymore after the if statement. It keeps coming back... How can I fix this?
$content1 = "";
foreach($array as $key => $value) {
if(!empty($brandnid)) {
$content1 .= ',"' . $key . '":{"und":[{"nid":"[nid:' . $value . ']"}]}';
unset($array[array_search('field_brandid',$array)]);
}
$content1 .= ',"' . $key . '":{"und":[{"value":"' . $value . '"}]}';
}
if(!empty($title) && !empty($day) && !empty($month) && !empty($year)) {
$postContent = '{"type":"carmodels","title":"' . $title . '"' . $content1 . ',"field_modelyear":{"und":[{"value":{"date":"' . $dateBuild . '"}}]}}';
}elseif(!empty($day) && !empty($month) && !empty($year)) {
$postContent = '{"type":"carmodels","field_modelyear":{"und":[{"value":{"date":"' . $dateBuild . '"}}]}' . $content1 . '}';
}else {
$postContent = '{"type":"carmodels"' . $content1 . '}';
}
In above case I entered fields color (normal field) and the brandid and it displays the following in $postContent:
{"type":"carmodels","field_modelcolor":{"und":[{"nid":"[nid:black]"}]},"field_modelcolor":{"und":[{"value":"black"}]},"field_brandid":{"und":[{"nid":"[nid:24]"}]},"field_brandid":{"und":[{"value":"24"}]}}
But it should only do the brandid in the if statement (once) and after that the normal field which doesnt reach the IF also once
I'm trying to take a multidimensional array and convert it into HTML form fields, like this:
<input type="hidden" name="c_record[contact][0][name]" value="First Last">
<input type="hidden" name="c_record[contact][0][date_submitted][date]" value="2010-01-01">
<input type="hidden" name="c_record[contact][0][date_submitted][hour]" value="10">
<input type="hidden" name="c_record[contact][0][date_submitted][min]" value="08">
<input type="hidden" name="c_record[contact][0][date_submitted][sec]" value="16">
<input type="hidden" name="c_record[contact][0][ip_address]" value="192.168.1.1">
Here is what I have so far:
$fields = array(
'c_record' => array(
'contact' => array(
0 => array(
'name' => 'First Last',
'date_submitted' => array(
'date' => '2010-01-01',
'hour' => '10',
'min' => '08',
'sec' => '16',
),
'ip_address' => '192.168.1.1',
),
),
),
);
$form_html = array_to_fields($fields);
function array_to_fields($fields, $prefix = '') {
$form_html = '';
foreach ($fields as $name => $value) {
if ( ! is_array($value)) {
if ( ! empty($prefix)) {
$name = $prefix . '[' . $name . ']';
}
// generate the hidden field
$form_html .= Form::hidden($name, $value) . EOL;
} else {
if ( ! empty($prefix)) {
$prefix .= '[' . $name . ']';
} else {
$prefix = $name;
}
$form_html .= array_to_fields($value, $prefix);
}
}
return $form_html;
}
This works fine until ip_address, which results in:
<input type="hidden" name="c_record[contact][0][date_submitted][ip_address]" value="192.168.1.1">
And any additional fields after ip_address keep having the previous field names added to them.
How can I make this work?
You could manhandle http_build_query into service for this purpose, since it naturally creates the scrunched-together keys you're looking for. If you wait until the end to urldecode your keys and values, it's easy to explode the output, since any = or & in a key or value will be safely encoded.
function array_to_fields($array) {
$html = '';
$entries = explode('&', http_build_query($array));
foreach ($entries as $entry) {
list($key, $value) = explode('=', $entry);
$html .= Form::hidden(urldecode($key), urldecode($value)) . EOL;
}
return $html;
}
You are updating $prefix in the current scope before you pass it into the recursive function. You don't want to do that. For multi-valued arrays it means that in the next iteration of the current function the prefix is going to contain the name of the previoust array. You can work around this by passing an updated prefix to the recursive function independent of $prefix.
function array_to_fields($fields, $prefix = '') {
$form_html = '';
foreach ($fields as $name => $value) {
if ( ! is_array($value)) {
if ( ! empty($prefix)) {
$name = $prefix . '[' . $name . ']';
}
// generate the hidden field
$form_html .= Form::hidden($name, $value) . EOL;
} else {
if ( ! empty($prefix)) {
$subprefix = $prefix . '[' . $name . ']';
} else {
$subprefix = $name;
}
$form_html .= array_to_fields($value, $subprefix);
}
}
return $form_html;
}
Try that.
As a hack and temporary solution, I did the following, although it's damn ugly and not flexible:
foreach ($fields as $name1 => $value1) {
if ( ! is_array($value1)) {
$form_html .= Form::hidden($name1, $value1) . EOL;
} else {
foreach ($value1 as $name2 => $value2) {
if ( ! is_array($value2)) {
$form_html .= Form::hidden($name1 . '[' . $name2 . ']', $value2) . EOL;
} else {
foreach ($value2 as $name3 => $value3) {
if ( ! is_array($value3)) {
$form_html .= Form::hidden($name1 . '[' . $name2 . '][' . $name3 . ']', $value3) . EOL;
} else {
foreach ($value3 as $name4 => $value4) {
if ( ! is_array($value4)) {
$form_html .= Form::hidden($name1 . '[' . $name2 . '][' . $name3 . '][' . $name4 . ']', $value4) . EOL;
} else {
foreach ($value4 as $name5 => $value5) {
if ( ! is_array($value5)) {
$form_html .= Form::hidden($name1 . '[' . $name2 . '][' . $name3 . '][' . $name4 . '][' . $name5 . ']', $value5) . EOL;
} else {
foreach ($value5 as $name6 => $value6) {
if ( ! is_array($value6)) {
$form_html .= Form::hidden($name1 . '[' . $name2 . '][' . $name3 . '][' . $name4 . '][' . $name5 . '][' . $name6 . ']', $value6) . EOL;
} else {
throw new Kohana_Exception('There are no levels than are supported by array_to_fields . Ending entire loop');
}
}
}
}
}
}
}
}
}
}
}
}