I am creating dependent dropdown in which i want stay dropdown value after page reloading. & i found above error in controller file
public function get_reason_details(Request $req)
{
$reason_detail_id=Session::get('reason_detail_id');
$html = '';
$get_product_details =
DB::table("reason_details")->select("reason_details.*")->where('reason_id',$req->reason_id)->get();
foreach ($get_product_details as $product) {
$html .= '<option value="'.$product->reason_detail_id.'"'if($reason_detail_id==$product->reason_detail_id){selected="selected"} '>'.$product->reason_detail.'</option>';
}
return response()->json(['html' => $html]);
}
You are writing your if condition inside a php variable that is why you are getting this error.
To solve this you can write your if condition outside K variable and use a variable to select the dropdown. For e.g
foreach ($get_product_details as $product) {
$selected = "false";
if($reason_detail_id==$product->reason_detail_id) {
$selected="true";
}
$html .= '<option value="'.$product->reason_detail_id.'" selected="'.$selected.'" >'.$product->reason_detail.'</option>';
}
Related
I need to modify a site that was written in Codeigniter but I'm no expert.
One thing I'd like to do is modify a select control in a form to use ms-dropdown for a drop-down list including pictures.
However, I can't work out how to make the Codeigniter form helper render parameters other than ID and Value in each option. In this case, to make ms-dropdown work, it would need to also render data-image="..." in each option.
The current code looks like:
$dropdown = array(
'name'=>'MyDropDown',
'options' => array('Op1'=>'First Option', 'Op2' =>'Second Option')
);
echo form_dropdown($dropdown['name'],$dropdown['options']);
This renders as
<select name="MyDropDown">
<option value='Op1'>First Option</option>
<option value='Op2'>Second Option</option>
</select>
Is there a way for me to make Codeigniter render
<select name="MyDropDown">
<option value='Op1' data-image="filepath1">First Option</option>
<option value='Op2' data-image="filepath2">Second Option</option>
</select>
You can't. You would need to extend CI's Form Helper and modify
form_dropdown to accept other attributes like ID's
you will have to extend the helper .
to extend the native Form Helper you'll create a file named
application/helpers/MY_form_helper.php, and add or override
functions:
if you want to override function form_dropdown
simply write the function the way you want in MY_form_helper.php
here is the base function
if ( ! function_exists('form_dropdown'))
{
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
}
you have to edit this part ,
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
as you can see , only the option's value attribute is set by the function , you can edit this code and
do the thing you want ,
try it , if you could not do it , tell me i ll help you , but first give it a try :)
Consider doing something like this:
<script type="text/javascript">
var filepath = <?=json_encode($dropdown['filepath'])?>;
</script>
$dropdown['filepath'] would use the option value as keys and store the filepath as the value. Then you can simply access filepath[$(this).val()] upon change event.
Example output:
<script type="text/javascript">
var filepath = { 'Op1' : 'filepath1', 'Op2' : 'filepath2' };
$('select').bind('change', function() {
console.log(filepath[$(this).val()]);
});
</script>
As much as I love using data- attributes, one must not forget other ways to achieve their goals.
In case it helps anyone, I found a work-around using JQuery.
I made a javascript function that applied the data-image attribute to each option field once the page was ready, then called the msDropdown function afterwards.
function PiccifyShowDropdown(){
var Diagrams = new Array(
"/assets/images/icons/SixtyToHundredPercent.png",
"/assets/images/icons/LessThanThirtyPercent.png",
"/assets/images/icons/ThirtyToSixtyPercent.png",
"/assets/images/icons/SixtyToHundredPercent.png"
);
$("#Show > option").each(
function() {
$(this).attr("data-image",Diagrams[this.index]);
}
);
$("#Show").msDropdown({visibleRows:2});
}
This seems to have worked, so now I just need someone to solve the same problem as this guy...
My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}
OK, below is a get_members function in my controller that I pulled and manipulated from the interwebs... i can print out the information from $output in the controller, but I don't want to do that... I cannot figure out how to get it to be part of my view so I can list info from it freely...
I know it has something to do with the $data array in the index function... can anyone assist?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Phonedirectory extends CI_Controller {
function get_members($group=FALSE,$inclusive=FALSE) {
// Active Directory server
$ldap_host = "fps";
// Active Directory DN
$ldap_dn = "OU=Users,DC=xxx,DC=org";
// User attributes we want to keep
$keep = array(
"samaccountname",
"displayName",
"telephonenumber"
);
// Connect to AD
$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
ldap_set_option ($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($ldap, "CN=LDAP Reader,OU=Users - Special,DC=xxx,DC=org", "xxx") or die("Could not bind to LDAP");
// Begin building query
if($group) $query = "(&"; else $query = "";
$query .= "(&(objectClass=user)(objectCategory=person))";
// Filter by memberOf, if group is set
if(is_array($group)) {
// Looking for a members amongst multiple groups
if($inclusive) {
// Inclusive - get users that are in any of the groups
// Add OR operator
$query .= "(|";
} else {
// Exclusive - only get users that are in all of the groups
// Add AND operator
$query .= "(&";
}
// Append each group
foreach($group as $g) $query .= "(memberOf=OU=$g,$ldap_dn)";
$query .= ")";
} elseif($group) {
// Just looking for membership of one group
$query .= "(memberOf=OU=$group,$ldap_dn)";
}
// Close query
if($group) $query .= ")"; else $query .= "";
// Uncomment to output queries onto page for debugging
// print_r($query);
// Search AD
$results = ldap_search($ldap,$ldap_dn,$query);
$entries = ldap_get_entries($ldap, $results);
// Remove first entry (it's always blank)
array_shift($entries);
$output = array(); // Declare the output array
$i = 0; // Counter
// Build output array
foreach($entries as $u) {
foreach($keep as $x) {
// Check for attribute
if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;
// Append attribute to output array
$output[$i][$x] = $attrval;
}
$i++;
}
return $output;
}
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$this->load->view('template/main', $data);
}
}
Correct me if I'm wrong, but it sounds like you just want the output sent to the view?
If that's the case, then add this to the index function
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$data['members'] = $this->get_members();
$this->load->view('template/main', $data);
}
or however you want to append that to your data array.
Then in the view you can do:
<?php echo print_r($members, TRUE); ?>
Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.
I have a question about using form_dropdown().
table:category
cat_id
cat_name
Controller:
function index()
{
$this->load->model('category_model');
$data['category'] = $this->category_model->cat_getallcat();
$this->load->view('category_input',$data);
}
Model:category_model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category')->result();
}
View:
<?php
$this->load->helper('form');
echo form_open('send');
$list[''] = 'Please select a Category';
foreach($query as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
echo form_dropdown('category', $list);
echo form_close();
?>
error obtained:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/category_input.php
Line Number: 28
the ->result() will return the first row only, so this function is what you want to loop over.
Model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category');
}
View
foreach($query->result() as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
EDIT:
Also, you are sending the result as $data['category'] then trying to access it as $query. So really the foreach would be foreach($category->result() as $row) in this example
You are asking foreach to loop over $query, but I you haven't set $query as a variable anywhere that I can see.
Since you set $data['category'] to hold your query result() in your controller, you need to loop over $category in the view:
foreach($category as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}