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.
Related
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>';
}
In this codeigniter model i have this query testing if value entered in input exists in database..
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Behold the controller i'd like to display value grabbed in input in view inscription.php
function search()
{
$data['row'] = $this->site_model->get_search_form();
$this->load->view('acceuil/aside');
$this->load->view('acceuil/inscription', $data);
}
My issue is how to display in that view input value and a form if this value exists in database ?
I have tried like this but i need help :
inscription view:
<?=form_open('navigation/search');?>
<input type="text" name="search1" id="search1" required />
<input type='submit' value='Display' />
<?=form_close();?>
I try to display the form like this but i don't know how to display as well the input value entered
<?php
if( $row > 0 )
{
?>
les champs du formulaire ici....
<?php
}else
{ }
?>
In your view you can check if the variable $row is not null (because it will be null when no rows are found):
if ($row !== null) {
// do stuff
}
You can modify the model function to return some other value if no rows are found, for example, by setting the $data to an empty array:
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
$data = array(); // <--- here
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
And then in the view you can simply loop the data:
foreach($row as $r) {
// do stuff
}
or you can implode the array to use as the input value:
<input type="text"
name="search1"
id="search1" required
value="<?php echo implode(' ', $row); ?>" />
You could also use html entities here, in case double quotes are possible to appear in what your model function returns (I have no idea what it returns).
you can access $data global object like this check
<?php
if( isset($row))
{
foreach($row as $v){
//Do the operations here
}
}else
{
//Do the operations here
}
?>
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
}
}
I have a edit view whose url is /group/edit/1 where 1 is the group id which is dynamic.
I am validating the form data in controller as :
if ($this->form_validation->run() == FALSE)
{
$this->load->view('group/edit', $data);
}
How do I pass the id parameter "1" to this view ?
Below option does not work since the url has to be group/edit/1
$this->load->view('edit', $data);
You're thinking about this wrong. You want to have a view called edit.php and pass the number 1 into it, or perhaps more to the point, you want to get the data for 1 from your model and pass the return value of your model into your view. Consider this:
controller
function edit($id)
{
$data['item_info'] = $this->whateverModel->getItem($id);
$this->load->view('edit', $data);
}
Then in your edit view, you can refer to the data like this:
view
echo $item_info['id'];
echo $item_info['name']; //or whatever you pass back from the model
Is this what you mean?
$this->load->view('group/edit/'.$parameter, $data);
That would make it load your 1, as you are simply defining the path of the VIEW document
Per CodeIgniters reference this is the format:
$this->load->view('folder_name/file_name');
http://codeigniter.com/user_guide/general/views.html
Not sure if you are confused by routing vs views, here is a quick difference:
If you want http://www.example/group/edit/10
then you need a route setup, not a view.
If you want http://www.example/ and to display the contents from page main.php (in your views folder) then you do $this->load->view('main'); inside your primary controller.
This is what I am doing. Is this acceptable ?
Controller action :
function edit($id)
{
$group_q = $this->db->query("SELECT * FROM groups WHERE id = ?", array($id));
$group_data = $group_q->row();
/* Form fields */
$data['name'] = array(
'name' => 'name',
'id' => 'name',
'value' => $group_data->name,
);
$options = array("A", "B", "C", "D");
$data['group_parent'] = $options;
$data['group_parent_status'] = $group_data->parent_id;
$data['group_id'] = $id;
/* Form validations */
$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[2]');
if ($this->form_validation->run() == FALSE)
{
if ($this->input->post('submit', TRUE))
{
$data['name']['value'] = $this->input->post('name', TRUE);
$data['group_parent_status'] = $this->input->post('group_parent', TRUE);
}
$this->load->view('group/edit', $data);
}
else
{
$data_name = $this->input->post('name', TRUE);
$data_parent_id = $this->input->post('group_parent', TRUE);
$data_id = $id;
if ( ! $this->db->query("UPDATE groups SET name = ?, parent_id = ? WHERE id = ?", array($data_name, $data_parent_id, $data_id)))
{
$this->session->set_flashdata('error', "Error");
$this->load->view('group/edit', $data);
} else {
$this->session->set_flashdata('message', "Success");
redirect('account');
}
}
return;
}
View file :
<?php
echo form_open('group/edit/' . $group_id); /***** NOTE THIS STEP *****/
echo "<p>";
echo form_label('Name', 'name');
echo "<br />";
echo form_input($name);
echo "</p>";
echo "<p>";
echo form_label('Parentp', 'group_parent');
echo "<br />";
echo form_dropdown('group_parent', $group_parent_active);
echo "</p>";
echo form_hidden('group_id', $group_id);
echo form_submit('submit', 'Submit');
echo form_close();
?>