Codeigniter passing data controller to view - php

Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.

To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link

How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.

Related

Converting array key and values into single variables

I know that you can use extract() to achieve this however my circumstances are as followed:
I am building a very small basic MVC framework for personal projects and I have this in my controller:
public function index(){
$data = [
'title' => 'Welcome'
];
$this->view('pages/index', $data);
}
As you can see this passes the data array into the view and you can echo it like:
echo $data['title'];
But I want to echo it like echo $title; I know that extract() can do this but that means I have to manually put extract($data); at the top of every page which isnt the end of the world but I was just curious if there was a way it could be done automatically? I have tried to use extract by putting it inside the view function but that did not work. I have also tried to use extract by putting it in the header file that is required_once in index.php (thus making the header file a static header thats always required) but neither has worked so any advice would be great.
Here is the code for the view function as requested:
public function view($view, $data = []){
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
Simple that is it ,use compact and extract function
index method
public function index(){
$title='Welcome';
$this->view('pages/index', compact('title'));
}
Wiew method
public function view($view, $data = []){
extract($data);
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
In html
<h1> hello <?php echo $title; ?></h1>
Here is where I went wrong, I put extract in the view method before and it didn't work.
However the advice here was to put it in the view function and I now understand that I put the extract function after require_once '../../views/'.$view.'.php'; I just put extract before that line of code and it is now working!

CodeIgniter fatal error: Call to a member function display_clients() on a non-object

I am writing a program that basically does stuff with a database, I am having trouble with some of the functionality though, this is what it is supposed to do
public function clist() {
$this->load->model('list_model');
$fields = $this->list_model->listcli();
if ($fields === $this->list_model->listcli()) {
$fieldl = $fields;
$this->load->view('clientlist');
$this->clientlist->display_clients($fieldl);
}
}
This loads the model which looks like this:
public function listcli()
{
$this->db->list_fields('clients');
}
}
Then runs the model function listcli so that it will list all the fields in the clients database and puts the value into $fields I then call it fieldl and load a view that will show the data, the view looks like this:
<html>
<body>
<p> sup </p>
<?php
function display_clients($fieldl)
{
?>
<html>
<body>
<p> sup2 </p>
<ul>
<?php
foreach ($fieldl as $l) {
?>
<li>
<?php echo $l;?>
</li>
<?php
}
}
Then calls the function inside the view and passed the data from $fieldl into it.
but I am getting the error " Call to a member function display_clients() on a non-object in /codeigniter/src/application/controllers/clientlist.php on line 40"
line 40 is
$this->clientlist->display_clients($fieldl);
Can you help? Please and thank you.
(I know this kind of question has been asked before but they are always very specific to the code at hand so doesn't help me, I am really new to CodeIgniter so if you can keep any answer relatively simple I will be grateful).
I needed to use the second parameter possible to pass my data over into the view, not my own makeshift solution for it, CI accepts an object as a second parameter for the CI_Loader::view()
Why can't you prepare the list in the controller and pass it to view via $data array?
$my_list = '<ul>';
foreach ($fieldl as $l) {
$my_list .= '<li>'.$l.'</li>';
}
$my_list .= '</ul>';
$data['my_list'] = $my_list;
then you can access it in view as $my_list. Just echo it where you need it.
EDIT:
AS per your own answer, yes - exactly. Using example above you would pass the $data to view as the second parameter:
$this->load->view('my_view',$data);
Then in the View, you access $data['my_list'] as $my_list, $data['foo'] as $foo etc.

placeholder attribute in zf2

How could insert the value of a field's db in the plcaholder in zf2
<div class="form_element">
<?php
$this->placeholder('name')->data = $this->data;
$name = $form->get('name');
echo $formLabel->openTag().$name->getOption('label')." ";
echo $this->formInput($name);
echo $formLabel->closeTag();
?>
</div>
A placeholder is a ViewHelper and therefore is is designed to help render view content.
In order to use your database data witin a placeholder you will need to ensure that the data is first passed to the view from the controller action.
public function modificaAlumnoAction()
{
//...
return ViewModel('data' => $data); // data passed to the view instance
}
Then within the view script
// modifica-alumno.phtml
$this->placeholder('foo')->data = $this->data;
An finally output the data (such as within the layout)
// layout.phtml
echo $this->placeholder('foo)->data;

where to process mysql queries in codeigniter?

Where should we process mysql queries in CodeIgniter application?
For example in a simple project we do like this :
for controller:
class Blog extends CI_Controller {
function posts(){
$data['query'] = $this->blog_model->index_posts();
$this->load->view('blog_view', $data);
}
}
and in view :
<?php
while ($post = mysql_fetch_object($query)):
?>
<div>
<p><?= $post->body; ?></p>
</div>
<?php endwhile; ?>
But, if we want to do something with body of post before print where should it be done?
For example, I want to write a function that formats the body of post and pass the body to it before doing echo.
Where should it be placed according to CoeIgniter's structure and recommended practices? (best option)
in the controller? (if so , how to use it)
in the view?
write a helper?
other approaches ?
Here's what is recommended:
Controller:
function posts() {
$this->load->model("blog_model");
$data['rows'] = $this->blog_model->index_posts();
$this->load->view("blog_view", $data);
}
Model: (blog_model.php)
function index_posts() {
$this->load->database();
$query = $this->db->get('your_table');
$return = array();
foreach ($query->result_array() as $line) {
$line['body'] = ... do something with the body....
$return[] = $line;
}
return $return;
}
View: (blog_view.php)
<?php foreach ($rows as $line): ?>
<div>
<p><?php echo $line['column']; ?></p>
</div>
<?php endforeach; ?>
Basically what happens is your model returns a multidimensional array that is passed the view and processed using a foreach() loop.
Good luck!
If you want to reuse that function create a helper. If you want this function only once put it in your controller and call from that controller.
Models are just for accessing database or maybe in few other cases, but mostly just for accessing things in database or editing, deleting etc. and sending the result to controller for further processing.
In your case I would stick with helper.
E.g. you will create a file top_mega_best_functions.php and put it inside helpers folder.
Than you write ther e.g. something like
function red_text($input) {
echo '<span style="color: red;">';
echo $input;
echo '</span>';
}
Then load the helper in your autoloader file or load before using.
And use in your view or controller like
$blablabla = "This text will be red";
red_text($blablabla);

CodeIgniter Template Library with a 2D array

I am using the following template library. What I am trying to do is to load one or more upper views inside a template,as an array so that I can easily load them in the template with a for-each loop.
This is a simple example on how it can be used on a controller:
function index() {
$data['title'] = 'My page title';
$partials = array('content'=>'c_location'); //Load view about inside the template.
$this->template->load('main', $partials, $data);
}
On the View you have an html like:
<html>
....
<?=$content?>
...
</html?>
This is what I am trying to use:
Controller:
$partials = array('content'=>'c_location',
array(
'first_upper_content'=>'1_u_location','second_upper_content'=>'2_u_location'
)
);
So for example I could pass for upper_content, a top header as "first_upper_content" and a slide for "second_upper_content" and then the remainder of the content for "content".
Html:
...
<?=$upper_content?>
<--if upper_content is a array,
I could display each content with a for loop-->
<?=$content?>
When I try everything I get:
Message: pathinfo() expects parameter 1 to be string, array given
Filename: core/Loader.php
Line Number: 759
How can I implement this? I am thinking of modifying the
// Load views into var array
Inside the Template.php & adding a foreach loop to the html;
This is what you want:
// Load views into var array
foreach(array_flat($view) as $key => $file)
Include the "array_flat" function call in Template.php, as shown above.
You will need to define this function. You can do this in any auto-loaded helper, or even include it the own Template class (in this case, you should call it as $this->array_flat in the code above). Here is it:
function array_flat($array)
{
$result = array();
foreach ($array as $key => $value)
{
if (is_array($value))
{
$result = array_merge($result, array_flat($value));
}
else
{
$result[$key] = $value;
}
}
return $result;
}
What you're trying to do is not possible with that library.
The error you received indicates the CI Loader class is being passed invalid data. So taking a look at the library's load function, your code will fail right here:
// Load views into var array
foreach($view as $key => $file)
{
$tpl[$key] = $this->CI->load->view($file, $vars, TRUE);
}
The library passes your nested array in $partials directly to the CI Loader. With your data, this line works out to:
$tpl[0] = $this->CI->load->view(array(
'first_upper_content'=>'1_u_location','second_upper_content'=>'2_u_location'
), vars, TRUE);
You can see in the CI user guide that isn't valid. It seems to me that your options are to either overhaul the library or change your approach.
Just make your main template view, and have something like this in it:
$this->load->view('header');
if (is_array($page) {
foreach($page as $key=>$val){
$this->load->view($key, $val); // $val being optional parameters
}
} else {
$this->load->view($page);
}
$this->load->view('footer');
In the controller, $data['page'] would contain view info, either its name (string) or an array of names to call in order. Of course, you'll have to have premade views with those names.
This was from the top of my head, but it should do what you wanted. This is done without template libraries, just plain CI.
To load partials, all you need to do is use:
$this->load->view('partial_location',$data);
inside your main view. So if you have a main view called home_page.php, and you want to load partials for headers and footers, you can just use:
$this->load->view('header');
// Main page layout
$this->load->view('footer');
If you want to use custom or different data inside your partials, just define them in your controller:
$data = array(
'content' => 'about',
'header_content' => 'Welcome to the site!',
'footer_content' => 'Made by me!'
);
And in your main view file:
$this->load->view('header',$header_content);
// would echo 'Welcome to the site!'
echo $content;
// would echo 'about'
$this->load->view('footer',$footer_content);
// would echo 'Made by me!'

Categories