Is there any simple solution to pass $this->data variable from parent controller to all children controllers.
All what I try bring empty array to child.
When I change the file "system/engine/controller.php" like below:
protected function getChild($child, $args = array()) {
$action = new Action($child, $args);
if (file_exists($action->getFile())) {
require_once($action->getFile());
$class = $action->getClass();
$controller = new $class($this->registry);
//$controller->{$action->getMethod()}($action->getArgs());
$controller->{$action->getMethod()}($action->getArgs()+array('parent-data'=>$this->data));
return $controller->output;
} else {
trigger_error('Error: Could not load controller ' . $child . '!');
exit();
}
}
Then I try to read the variable 'parent-data' from the passed arguments in the child controller:
if (isset($setting['parent-data'])) {
echo "<pre>".print_R($setting['parent-data'],true)."</pre>";
}
As a result I get an empty array:
Array
(
[modules] => Array
(
)
)
The data variable is empty. Thats why it prints blank array.
Also there is no need to pass the data varaiable.Its a global one and you will get it till upto the .tpl files.
The issue was in the parent that was the column controller with empty data variable rather the main page parent controller that has had necessary data variable.
on opencart2 and maybe older:
ex: parse ver (steps) from parent controller product-custom to child controller header
parent
<?php
class ControllerProductCustom extends Controller {
private $error = array();
public function index() {
$this->load->language('product/product');
...
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header', array('steps' => true));
child
<?php
class ControllerCommonHeader extends Controller {
public function index($arg) {
$data['title'] = $this->document->getTitle();
if (isset($arg['steps'])) $data['steps'] = $arg['steps'];
...
Related
I'm pretty new in Joomla and I am struggling with a method that seems to appear out of thin air.
The problem I am having is an empty variable when it is supposed to be filled by
$items = $this->get('Items');
It is located in the file view.html.php and the class name is
class guruViewguruauthor extends JViewLegacy {}
I am sorry in advance if this is a stupid question!!
You should have a getItems method in your guruauthor model class found in your site models folder.
$items = $this->get('Items');
retrieves the data from the model. If you dont have getItems defined in model or getItems sql is not defined properly you may get an empty object.
Check this link it may help you
https://docs.joomla.org/Special:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_model_to_the_site_part
A sample getItems method from one of my component
public function getItems($recursive = false)
{
if (!count($this->_items)) {
// import Joomla Categories library
//if you forget this -> Fatal error: Class 'JCategories' not found in ...
jimport( 'joomla.application.categories' );
$app = JFactory::getApplication();
$options = array();
$options['countItems'] = 20;
//$categories = JCategories::getInstance('Content', $options);
$categories = JCategories::getInstance('eventmanagement', $options);
$this->_parent = $categories->get('root');
if (is_object($this->_parent)) {
$this->_items = $this->_parent->getChildren($recursive);
}
else {
$this->_items = false;
}
}
return $this->_items;
}
This will return list of categories and in view I call this as
$categories = $this->get('Items');
I am making a website in which i have to save a global variable.
I am using this person code globals_helper.php custom global variable class
But i always get static variable value null.
globals_helper.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Application specific global variables
class Globals
{
private static $authenticatedMemberId = null;
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$authenticatedMemberId = null;
self::$initialized = true;
}
public static function setAuthenticatedMemeberId($memberId)
{
self::initialize();
self::$authenticatedMemberId = $memberId;
}
public static function authenticatedMemeberId()
{
self::initialize();
return self::$authenticatedMemberId;
}
}
I have done all the steps like add globals_helper.php in helper folders and updated autoload file. Now I am trying to access those static variable from a custom library "Ctrl_utility" function "get_search_term" and my controllers calling get_search_term function
Ctrl_utility.php
class Ctrl_utility {
protected $CI;
public static $static_search = "";
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function get_search_term($searchTerm){
$searchTerm = $this->CI->security->xss_clean(htmlspecialchars($searchTerm));
if (isset($searchTerm) && strlen($searchTerm)>0) {
Globals::setAuthenticatedMemeberId($searchTerm);
} else {
$searchTerm = Globals::authenticatedMemeberId();
}
return $searchTerm;
}
One of my controller and they all have class ctrl_utility, get_search_term function:
class Blog_controller extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->model('blogs_model');
}
public function index(){
//Get SearchTerm Values
$searchTerm = $this->ctrl_utility->get_search_term($this->input->post('searchTerm'));
//Get Url First Parameter
$start = $this->ctrl_utility->get_url_first_parameter();
// Get Data from solr
$rows = 10;
$data = $this->blogs_model->solrData($start, $rows, $searchTerm); //give start of documents
//Pagination
$this->pagination->initialize($this->ctrl_utility->pagination_config($this->uri->segment(1), $rows, $data['found']));
//Views
$this->load->view('tabs/blogs', $data);
}
}
Am i doing something wrong?
Now when it comes to define them in CodeIgniter, there are several ways do that. I’ve listed some of them below:
Create your own file in application/libraries in which class constructor contains an array as an argument. Now create a new file in /application/config with same name as given in application/libraries and declare your global variables in it. Now to use these variables, autoload the newly created library.
Create your own file in application/core and declare the global variables in it. Than in controller you need to extend your file name instead of CI_Controller.
If the Global Variables are true constants, just add them in application/config/constants.php file and name them in all uppercase like the others are defined.
If you want to set application constants create new config file and add the variables. Now load it as $this->config->load(‘filename’); And access those variables as
$this->config->item(‘variable_name’);
Instead of creating helper create a library
Step 1: First of all, open application/libraries and create a custom
class name globals.php. It contains a constructor function which
contains an array as an argument.
<?php
class Globals {
// Pass array as an argument to constructor function
public function __construct($config = array()) {
// Create associative array from the passed array
foreach ($config as $key => $value) {
$data[$key] = $value;
}
// Make instance of CodeIgniter to use its resources
$CI = & get_instance();
// Load data into CodeIgniter
$CI->load->vars($data);
}
}
?>
Step 2: Now to make config file, open application/config and create
file as globals.php and write the code given below. This file contains
the config variable which will be passed as an array to constructor of
Globals class where its keys and values are stored in $data
<?php
// Create customized config variables
$config['web_Address']= 'https://www.example.com/blog';
$config['title']= 'CodeIgniter Global Variable';
?>
When constructor function loads, it will take the config variables
from the config file in order to use these variables anywhere.
Note: Name of the above file must be same as the class created in
libraries folder otherwise the code will not work.
Step 3: But before using these variables we have to autoload the newly
created library globals as given below.
And load library in autoload
$autoload['libraries'] = array('globals');
Now, you can use global variables in your controller
<?php
class CI_Global_Variable_Tutorial extends CI_Controller{
public function __construct() {
parent::__construct();
}
// Load view page
public function index() {
$this->load->view('show_global_variables');
}
}
?>
Views : show_global_variables.php
In view page, we can use global variables according to our need.
<?php
echo "Title of the blog post : ".$title;
echo "<a href='$web_Address'>"."Click here to go to blog page"."</a>";
?>
i have two helper classes
link are :
C:\xampp\htdocs\ecom\application\views\helpers\comman.php
C:\xampp\htdocs\ecom\application\views\helpers\RefineUrl.php
class Zend_View_Helper_Refinestr
{
public function Refinestr($str, $options = array()){
..............
.............
return $str;
}
}
second is
class Zend_View_Helper_Comman
{
public function Comman(){
return $this;
}
public function getPageContent($pageId){
// return $pageId;
$mapper = new Application_Model_StaticpageMapper();
$selectedFields=array('desc');
$tblName=array($mapper->getDbTable()->_name);
$whr= "`id`=$pageId";
$content=$mapper->fetchSelectedFields($tblName,$selectedFields,$whr);
$des=$content[0]['desc'];
// here i want to use function Refinestr() of another helper class how i use this
$des=$this->Refinestr($des);
// not working , searching this function inside comman class
} }
How to use one helper class function in another helper class function?
You can use below trick for your case.
While calling getPageContent() helper from your view file pass the view object in helper as a param (like $pageId) and use that view object to call another helper in helper definition.
View file:
<?php echo $this->getPageContent($pageId, $this); ?>
Helper File:
class Zend_View_Helper_GetPageContent {
public function getPageContent($pageId, $viewObj) {
// return $pageId;
$mapper = new Application_Model_StaticpageMapper ();
$selectedFields = array ('desc'
);
$tblName = array ($mapper->getDbTable ()->_name
);
$whr = "`id`=$pageId";
$content = $mapper->fetchSelectedFields ( $tblName, $selectedFields, $whr );
$des = $content [0] ['desc'];
// here i want to use function Refinestr() of another helper class how i
// use this
$des = $viewObj->Refinestr($des); //use view object to call another helper
}
}
Another helper will remain as it is.
One more solution to this problem could be, set view object in Zend Registry at the time of bootstrapping and use that registry variable in helper file to call another helper.
In Bootstrap File:
protected function _initConfig() {
$this->bootstrap('view');
$this->_view = $this->getResource('view');
Zend_Registry::set('viewObj', $this->_view);
}
Helper File:
class Zend_View_Helper_GetPageContent {
public function getPageContent($pageId) {
// return $pageId;
$mapper = new Application_Model_StaticpageMapper ();
$selectedFields = array ('desc');
$tblName = array ($mapper->getDbTable ()->_name);
$whr = "`id`=$pageId";
$content = $mapper->fetchSelectedFields ( $tblName, $selectedFields, $whr );
$des = $content [0] ['desc'];
// here i want to use function Refinestr() of another helper class how i
// use this
$viewObj = Zend_Registry::get('viewObj');
$des = $viewObj->Refinestr($des); //use view object to call another helper
}
}
I usually do the following:
Inside helper1
$this->helper1()->view->helper2();
In case helper1 is taking some arguments, I modify it to take no arguments and just return. Try it out, may work.
I have a two classes PHP:
Profile
Publicprofile
At Publicprofile class there are:
public function index($id){
$profile = new profile($id, true);
$profile->index();
}
So, here I create a new object profile.
Let's some to see class Profile:
class Profile extends Auth {
public $data = array();
public function __construct($idUser = null, $view = false){
parent::__construct();
$this->getTemplate();
}
}
}
The function getTemplate(); - forms an array $this->data
If to show at once this array after execute getTemplate(), will see (via var_dump), that array contains data with a keys:
view_inside
view
When is called a method $profile->index() - this array not is same:
Method index in class Profile:
public function index(){
var_dump($this->data); die(); // Here there are not keys view_inside, view
$this->route();
}
What is wrong at my code, that the source array in one class is different at two methods?
Function GetTemplate():
public function getTemplate(){
$this->data['view_inside'] = 'profile/doctor/index';
$this->data['view_left'] = 'profile/doctor/left';
$this->data['view_edit'] = 'profile/doctor/personal_update';
$this->data['view_personal'] = 'users/doctor/personal';
var_dump($this->data); // All right
}
I have a little issue with Zend. I am trying to make some fake HTTP requests and after the module->controller->action is executed, to return random variables that are set in that action. Like in the case of variables set with view->assign(,) - I can access them later from view file (.phtml).
Here is part of my code:
/application/controller/IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init(){}
public function indexAction()
{
#$this->view seems to be a NULL value from the fake request, so I can't pass variables to it
//$this->view->x = 'y';
echo 'test';
return array(
'x' => 'y'
);
}
}
/public/index2.php
<?php
//--cut--
$application->bootstrap();
$options = array(
'action' => 'index',
'controller' => 'index',
'module' => 'default'
);
if( isset($options['action'], $options['module'], $options['controller']) )
{
$request = new Zend_Controller_Request_Http ();
$request->setModuleName($options['module'])->setActionName($options['action'])->setControllerName($options['controller']);
$frontController = Zend_Controller_Front::getInstance ()->returnResponse ( true );
$response = new Zend_Controller_Response_Http ();
$frontController->getDispatcher ()->dispatch ( $request, $response );
echo '$response:<b>Zend_Controller_Response_Http</b><br>';
//This returns me the body of what I echo in the indexAction but not the variables.
var_dump($response);
}
Thank you so much!
If you want to assign variables to view when the request is dispatched, you can create a Zend_View instance in the indexAction and assign values, as shown below:
public function indexAction()
{
echo "test";
$view = new Zend_View();
$view->setBasePath(APPLICATION_PATH."/views/");
$view->x = 'y';
echo $view->render("index/index.phtml");
}
Try embedding the variable in the index view script, and var_dump of your response will contain both the echoed "test" and the index.phtml output.
If you want to return the array to the response, use json:
public function indexAction()
{
$array = array('x' => 'y');
echo json_encode($array);
}
index2.php:
//.....
var_dump($response);
var_dump(json_decode($response->getBody()));
You need to extend Zend_Controller_Action for this because standard Action didn't receive returned variables.
You will not be able to fetch the view parameters in the way you are trying (outside the view/MVC). This is because the action controller, in your case, IndexController only exists in memory for the duration of the dispatched method (IndexAction).
The parameters that are defined with the view class are only referenced when a call is made to view->render() and then just the HTML is generated.
You can however get the user defined variables (public scope) from within the controller action like so:
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/** The view class uses PHP's magic set/get/isset methods to
NULL any access to values that are protected (or more precisely
have a underscore _ prefix for the property name)
hence $this->_view = null;
**/
/** we do however have access to this view (or create a new one if not already
defined within the action controller) with: **/
$view = $this->initView();
/** An array of the public controller parameters **/
$viewParams = $view->getVars();
}
}
Also, the code dispatching theses requests can now be simplified:
$front = Zend_Controller_Front::getInstance();
$front->setRequest(
new Zend_Controller_Request_Http()->setParams($options)
)->dispatch();
Note: I'm using version 1.11