TYPO3 v9 Scheduler does not persist the data - typo3

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();
}

Related

Issue with add global variable 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);
}
}

In Magento, on submitting the registation form; throws a new Exception()

I am creating a custom Registration form. On submitting the form it has to generate a mail but now it is throwing a new Exception(); error. Guide me on how to solve this problem
my code
<?php
class Huntgather_Registration_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/huntgather_registration/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/huntgather_registration/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/huntgather_registration/email_template';
const XML_PATH_ENABLED = 'contacts/huntgather_registration/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('registrationForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['product-name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['serial-number']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['date']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['address']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($post['data-privacy'], 'NotEmpty')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('huntgather_registration')->__('Your registration has been processed. Thank you for registering your product'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
Form submit getting error
(We were unable to process your registration. Please make sure you have entered all required data in the form below)
I think you got an exception while sending email. You should replace
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
With
Mage::getSingleton('customer/session')->addError($e->getMessage());
to get problem exactly.

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());

Symfony Integrate Zend Lucene Search

I've been following the Jobeet tutorial in order to integrate the Zend Lucene search into my Symfony project and I can't seem to get it to work. I have added the following code to my config/ProjectConfiguration.class.php
class ProjectConfiguration extends sfProjectConfiguration
{
static protected $zendLoaded = false;
static public function registerZend()
{
if (self::$zendLoaded)
{
return;
}
set_include_path(sfConfig::get('sf_lib_dir').'/vendor'.PATH_SEPARATOR.get_include_path());
require_once sfConfig::get('sf_lib_dir').'/vendor/Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
self::$zendLoaded = true;
}
I have also added this code to my CarTable.class.php
static public function getLuceneIndex()
{
ProjectConfiguration::registerZend();
if (file_exists($index = self::getLuceneIndexFile()))
{
return Zend_Search_Lucene::open($index);
}
return Zend_Search_Lucene::create($index);
}
static public function getLuceneIndexFile()
{
return sfConfig::get('sf_data_dir').'/car.'.sfConfig::get('sf_environment').'.index';
}
And lastly I have added the following code to my Car.class.php
public function updateLuceneIndex()
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
if (!$this->getActivated())
{
return;
}
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Keyword('pk', $this->getIditem()));
$doc->addField(Zend_Search_Lucene_Field::UnStored('title', $this->getTitle(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('features', $this->getFeatures(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_city', $this->getLocation_city(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_state', $this->getLocation_state(), 'utf-8'));
$index->addDocument($doc);
$index->commit();
}
public function delete(Doctrine_Connection $conn = null)
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
return parent::delete($conn);
}
And of course I added these few lines to the save function:
$conn = $conn ? $conn : $this->getTable()->getConnection();
$conn->beginTransaction();
try
{
$ret = parent::save($conn);
$this->updateLuceneIndex();
$conn->commit();
return $ret;
}
catch (Exception $e)
{
$conn->rollBack();
throw $e;
}
I have extracted the contents of the "library" folder of the Zend Framework into my lib/vendor/Zend folder.
But every time I run the command
php symfony doctrine:data-load
It runs all the way through and loads all of my fixtures but it doesn't create the folder with the index files in my data folder. I'm not sure what I'm doing wrong.
Here is my reference (Jobeet Tutorial) http://www.symfony-project.org/jobeet/1_4/Doctrine/en/17
By the way I'm using Symfony 1.4 (Doctrine).

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");