Issue with add global variable codeigniter 3 - codeigniter-3

I've admin dashboard with header available in all pages.
in Admin Controller I add function:
`class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view('admin/index');
$this->load->view('admin/includes/_footer');
}
}`
The problem is this working only for "home page (index)" dashboard. When I open anyother page then I get issue undefinied variable.
How can I call this variables in global?
`
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();`
update:
I've one file Core_Controller.php and this file contains:
class Admin_Core_Controller extends Core_Controller
{
public function __construct()
{
parent::__construct();
if (!is_admin()) {
redirect(admin_url() . 'login');
exit();
}
//set control panel lang
$this->control_panel_lang = $this->selected_lang;
if (!empty($this->session->userdata('mds_control_panel_lang'))) {
$this->control_panel_lang = $this->session->userdata('mds_control_panel_lang');
//language translations
$this->language_translations = $this->get_translation_array($this->control_panel_lang->id);
}
//check long cron
if (check_cron_time_long() == true) {
//delete old sessions
$this->settings_model->delete_old_sessions();
//add last update
$this->db->where('id', 1)->update('general_settings', ['last_cron_update_long' => date('Y-m-d H:i:s')]);
}
}
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
public function paginate($url, $total_rows)
{
//initialize pagination
$page = $this->security->xss_clean($this->input->get('page'));
$per_page = $this->input->get('show', true);
$page = clean_number($page);
if (empty($page) || $page <= 0) {
$page = 0;
}
if ($page != 0) {
$page = $page - 1;
}
if (empty($per_page)) {
$per_page = 15;
}
$config['num_links'] = 4;
$config['base_url'] = $url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$config['reuse_query_string'] = true;
$this->pagination->initialize($config);
return array('per_page' => $per_page, 'offset' => $page * $per_page);
}
}
You see I add your code here and now in Admin_Controller I add:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->load->view('admin/includes/_header', $data);
$this->render('admin/index');
$this->load->view('admin/includes/_footer');
}
and after this dashboard now working and everytime is refreshed every sec.

I would suggest creating a base controller with a render function, then have your controllers extend from this base controller and use this function to render their pages. The render function can then contain the variables that need to be available on all pages.
Since you already have an Admin_Core_Controller class, you might be able to add the render function there instead (not sure of your project structure). Something like this:
class Admin_Core_Controller // ...
{
// ...
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
}
Then use it to render your page in Admin_Controller:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->render('admin/index');
}
}
Edit Your Admin_Controller class should look like this - I've removed the header and footer includes (those are already rendered by the render function) and passed the $data array to render:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->render('admin/index', $data);
}
}

Related

TYPO3 v9 Scheduler does not persist the data

I have a function that loads data from a JSON file and enters it into the TYPO3 database. If I call this function via the backend Controller (indexAction), then everything works fine. However, when I call it from a task, the data is not saved. By means of test output I see that the object was changed correctly, only the Update or Add is not executed correctly, because the data in the database is not changed.
Here is my controller function:
class ImportController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
protected $siteRepository = null;
public function injectSiteRepository(SiteRepository $siteRepository)
{
$this->siteRepository = $siteRepository;
}
public function indexAction()
{
$this->dataImport();
}
public function dataImport() {
$file = "test.json";
$json = file_get_contents($file);
$jsonarray = json_decode($json);
foreach ($jsonarray->{'sites'} as $site) {
$newValue = false;
$dbSite = $this->siteRepository->getSiteByID($site->{'ID'});
if (empty($dbSite->getFirst())) {
$dbSite = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('test\test123\Domain\Model\Site');
$dbSite->setID($site->{'ID'});
$newValue = true;
} else {
$dbSite = $dbSite->getFirst();
}
//Set Data
$dbSite->setTest($site->{'TEST'});
//This object is correct, even in the Task
DebuggerUtility::var_dump(
$dbSite
);
//Update or Add new Data
if (!$newValue) {
$this->siteRepository->update($dbSite);
} else {
$this->siteRepository->add($dbSite);
}
}
$persistenceManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager');
$persistenceManager->persistAll();
return true;
}
}
Here is my task:
class JsonImportTask extends AbstractTask {
public function execute() {
$objectManager = GeneralUtility::makeInstance(
ObjectManager::class
);
$controller = $objectManager->get(ImportController::class);
$controller->dataImport();
return true;
}
}
Here my repository:
public function getSiteByID($id) {
$query = $this->createQuery();
$query->matching(
$query->equals("uid", $id),
);
return $query->execute();
}
Does anyone have an idea what this could be?
Ok I found my mistake myself. Here is the solution for all who have the same problem:
I added setRespectStoragePage in my getSiteByID function in SiteRepository:
$query->getQuerySettings()->setRespectStoragePage(false);
The error was that it was looking for the data at StoragePid 1. With this command he searches at the right place
Here is my correct repository function:
public function getSiteByID($id) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(false);
$query->matching(
$query->equals("uid", $id),
);
return $query->execute();
}
I had another problem. You have to set the PID number for new entries.
For example, my data is stored on Page ID 12.
I added this line here:
if (empty($dbSite->getFirst())) {
$dbSite = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('test\test123\Domain\Model\Site');
$dbSite->setID($site->{'ID'});
$newValue = true;
$dbSite->setPid(12); //New Line set PID (For me to PID 12)
} else {
$dbSite = $dbSite->getFirst();
}

