CakePHP Newbie :)
I am having trouble accessing another controller and passing that data to a view in one of my controllers:
In controllers/landings_controller.php:
var $uses = 'User';
function home() {
$userdata = $this->User->read();
$this->set(compact('userdata'));
}
In views/landings/home.ctp:
<?php
echo $this->userdata;
?>
When accessing /landings/home I get the following error:
Notice (8): Undefined property: View::$userdata [APP/views/landings/home.ctp, line 38]
I don't know what I am doing wrong. Any help?
Thanks!
$this->set('userdata', $userdata);
Compact returns a single array. $this->set expects two parameters.
http://book.cakephp.org/view/57/Controller-Methods
Correction:
set does in fact accept associative arrays (thanks Daniel Wright). Read below about using variables in views.
Also, variables are placed in scope -- not attached as members -- so you wouldn't do this in the view:
<?php echo $this->userdata ?>
but, rather:
<?php echo $userdata ?>
Assuming $userdata is a scalar, of course.
I think using compact is fine.You need know more about set().
Related
hello guys im having a problem with passing variable from my controller to views, as it does not identify its variable, here is my code:
RegisterController.php
use App\angkatan;
public function index()
{
$select = Angkatan::all();
return view('/auth/register')->with('name', $select);
}
My Route
web.php
Route::get('register', 'RegisterController#index');
and my view
register
#foreach($name as $ps)
#endforeach
the error say
Undefined variable: name (0)
im very thankful if anyone can help
You are just passing the wrong way $select variable to your view.
when you use Illuminate\View\View::with method you should pass an associative array which as key => value pairs
return view('/auth/register')->with(['name' => $select]);
You can also use compact which allows to pass variable which are accessible inside of the scope of your controller to the view and the string passed as argument to that function will be the name of variable accessible inside of the view file
$select = Angkatan::all();
return view('/auth/register', compact('select'));
You can not pass the variable in this way to the view. You have to pass an array in the second parameter of the with() method - it should be something like this:
return view('greeting', ['name' => 'James']);
return view('/auth/register', ['name' => $select]);
you can pass a second massive parameter to the view,
and also in with method, you need to pass massive as I remember.
I've been using 2 methods to render data.
The first one:
function name($id,$name){
return '<div id="'.$id.'">'.$name.'</div>';
}
echo implode($pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_FUNC,'name'));
The second one:
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
foreach($users as $user){
echo name($user->id,$user->name);
}
I don't really understand how PDO::FETCH_FUNC works. I already tried to figure it out. However, this is not so well-documented.
Could anybody please explain this fetch mode? And also, which one performs better? Thank you.
Both methods are wrong and you have to learn how to use templates and how to separate business logic from presentation logic.
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
tpl::assign('users', $users);
is ALL the code for the business logic part.
then in template
<?php foreach $users as $row): ?>
<div id="<?=$row->id?>"><?=$row->name?></div>
<?php endforeach ?>
Frankly, your business logic should contain not a trace of HTML while presentation logic should contain not a single database call.
Here is an example:
$stmt = $pdo->query('SELECT id, name FROM user');
$data = $stmt->fetchAll(PDO::FETCH_FUNC, array('Foo', 'name'));
Class Foo {
public static function name($id, $name) {
return '<div id="'.$id.'">'.$name.'</div>';
}
}
So basically FETCH_FUNC mode fetches records to user defined function. This is useful because you can manipulate the result.
Use static method if you are not passing in an object of the class. You can just pass in an object and not use static method just the way #Barmar noted in comments.
Seems like this shouldn't be that hard but is giving me fits.
Have variables initialized in the model's __construct method.
Need to access them in the view.html.php and default.php files.
In my model:
$this->MyVar = 'somevalue';
In my view.html.php:
$model = $this->getModel('mymodelname');
print_r($model) //checking, yes - the model's being pulled in
$myvar = $model->__construct($this->MyVar);
echo $myvar; //empty
What am I doing wrong and how do I fix it?
Thanks!
=========================================
Solution:
$model = $this->getModel('mymodelname');
echo $model->MyVar; // returns the variable in the model
__construct() does not return any value, this is why $myvar remains null. If you want, you can read more about it here
According to the specification (in the link above) you should pass to __construct an associative array that could hold one or more of the following fields:
'name'
'state'
'dbo'
'table_path'
and according to what you say - you pass a parameter. Try:
$arr = array('name' => $this->MyVar);
$model->__construct($arr);
Why use construct at all after you have instantiated the model simply do like this:
$model = $this->getModel('mymodelname');
$model->MyVar = $myvar;
in the sections_controller i use loadmodel to print username in sections/index file but i get error :
Notice (8): Undefined variable: user [APP\views\sections\index.ctp, line 3]
public function index ()
{
$this->loadModel('User');
$user = $this->User->find('all');
$this->Section->find('threaded', array('order' => array('Section.created ASC')));
$this->set('data','user');
}
in the sections/index
<div><?php echo $user['User']['username']; ?></div>
You have a typo, try :
$this->set('data',$user);
and then in your view :
<div><?php echo $data['User']['username']; ?></div>
Hope this helps !
You're not assigning the variable properly, try this instead:
$this->set('user', $user);
$user pointing to your find result and set as user, since that's what you're trying to call in your view. Or alternatively use the compact notation to achieve the same:
$this->set(compact('user'));
What you are doing now is setting a variable called data with the string value user, so when you would do this in your view:
echo $data;
It would return user as a string in your view.
EDIT
Since a find('all') will return an array, make sure you loop over the results in your view as well, like this:
foreach($user as $u) {
echo $u['User']['username'];
}
Or if you want a specific result, call it's array key, which for the first user would be:
echo $user[0]['User']['username'];
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.