I have a controller with an index function as follows:
function index()
{
$this->load->model('products_model');
$data['product'] = $this->products_model->get(3); // 3 = product id
$data['product_no'] = 3;
$data['main_content'] = 'product_view';
//print_r($data['products']);
$this->load->view('includes/template', $data);
}
This is the get function in the products_model file
function get($id)
{
$results = $this->db->get_where('products', array('id' => $id))->result();
//get the first item
$result = $results[0];
return $result;
}
The products table contains fields such as name, price etc. Please can you tell me how to output variables from $data['product'] after it is passed into the view? I have tried so many things but nothing is working, even though the print_r (commented out) shows the data - it is not being passed into the view. I thought it may have been because the view calls a template file which references the main_content variable:
Template file contents:
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
but i tried creating a flat view file and still couldn't access the variables.
Many thanks,
your $data array is "ripped" into single variables within the view.
print $product;
print $product_no;
print $main_content;
Handling headers & footers this way sucks and get's unmanageable pretty quickly.
Try using my Template library, your data will be passed through to the product_view no problem.
Related
I am novice in Codeigniter and I am working on pagination. But there is something wrong in my code. What mistake I have been done in the following code?
I have attached my code snippet below.
Route
$route['default_controller'] = "pages";
$route['default_controller/(:num)'] = "pages/index/$1";
Controller
public function index($page='home')
{
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$config=[
'base_url' => base_url().'/pages/index',
'per_page' => 5,
'total_rows' =>$this->products_model->record_count()
];
$this->pagination->initialize($config);
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['products'] = $this->products_model->get_products($config['per_page'], $this->uri->segment(3));
$data['request'] = 'pages/home';
$this->load->view('templates/content',$data);
}
Model
public function get_products($limit, $offset)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
$query=$this->db->get('product');
return $query->result_array();
}
public function record_count($value='')
{
return $this->db->count_all("product");
}
View
<?php echo $this->pagination->create_links() ?>
In the View, I am displaying the records from a table. The first page of records displays, but when I click the second page it shows Error
"**404 Page Not Found**"
Any kind of help regarding this issue will be highly appreciated. Thanks in advance.
From your logic, the line "index($page='home') the index method gets the script to display from the parameter passed to it. On the first load, the default page, 'home.php' is matched, but when you select the second page, the CI router and index function look for maybe '1.php' or '2.php' and so on, depending on your paging, do those files exist for every page you request? Otherwise, you should instead check if the page variable is a valid page (e.g non-negative) then continue execution and load the results to your view
Is there any other best way to use session_data in website.
How i set session in my project:
$sess_array = array('id' => $row->user_id,'name'=>$row->user_name,'email'=>$row->email,'condition'=>'','balance'=>$row->balance,'did_alloted'=>$row->did_alloted,'create_date'=>$row->create_date);
$this->session->set_userdata('logged_in', $sess_array);
when it comes to controller:
$data['id'] = $session_data['id'];
$data['name'] = $session_data['name'];
$data['email'] = $session_data['email'];
$data['balance']=$session_data['balance'];
$data['did_alloted']=$session_data['did_alloted'];
$data['create_date']=$session_data['create_date'];
$this->load->view('san-reception', $data);
and in my view. I use <?php echo $name ?> to get session_data.
So is there any method by which i can directly access session_data in view without including as $data.
$this->session->userdata('logged_in'); will be available directly in views and hence you just need to assigned this to a variable and then use that as array like bellow.
$userdata=$this->session->userdata('logged_in');
now variable $userdata contain all array field that you set in controller and hence you can use it as $userdata['id'], $userdata['name'] etc
public function __construct()
{
parent::__construct();
$data['session_data']=$this->session->user_data('logged_in');
}
public function some_function(){
$data['dummy']="";
$this->load->view('someview3',$data)
}
public function some_function1(){
$data['dummy']="";
$this->load->view('someview1',$data)
}
public function some_function2(){
$data['dummy']="";
$this->load->view('someview2',$data)
}
If you assign that into the constructor then it will call by automatically whenever a function calls in the controller.
you can view it in you view page by,
print_r($session_data);
Can I set a variable in view file?
for exemple:
I have a controller: welcome.php
Its load:
$this->load->view('header');
$this->load->view('main');
$this->load->view('footer');
I need set a variable on file main.php and get on footer.php
Its possible?
You can pass a variable from one view to another just like you would from a controller to a view. You just have to load the view file that sets that variable before the view that uses that variable:
$this->load->view('main'); //load before
$this->load->view('footer'); //load after
Inside of main.php do $this->load->vars(array('your_variable'=>'it's value')); and you will be able to call it in the footer like you would any other variable. The only requirement is that main.php be loaded before footer.php.
It is not possible to set a variable in a view file and access it from another. There is no reason you should be setting variables in your view files anyway. The controller should be handling all of your application logic so you should be setting the variable there. I would recommend reading through the user guide or looking at some articles to get a better grasp of MVC principles.
To access the same variable in multiple views, pass it to each view you load.
// Set your variable
$data['variable'] = 'value';
// Pass variable to multiple views
$this->load->view('main', $data);
$this->load->view('footer', $data);
You can pass both array or object to your view, for example:
$data = new StdClass;
$data->title = "The Title";
$data->content = "The Content";
$this->load->view('main', $data);
or
$data = new SomeClass;
$this->load->view('main', $data);
Also, in each view you are able to pass a different data:
$data1 = array("key" => "val");
$data2 = $this->some_class->some_method($params);
$data3 = $this->another_class->another_method($params);
$this->load->view('navigation', $data1);
$this->load->view('main', $data2);
$this->load->view('footer', $data3);
Yes you can, to pass variable from controller you can type the variable data after the name of view, this is the example :
$data["vehicle"] = $vehicle;
$this->load->view('header',$data);
then in your view just call the name of variable :
<td>
<?php echo $vehicle ?>
</td>
Hope it can help
if i have to display some data from the database, how do i pass this data in the admin controller? Say i am defining a block in my controller
$block = $this->getLayout()->createBlock('core/text')->setText('<h1>Main Block</h1>');
Can i pass any sort of data to the setText() function to display the data i require in the admin page or are there other functions? I want to display a few order no from my custom table in the back end.
I tried something like this : $block = $this->getLayout()->createBlock('core/text')->setText('<h1>Main Block</h1><div>'.$this->showAllRecordsAction().'</div>');
The showAllRecordsAction() retrieves data from the custom table and displays it. When i try this out, i see the data at the top of the page and not in the content block.
How can i display it in a content block? Thanks.
I was able to get the content displayed through a block.
Used this code in my indexController :
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('adminhelloworld/view'))
->renderLayout();
This is my View.php in the Block/View.php
<?php
class Foostor_Adminhelloworld_Block_View extends Mage_Core_Block_Template
{
protected function _toHtml()
{
$html="";
$records = Mage::getModel('direcpay/database')->getCollection();
foreach($records as $db_record){
$html = $html . 'Order no : '.$db_record->getOrder_no().' Referecnce id : ';
$html = $html . $db_record->getDirecpay_refid()."<br/>";
}
return $html;
Hope this helps someone.
Im having a few problems with the form_dropdown function in CodeIgniter .... My application is in 2 parts, a user goes in, enters a form and submits it .... once its submitted a admin can go in and edit that persons form and then save it to database.
So, to display the dropdown in the initial form, im using the following ( all the options in the dropdown are coming from the database )
Model:
function get_salaries_dropdown()
{
$this->db->from($this->table_name);
$this->db->order_by('id');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0){
$return[''] = 'please select';
foreach($result->result_array() as $row){
$return[$row['id']] = $row['salaryrange'];
}
}
return $return;
}
Then in the Controller:
$data['salaries'] = $this->salary_expectation->get_salaries_dropdown();
Then finally the View:
<?php echo form_dropdown('salaries', $salaries, set_value('salaries', $salaries)); ?>
That bit works perfect in displaying the dropdown filled with values for the user to select.
So, when the user selects a value, then hits save, its saved to the database.
On the Edit page which the admin see's, im using the same code to display the dropdown filled with options, but how do i get it to automatically choose the one thats been selected by the user in the initial stage?
Cheers,
According to Codeigniter documentation
The first parameter will contain the
name of the field, the second
parameter will contain an associative
array of options, and the third
parameter will contain the value you
wish to be selected. You can also pass
an array of multiple items through the
third parameter, and CodeIgniter will
create a multiple select for you.
Your admin controller should have something like
$data['selected'] = $this->salary_expectation->get_salary_selected();
According to this, the admin view should be like this
<?php echo form_dropdown('salaries', $salaries, $selected_value); ?>
one nasty solution to select the <option> element of <select> generated by form_dropdown() function of the form_helper is using the post input sended.
I made this because any solutions I found doesn't display the value that the user select in the form neither set_selected nor set_vaule.
Well, in my controller I have:
$countries = $this->country_model->get_dropdown_array(); // The array have something like $countries[COUNTRY_ID] = COUNTRY_NAME
$data['countries']=$countries;
In my view:
$selected_country = $this->input->post('country');
echo form_dropdown('country',$countries,$selected_country);
And works fine !!! :)
The form_dropdown function has a third parameter for the selected option. Use it like this:
<?php echo form_dropdown('piece_type',
array(
'type1' => 'Firts type',
'type2' => 'Second option'
$selected_value,
'id = "piece_type"') ?>
I had the same problem but i have overcome on this problem using code igniter syntex.
Here is the solution.
Fisrt step
Before the loop initialize two arrays
$options = array();
$select = array();
Then in the loop write this instruction
foreach($result->result_array() as $row)
{
/////////Your Condition ////////////
if($row['id'] == $myarray['mycolumn'])
{
$options [$row['id']] = $row['salaryrange'];
$select = $row['id'] ;
}else{
$options [$row['id']] = $row['salaryrange'];
}
}
Now
echo form_dropdown('dropdown_name' , $options , $select);
It is working ok
For update case, you have pass corresponding value to view, if passing variable is like $ind_post(from controller ) then write this code like:
<?php echo form_dropdown('salaries', $salaries, $ind_post->salaries,''); ?>