How to use locale in select query in Zend model

On my administrator cms I can add newsitems and add a language code in column 'language' to the newsitem 'en' or 'nl'. In the bootstrapfile the language is set through:
public function _initLanguage()
{
$objSessionLanguage= new Zend_Session_Namespace('Zend_Lang');
$objLocale = new Zend_Locale();
$locale = new Zend_Locale();
$language = $locale->getLanguage();
$region = $locale->getRegion();
Zend_Loader::loadClass('Zend_Controller_Request_Http');
$request = new Zend_Controller_Request_Http();
if($language=='nl' or $language=='en')
{
if($language=='nl')
{
$localFile = 'dutch.php';
$Locale = 'nl';
}else
{ {
$localFile = 'english.php';
$Locale = 'en';
}
$objSessionLanguage->localFile=$localFile;
$objSessionLanguage->Locale=$Locale;
}else
{
if(!isset($objSessionLanguage->localFile))
{
$localFile = 'english.php';
$Locale = 'en';
}else
{
$localFile = $objSessionLanguage->localFile;
$Locale =$objSessionLanguage->Locale;
}
}
$objTranslate = new Zend_Translate('array', APPLICATION_PATH .'/../language/english.php', 'en');
$objTranslate->addTranslation(APPLICATION_PATH .'/../language/'.$localFile, $Locale);
$objTranslate->setLocale($Locale);
Zend_Registry::set("Zend_Translate", $objTranslate);
}
To display newsitems in a NewsList I want to select the newsitems in the newsmodel depending on language.
<?php
class Admin_Model_News extends Zend_Db_Table_Abstract
{
protected $_modelName = 'news';
protected $_modelLabel = 'News';
protected $_name = 'news';
protected $_objGeneralSettingVar;
public function init()
{
parent::init();
$this->_objGeneralSettingVar = Zend_Registry::get( "objGeneralSettingVar");
}
public function fetchNewsList()
{
$objSelect = $this->select()->limit(5);
$objSelect->where ("language = '$language'");
$objSelect->order("news_date DESC");
return $this->fetchAll($objSelect)->toArray();
}
}
But with the above
$objSelect->where ("language = '$language'");
no newsitems is displayed. I am sure I am missing something but can not seem to find it. How can I use the language setting in selecting newsitems on language?
In Admin_Model_News you are using
$objSelect->where ("language = '$language'");
for your where clause, but $language has not been set anywhere, so you are querying Where language = null.
The function fetchNewsList should look like this:-
public function fetchNewsList($language)
{
$objSelect = $this->select()->limit(5);
$objSelect->where ("language = '$language'");
$objSelect->order("news_date DESC");
return $this->fetchAll($objSelect)->toArray();
}
You don't show how you are using Admin_Model_News, but it should be something like this:-
$news = new Admin_Model_News();
$newList = $news->fetchNewsList(howeverYouGetlanguage());

Zend Framework - Passing a variable request in controller

In one of these php frameworks I've noticed a posibility to request the object Request in action as $this->request->paramName
class MyRequest extends Zend_Controller_Request_Http{
public $params = array();
public function __construct() {
$this->params = $this->getParams();
parent::__construct();
}
public function __get($name) {
if (isset($this->_params[$name])) {
return $this->_params[$name];
}
}
public function __isset($name) {
return isset($this->_params[$name]);
}
}
in MyController I've added variable request
public $request = null;
How can I change that standart Request to my one?
public function __construct(
Zend_Controller_Request_Abstract $request,
Zend_Controller_Response_Abstract $response,
array $invokeArgs = array()) {
$request = new MyRequest();
parent::__construct($request, $response, $invokeArgs);
$this->request = $this->getRequest();
}
This function has given no results.
Option 1 is make method _initRequest() in bootstrap:
protected function _initRequest() {
$this->bootstrap ( 'FrontController' );
$front = $this->getResource ( 'FrontController' );
$request = $front->getRequest ();
if (null === $front->getRequest ()) {
$request = new MyRequest();
$front->setRequest ( $request );
}
return $request;
}
A bit dirty and untested solution. Would love to hear if it works.
//Bootstrap:
public function _initRequest()
{
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->setRequest(new MyRequest());
}
Try this it might help you:
in controller file
public function exampleAction(){
$result = $this->_request;
$model = new Employer_Model_JobInfo();
$results = $model->sample($result);
}
// the above line stores the values sent from the client side in $result.then sends that values to Model file with parameter $result ..
in model file
class Employer_Model_JobInfo extends Gears_Db_Table_Abstract{
public function sample($param){
$paramVal = $param->getParam('name');
$paramVal1 = $param->getParam('email');
}
}
The name and email are what name used to sent the data from client to server.

Zend Framework: How to write a correct model that use another table?

I have models in project that use more than one table to select.
How can I write code like this more correct?
public function __construct()
{
$this->_name = DB_PREFIX . 'teachers';
parent::__construct();
}
public function init()
{
$this->db = Zend_Db_Table::getDefaultAdapter();
}
public function getTeachers($course_id)
{
$students_query = $this ->db->select()
->from($this->_name, '')
->from(<ANOTHER_TABLE_NAME>, array('uid', 'ulogin'))
->where("<ANOTHER_TABLE_NAME>.uid = {$this->_name}.teacher_id")
->where("{$this->_name}.course_id = ?", $course_id)
->order("<ANOTHER_TABLE_NAME>.ulogin");
$result = $this->db->fetchAll($students_query) ? $this->db->fetchAll($students_query) : NULL;
return $result;
}
$students_query = $this->db->select()
->from($this->_name, '')
->setIntegrityCheck(false)
->join('<ANOTHER_TABLE_NAME>', "<ANOTHER_TABLE_NAME>.uid = {$this->_name}.teacher_id", array('uid', 'ulogin'))
->where("{$this->_name}.course_id = ?", $course_id)
->order("<ANOTHER_TABLE_NAME>.ulogin");

zend framework stringtrim filter not working

I'm having trouble with zend framework's string trim filter. I use the following code to set up a text element in a Zend_Form:
$voucherValidator = new Project_Validate_Voucher();
$code = $this->addElement('text', 'code', array('label'=>'Gutscheincode'));
$code = $this->getElement('code')
->addFilter('StringTrim')
->addValidator($voucherValidator, true);
When I type in some text with preceeding blanks or tabs, the validator correctly works on the StringTrim filtered input and accepts the input. When I later check the $_POST['code'] after code submission, I get the unfiltered input. How can I get my text element to post the filtered value?
Use $code = $this->code->getValue() as Zend_Form doesn't actually filter the $_POST array.
Sorry, i know i'm late but in case any one faced the same problem,
I have faced this problem today and i found few ways to solve this problem:
i have answered same reply on this post
Other Post
first my code is:
This is the form class
class Application_Form_UserForm extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('POST');
$fname = new Zend_Form_Element_Text('fname');
$fname->setLabel('First Name: ');
$fname->setAttribs(Array(
'placeholder'=>'Example: Eslam',
'class'=>'form-control'
));
$fname->setRequired();
$fname->addValidator('StringLength', false, Array(4,20));
$fname->addFilter('StringTrim');
$fname->addFilter('StripTags');
$fname->removeDecorator('DtDdWrapper');
$fname->removeDecorator('label');
$fname->removeDecorator('HtmlTag');
$lname = new Zend_Form_Element_Text('lname');
$lname->setLabel('Last Name: ');
$lname->setAttribs(Array(
'placeholder'=>'Example: Khoga',
'class'=>'form-control'
));
$lname->setRequired();
$lname->addValidator('StringLength', false, Array(4,20));
$lname->addFilter('StringTrim');
$lname->addFilter('StripTags');
$lname->removeDecorator('DtDdWrapper');
$lname->removeDecorator('label');
$lname->removeDecorator('HtmlTag');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email: ');
$email->setAttribs(Array(
'placeholder'=>'Example#Example.com',
'class'=>'form-control'
));
$email->setRequired();
$email->addValidator('StringLength', false, Array(5,250));
$email->addFilter('StringTrim');
$email->addFilter('StripTags');
$email->removeDecorator('DtDdWrapper');
$email->removeDecorator('label');
$email->removeDecorator('HtmlTag');
$gender = new Zend_Form_Element_Select('gender');
$gender->setRequired();
$gender->addMultiOption('male','Male')->
addMultiOption('female','Female')->
addMultiOption('none','Prefer not to mention');
$gender->setAttrib('class', 'form-control');
$track_obj = new Application_Model_Track();
$allTracks = $track_obj->listAll();
$track = new Zend_Form_element_Select('track');
foreach($allTracks as $key=>$value)
{
$track->addMultiOption($value['id'], $value['name']);
}
$submit= new Zend_Form_Element_Submit('submit');
$submit->setAttribs(array('class'=>'btn btn-success'));
$reset= new Zend_Form_Element_Submit('reset');
$reset->setAttribs(array('class'=>'btn btn-danger'));
$this->addElements(array(
$fname,
$lname,
$email,
$gender,
$track,
$submit,
$reset
));
}
}
This is controller class
class UserController extends Zend_Controller_Action{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function listAction()
{
// action body
$user_model = new Application_Model_User();
$this->view->users = $user_model->listUsers();
$track_form = new Application_Form_Track();
$this->view->track_form = $track_form;
$track_model = new Application_Model_Track();
$request = $this->getRequest();
if($request->isPost())
{
if($track_form->isValid($request->getPost())){
$track_model-> addTrack($request->getParams());
$this->redirect('/user/add');
}
}
}
public function detailsAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user = $user_model->userDetails($us_id);
$trackModel = new Application_Model_Track();
$track = $trackModel->getTrackName($user[0]['track']);
$user[0]['track'] = $track[0]['name'];
$this->view->user = $user[0];
}
public function deleteAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user_model->deleteUser($us_id);
$this->redirect("/user/list");
}
public function addAction()
{
// action body
$form = new Application_Form_UserForm();
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
/*echo "<pre>";
print_r($form);
echo "</pre>";
exit;*/
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model = new Application_Model_User();
$user_model-> addNewUser($userData);
$this->redirect('/user/list');
}
}
$this->view->user_form = $form;
}
public function editAction()
{
// action body
$form = new Application_Form_UserForm();
$user_model = new Application_Model_User ();
$id = $this->_request->getParam('uid');
$user_data = $user_model-> userDetails($id)[0];
$form->populate($user_data);
$this->view->userName = $user_data['fname']." ".$user_data['lname'];
$this->view->user_form = $form;
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model-> updateUser($id, $userData);
$this->redirect('/user/list');
}
}
}
}
First Solution:
i used filter on Form elements in the form class,
but i retrieved data from $form object in the controller,
as i found that method
addFilter()
doesn't change in the $_POST array values, so i have retrieved the data from $form object and then passed it as array to Model.
Second Solution:
i have tried to apply the filter on the values in the controller, not in the form by creating object from filter class and apply needed filter
Third Solution:
is to use method
addValidator()
with regex which affects on $_POST values.