I'm working with CakePHP 1.3. I'm making an AJAX call where I want the server to return some HTML that corresponds to several of rows of results that I can throw inside a <div>. I have the template for a single row stored as an element called 'library_track'. The element requires variables 'id', 'artist' and 'name' to be passed to it. I would like my function getResults() to return a block of HTML that is composed of HTML from several elements.
Can anyone show me what this code would look like please?
Just as usual, you'll probably have to loop through the results in your view:
Controller:
function getResults() {
// here be dragons
$this->set(compact('results'));
}
View /foo/getresults.ctp:
foreach ($results as $result) {
echo $this->element('library_track', array('id' => $result['Result']['id'], ...));
}
Related
I fetched data from model in controller . i want to display this data in view inside another view. its showing blank page.
here is my code..
controller -
public function Listblog()
{
$listblog=$this->Login->listblog();
$listblogwithpage=$this->load->view('list_blog',$listblog);
$this->load->view('Welcome_message',$listblogwithpage);
}
model -
public function listblog()
{
$query=$this->db->get('new_employee');
return $query->result();
}
To assign a view to a variable the 3rd param must be true:
$listblogwithpage=$this->load->view('list_blog',$listblog, true);
Further the 2nd param must be an array. E.g. $data['listblog'] = 123;
$var = $this->load->view('somepage', $data, true);
This applies to any usage of view.
If you want to pass data from a controller to the first view and then have the second view pass data to the second view, you should do the following, always remembering that CI expects data passed to a view to be in form of an array. Take this and feel free to adapt it to suit your needs
In controller:
// populate an array and pass it to the first view
$first_view_data = array(
'listblog' => $listblog_query_result,
);
$this->load->view('firstview', $first_view_data);
In the first view, populate a new array with whatever data you need and call the second view from within the first one, passing the second data array:
$second_view_data = array(
'second_data_var' => $variable,
'other_data_var' => $other_var,
);
$this->load->view('second_view', $second_view_data);
CI is intelligent enough to let you call a view from within a view and pass data from each to the next in this way. Just remember, it has to be an array.
Using the data:
In the first view you'd call $listblog
In the second view, you would access $second_data_var and $other_data_var
$listblog $second_data_var and $other_data_var each could be single variables, arrays, objects and mostly anything as long as they are passed to the view as elements of an array
try this way.
//Controller
function Listblog() {
$data = array();
$data['listblog']=$this->Login->listblog();
$this->load->view(''list_blog',$listblog');
}
in view page you have to call that data array $listblog
ok I have my route to my controller (for future crud maybe angular use)
public function Dashboard_Clicks()
{
$DBClicks = DB::table('TotalClicks')->select('Total_Clicks')->get();
return view::('dashboard.pages')->with('$DBClicks', Total_Clicks);
do I use view composer? or another clean simple way to call this in?
}
this has one result a number 45454
I want to be able to get this result in my view like so.
<h1 class="clicks"><strong>{{ $DBClicks->Total_Clicks }} </strong> </h1>
You can try this: (Laravel 5)
return view('dashboard.pages', ['Total_Clicks' => $DBClicks]);
As far as I can recall there are two ways of passing data from controller to views first is compacting the variable in your controller and it will available as it is in your view. An example for the same is following:
$variable = 'somedata';
$array = ['some' => 'data'];
return view('viewName', compact('variable', 'array'));
//now in your view you can access {{$variable}} and #foreach($array as $something)
Second is with :
return view('viewName')->with(['first_var' => $variable, 'first_array' => $array])
//now in your view you can access {{$first_var}} and #foreach($first_array as $array)
What do I want to do
I want to list data that is pulled from the database with a certain condition.
What do I have and what does it do
I have a function that calls the data. When I print_r the data, it throws the correct stuff, so the query is executing directly. However, the display isn't working. It shows all the data in the database.
Here is my function:
public function myfunction() {
$adminExtensions = $this->AdminExtension->find('all',
array(
'conditions' => array('location_id'=>'3')
)
);
//print_r($adminExtensions);
$this->set('adminExtensions', $this->paginate());
}
What is the problem
The problem, as stated, is that it doesn't list just the records with location_id == 3. It lists everything.
I have narrowed it down to the last line of the function, but I can't seem to get the right code in there.
My display file (myfunction.ctp) is a basic baked cakePHP index file.
What am I doing wrong?
The code you currently have calls two different find operations. $this->AdminExtension->find() will return an array with all the AdminExtensions with a location_id of 3. The second $this->paginate() call just returns all possible results suitable for pagination in the view.
If you want to filter the paginated results you have to either configure the $paginate variable in the Controller or do it directly before you call $this->paginate.
class PostsController extends AppController {
public $paginate = array(
'conditions' => array('location_id'=>'3')
);
}
This will adjust pagination for all $this->paginate calls in the controller.
To do it for only one paginate call:
public function your_view() {
$this->set('adminExtensions', $this->paginate('AdminExtension', array('location_id' => '3')));
);
I consider myself as a php beginner, so it may be possible that this question is too easy for someone, but I got really confused on how to solve it. I am trying to loop something from the database in my views. So, in a quick way I solved it like this:
I've created a function in my model that does the loop and in the same time is creating the html and saves it in a variable. Then, I get that variable from my controller and I pass it in my view. But, it seems that this is not a good way to solve it, since if I want to change my html I need to enter my model function instead some of the view files.
Then, I've created another function in my model that looks like this:
function displayUsers() {
$sql = $this->pdo->prepare('select * from user');
$sql->execute();
while($row = $sql->fetch())
$results[] = $row;
return $results;
}
Now... I take the result in my controller, and send it in the view, but then... I don't know how to extract the results from my variable. I have done something like this:
while($output) {
foreach($output[$i] as $key => $value)
$data[$key] = $value;
echo $data['email'];
$i++;
}
But then, in the end it says to me undefined offset, which means I am referring to an array key that doesn't exist. Can anyone help me on how to solve this issue?
Proper MVC shouldn't have any output in the model or the controller.
Ideally you would have a model that just gets the raw data and returns it in the controller. The controller can then build up an array of values that we'll call data. For example:
Controller
$data['users'] = $this->MyModel->getusers(); // Getting the users from your model
$data['posts'] = $this->MyModel->getposts(); // Getting the posts from your model
$this->getTemplate('userdisplay', $data); // Get the template userdisplay and pass data
This gets the data from the model, and then assigns it to a key within the "data" variable. You can then pass the data variable into the template. You'll then have two variables to work with in the template, $users and $posts.
You'll need a "getTemplate" function that properly maps the data array to individual variables for use in the template, but all of the display should be located in the template.
To answer your specific question at the end, something like this should work in the template:
if (count($users) > 0) {
foreach ($users as $person) {
echo $person['email'];
}
}
You should be able to do this:
foreach($output as $row) {
echo $row['email'];
}
I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.