I haven't gotten the hang of the extract() function, and transferring variables.
I have a method in a user controller where some variables are defined, and sent in an array to a view function in a parent controller, where the array is extracted. Then the view is required. But the variables turn out undefined. The array contents can be printed though.
Here is the user controller with a simplified profile function:
class User extends Controller{
public function profile(){
$profiledetails = $this->profiledetails();
$profilestatus = $this->profileStatus();
$this->view('profile', [$profiledetails, $profilestatus]);
}}
The variables are sent to the view function in parent Controller:
class Controller {
public function view($view, $variables =[]){
extract($variables);
require_once './app/views/' . $view . '.php';
}}
And in the view, 'profile.php', the undefined variable error is shown. I thought that the "extract()" function would make $profiledetails and $profilestatus available as variables in the view.
What am I doing wrong? Maybe I'm using the wrong type of array, or I should use "variabe variables" or something.. (in that case, how?).
extract works with an associative array.
$this->view('profile',
[
'profiledetails' => $profiledetails,
'profilestatus' => $profilestatus
]);
Related
I want to create a global array inside a controller class in laravel. I searched and explored many resources but couldn't find a proper answer. I want that array to be accessible by all the methods in that controller. Currently I have tried this :
public $members=array(1,2); Global variable
`global $members;` //Inside function
echo $members[0]; //Inside function
I tried to access the data in the array in the function but got a null exception.Please help me out.
You should use the $this keyword.
class x extends Controller {
public $members = array(1,2);
public function myAction(){
echo $this->members[0];
}
}
I have implemented a controller to give access of data of candidates.
class List_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$data[]=array();
/*
Here I want to get value of $area parameter, to save into logs
*/
$userId=$this->session->userdata('userId');
// save logs
$this->UrlAccessHistory->save($this->router->class,$this->router->method,$userId,"Web Application");
}
public function fetchList($area=null){
// fetch list of records from specified area
}
}
$this->router->className gives name of controller Class and $this->router->method gives name of of function called.
Please help to get the list of parameters at location (see comments in code) in the constructor, so that I can store it in the logs.
You could use the URI Class:
$this->uri->segment(n);
I have added a function inside controller to get list of controller parameters
function getControllerParametersFromUri($uri_string){
$list = explode("/",$uri_string);
// skip controller and method names from
// return array list
return array_slice($list,2);
}
// call function by passing uri_string to get parameters list
print_r($this->getControllerParametersFromUri($this->uri->uri_string()));
#Sujit Agarwal $this->uri->segment(3) also works,
but if we need list of all parameters then we may explode uri_string
I am using cakephp-2.x. I have one function name user_info() in the UsersController.php i want to access this in another controller name MessagesController.php
Code -
UsersController.php
public function user_info(){
$user_id=$this->Session->read('Auth.User.id');
$data=$this->User->findById($user_id);
$this->set('user_info',$data);
}
MessagesController.php
public function index(){
//$userInfo=new UsersController();
//$userInfo->user_info();
$this->user_info();
pr($data);
}
Error Message-
Fatal Error
Error: Call to undefined method MessagesController::user_info()
File: E:\xampp\htdocs\2014\myshowcam\msc\app\Controller\MessagesController.php
Line: 18
Notice: If you want to customize this error message, create app\View\Errors\fatal_error.ctp
Typically if you're trying to access a function in one controller from another controller you have a fundamental flaw in your project's logic.
But in general object usage is thus:
$otherController = new whateverMyControllerNameIs();
$otherController->functionName();
However I'm not familiar enough with cake to tell you the pitfalls of doing such a thing. For example I have no idea what this would do to routes or what other variables/objects are required to initialize a controller correctly.
EDIT:
Ref: CakePHP 2.3.8: Calling Another Controller function in CronController.php
App::import('Controller', 'Products'); // mention at top
// Instantiation // mention within cron function
$Products = new ProductsController;
// Call a method from
$Products->ControllerFunction();
Try requestAction function of cakephp
$result = $this->requestAction(array('controller' => 'users', 'action' => 'user_info'));
Why would a simple, When can complicated?
All the information for a registered user of User model is accessible in the following manner:
AppController.php
public $user_info; /* global scope */
public function beforeFilter(){
$this->user_info = $this->Auth->user(); // for access user data in any controller
$this->set('user_info_view',$this->Auth->user()); // for access user data in any view or layout
}
MessagesController.php
public function index(){
debug($this->user_info);
$my_messages = $this->Message->find('all',
array('conditions' => array('Message.user_id' => $this->user_info['id']))
}
....
layout or view.ctp
<?php echo $user_info_view['name']; ?> // email, etc
Why not take advantage of the way CakePHP handles relationships? There's a very easy way to achieve what you're trying to do without extending controllers or loading in additional controllers which seems excessive for your example.
Inside AppController's beforeFilter()
Configure::write('UserId', $this->Session->read('Auth.User.id'));
This will allow you to access the UserID from your models
Inside your User's model, create the following function
/**
* Sample query which can be expanded upon, adding fields or contains.
*
* #return array The user data if found
*/
public function findByUserId() {
$user = $this->find('first', array(
'conditions' => array(
'User.id' => Configure::read('UserId')
)
));
return $user;
}
Inside your Users controller (Minimal is better, no?)
public function user_info() {
$this->set('user', $this->User->findByUserId());
}
Inside your Messages controller
public function index() {
$this->set('user', $this->Message->User->findByUserId());
// --- Some more stuff here ---
}
And that's it, no need to be extending controllers, just make sure your Message and User model are related to each other, failing that you can bindModel or use ClassRegistry::init('User')-> for example.
I am currently learning how to use CakePhp.
I have created a function in my custom controller as follows:
class FormatsController extends AppController
{
// ....
function admin_add()
{
// if the form data is not empty
if (!empty($this->data)) {
// initialise the format model
$this->Format->create();
// create the slug
$this->data['Format']['slug'] = $this->slug($this->data['Format']['name']);
// try saving the format
if ($this->Format->save($this->data)) {
// set a flash message
$this->Session->setFlash('The Format has been saved', 'flash_good');
// redirect
$this->redirect(array('action' => 'index'));
} else {
// set a flash message
$this->Session->setFlash('The Format could not be saved. Please, try again.', 'flash_bad');
}
}
}
}
However in my view I am getting this error:
Error: Call to a member function create() on a non-object
Why is this error caused and how can I fix it?
My apologies, I believe the line it is referencing is not in the Controller but in my view itself. It refers to my view which has the following line:
<?php echo $form->create('Format');?>
Is there something else I need to declare before using this? i.e. $this->Format->create();
you should be using:
$this->Form->create('Format');
delete the
<?php echo $form->create('Format');?>
and replace it with
<?php echo $this->Form->create('Format');?>
$form is the one that causes the error.
Need to define the global name of the model. So, to access it anywhere in application.
For example: my model is User
class User extends AppModel {
var $name = 'User';
function myfunction ($id) {
.....
}
}
To use in controller
Controller:
class UsersController extends AppController
{
function test()
{
$this->User->myfunction();
......
}
}
I hope this will help you!
This is probably being caused because for some reason $this->Format isn't being created. If you look in your code snippet you see it calling the create() function. Add this as a debug statement in your controller function before you call create() to see if it is even set.
debug( isset( $this->Format ) );
If it is set should output true. If you try this let me know what it says I might have some other suggestions to go from there.
Have you created the model "Format"?
This kind of errors arise when the called model has a problem. Either it is not created, or it is not properly created or it is not imported/ initiated properly.
If you declared $uses variable in your controller, make sure you include "Format" in your $uses array along the other models.
Try this one into your action
$this->loadModel('Format');
$this->Format
is undefined (so it's value is null), a null object has no functions, therefor you can't use
$this->Format->create();
It's pretty much equal to
null->create();
Try
$this->Form->create(null,['url' => ['controller' => 'yourController', 'action' => 'yourAction']])
I'm saving the ID of the conected user in a static variable at MainController, but I need to access this variable in others controllers. When I try to get the value from the variable, the result is always the initial value of the variable, even when I have already modified it.
class MainController extends AppController {
//...
public static $loggedClienteId;
//functions
public function loginCliente(){
//code...
self::$loggedClienteId = $cliente['Cliente']['id'];
var_dump(MainController::$loggedClienteId); //returns the correct value.
return $this->redirect(array('controller' => 'clientes', 'action' => 'index'));
}
}
So, in another controller...
include "MainController.php";
class ClientesController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
var_dump(MainController::$loggedClienteId); //null, althought it already has a value...
$this->set('clientes', $this->Cliente->find('all'));
}
//functions...
}
Why is that happening?
Use $this->Auth->user('id') to get the current logged in user's id.
The reason your code does not work is because once the request for the login action is completed, the script is over. Setting a variable does not persist across requests. You have to save variables in the session for that.
If it's not the logged in user's id you need, what you have to do is use the SessionComponent and use $this->Session->write('key', 'value'); and to read it in another request/controller $this->Session->read('key');.