i'm trying to develop a PrestaShop module with controllers i placed, for example in:
/modules/mymodule/controllers/admin/myControlController.php
class MyControlController extends ModuleAdminController {
public function __construct() {
$this->module = 'mymodule';
$this->bootstrap = true;
$this->context = Context::getContext();
$token = Tools::getAdminTokenLite('AdminModules');
$currentIndex='index.php?controller=AdminModules&token='.$token.'&configure=mymodule&tab_module=administration&module_name=mymodule';
Tools::redirectAdmin($currentIndex);
parent::__construct();
}
public function showForm() {
die("hello");
}}
Controller works (construct method is called) if i call it form url
http://myshop.com/adminxxx/index.php?controller=MyControl&token=9faf638aa961468c8563ffb030b3c4a8
But i can't access methods of controller from main class of module:
ModuleAdminController::getController('MyControl')->showForm();
I received "Class not found" ever
Is that the correct method to access a control from outside?
Thanks!
If you want to show anything that concern a form you should use renderForm().
Your should try parent::showForm(); or $this->showForm();.
Here is an example of controller that can work :
require_once _PS_MODULE_DIR_.'modulename/models/ModuleNameLog.php';
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class AdminModuleNameLogController extends ModuleAdminController
{
protected $_defaultOrderBy = 'id_modulenamelog';
protected $_defaultOrderWay = 'DESC';
public function __construct()
{
$this->table = 'modulenamelog';
$this->className = 'ModuleNameLog';
$this->context = Context::getContext();
$this->lang = false;
$this->bootstrap = true;
$this->actions_available = array();
$this->actions = array();
$this->show_toolbar = false;
$this->toolbar_btn['new'] = array();
$this->tabAccess['add'] = '0';
$this->allow_export = true;
$this->requiredDatabase = true;
$this->page_header_toolbar_title = $this->l('Example Module Name logs');
$this->_select = 'SUM(a.quantity) as total_quantity';
$this->_group = ' GROUP BY a.id_product, a.id_product_attribute ';
$this->fields_list = array(
'id_product' => array(
'title' => $this->l('Product'),
'align' => 'center',
'callback' => 'getProductName',
),
'id_product_attribute' => array(
'title' => $this->l('Combination'),
'align' => 'center',
'callback' => 'getAttributeName',
),
'total_quantity' => array(
'title' => $this->l('Total Quantity'),
'align' => 'center',
),
);
$this->mod = new ModuleName();
$this->mod->cleanLogs();
$this->context = Context::getContext();
parent::__construct();
}
public function getProductName($id)
{
if (!empty($id)) {
$product = new Product($id, true, $this->context->cookie->id_lang);
return $product->name;
}
}
public function getAttributeName($id)
{
if (!empty($id)) {
$combination = new Combination($id);
$names = $combination->getAttributesName($this->context->cookie->id_lang);
$str = array();
if (!empty($names)) {
foreach ($names as $value) {
$str[] = $value['name'];
}
}
return implode(' - ', $str);
} else {
return '-';
}
}
public function postProcess()
{
if (Tools::isSubmit('purge_id')) {
// Do something here
$id = (int) Tools::getValue('purge_id');
Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModuleNameLog').'&conf=4');
}
parent::postProcess();
}
public function renderList()
{
$carts = Db::getInstance()->executeS('SELECT ct.*, cs.`firstname`, cs.`lastname` FROM '._DB_PREFIX_.'cart ct LEFT JOIN '._DB_PREFIX_.'customer cs ON ct.id_customer = cs.id_customer WHERE 1 ORDER BY id_cart DESC LIMIT 0,2000');
$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.'modulename/views/templates/admin/preform.tpl');
$tpl->assign(array(
'carts' => $carts,
));
$html = $tpl->fetch();
return $html.parent::renderList();
}
public function renderForm()
{
if (!$this->loadObject(true)) {
return;
}
$obj = $this->loadObject(true);
if (isset($obj->id)) {
$this->display = 'edit';
} else {
$this->display = 'add';
}
$array_submit = array(
array(
'type' => 'select',
'label' => $this->l('Cart :'),
'name' => 'id_cart',
'options' => array(
'query' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'cart WHERE id_cart > 0 ORDER BY id_cart DESC LIMIT 0,500'),
'id' => 'id_cart',
'name' => 'id_cart',
),
),
array(
'type' => 'text',
'label' => $this->l('Quantity translation here'),
'hint' => $this->l('Description and translation here'),
'name' => 'quantity',
),
);
$this->fields_form[0]['form'] = array(
'tinymce' => false,
'legend' => array(
'title' => $this->l('Form title'),
),
'input' => $array_submit,
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default',
),
);
$this->multiple_fieldsets = true;
return parent::renderForm();
}
}
Related
I'm getting error
Call to a member function buildCTCCompensationData() on null
in PayrollspendController.php on this line of code:
$compData = $this->payrollspendManager->hello($postData);
I have checked the module.config.php and __construct() method but not able to find the error. What is the issue in the code?
Please help me to resolve me the error
I have called the method properly
if any code is required will help
if want view file that will also give
Those who know zendframework help me to resolve issue
This is module.config.php
'dashboard_activity_payrollspend' => [
'type' => Literal::class,
'options' => [
'route' => '/dashboard/employer-details/activity-manage',
'constraints' => [
'action' =>'[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-zA-Z0-9_-]+',
],
'defaults' => [
'controller' => Controller\PayrollspendController::class,
'action' => 'add',
],
],
],
'controllers' => [
'factories' => [
Controller\PayrollspendController::class => Controller\Factory\PayrollspendControllerFactory::class
],
],
'service_manager' => [
'factories' => [
Service\PayrollspendManager::class => Service\Factory\PayrollspendManagerFactory::class
],
],
This is my controller PayrollspendController.php
<?php
namespace Dashboard\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Application\Entity\PyPayGroup;
use Application\Entity\PyPayPeriod;
//use Payroll\Form\SalaryVariationForm;
use Zend\Session\SessionManager;
use Application\Entity\CommonCompanyHeader;
use Dashboard\Form\PayrollspendForm;
class PayrollspendController extends AbstractActionController
{
private $entityManager;
private $sessionContainer;
private $pyPayPeriodClass;
private $pyPayGroupClass;
private $companyClass;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
$this->pyPayGroupClass = $this->entityManager->getRepository(PyPayGroup::class);
$this->pyPayPeriodClass = $this->entityManager->getRepository(PyPayPeriod::class);
$this->companyClass = $this->entityManager->getRepository(CommonCompanyHeader::class);
$this->commonTranslationManager = $commonTranslationManager;
$sessionManager = new SessionManager();
$this->sessionContainer = new Container('ContainerNamespace', $sessionManager);
$arrLabelId = [];
}
public function addAction()
{
if ($this->sessionContainer->empId == "") {
return $this->redirect()->toRoute('admin_user_login');
}
if (!in_array('PY', $this->sessionContainer->arrRole)) {
if (!in_array('py_admin', $this->sessionContainer->arrRole)) {
return $this->redirect()->toRoute('dashboard_ess_index');
}
}
$reportForm = new PayrollspendForm();
$payGroup = $this->pyPayGroupClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode,
'pgActive' => 1
]);
$reportForm->buildPayGroupData($payGroup);
$company = $this->companyClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode
]);
$reportForm->buildCompanyData($company);
$payPeriodData = ['' => 'Select'];
$reportForm->get('payPeriod')->setValueOptions($payPeriodData);
$postData = $this->getRequest()->getPost()->toArray();
$postData['ouCode'] = $this->sessionContainer->ouCode;
$postData['langCode'] = $this->sessionContainer->langCode;
$compData = $this->payrollspendManager->hello($postData);
$groupByData = [
'' => 'Select',
'location' => 'Location',
'department' => 'Department',
'cost-center' => 'Cost center'
];
$reportForm->get('groupby')->setValueOptions($groupByData);
return new ViewModel([
'reportData' => $compData,
'form' => $reportForm,
'ouCode' => $this->sessionContainer->ouCode,
'postData' => $postData,
'langCode' => $this->sessionContainer->langCode,
'arrLabels' => $this->arrLabels
]);
$resultData->setTerminal(true);
return $resultData;
}
}
This is PayrollspendControllerFactory.php
<?php
namespace Dashboard\Controller\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Dashboard\Service\PayrollspendManager;
//use Application\Service\CommonTranslationManager;
use Dashboard\Controller\PayrollspendController;
class PayrollspendControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container,$requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
$payrollspendManager = $container->get(PayrollspendManager::class);
//$hrManager = $container->get(HrManager::class);
// $commonTranslationManager = $container->get(CommonTranslationManager::class);
return new PayrollspendController($entityManager);
}
}
This PayrollspendManager.php
<?php
namespace Dashboard\Service;
//use Application\Entity\DsAnnouncement;
//use Application\Entity\TmDomain;
// The AnnouncementManager service is responsible for adding new task.
class PayrollspendManager
{
/**
* Doctrine entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
// Constructor is used to inject dependencies into the service.
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function hello($postData)
{
$headerData = $this->getAllCTCCompensationHeader($postData);
$compData = $this->getAllCTCCompensationData($postData);
return [
'header' => $headerData,
'detail' => $compData
];
}
public function getAllCTCCompensationHeader($postData)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('DISTINCT(pc.pyComPayitem) as payHeader')
->from(PyCompensationDetails::class, 'pc')
->innerJoin(PyPayItemPaygroupMap::class, 'ppipm', 'with', 'ppipm.payitemCode = pc.pyComPayitem
AND ppipm.ouCode = pc.ouCode
AND ppipm.langCode= pc.langCode
AND ppipm.pgCode= pc.pgCode')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.isModified = ?4')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', 0)
->orderBy('ppipm.orderofProcessing', 'ASC');
$compData = $queryBuilder->getQuery()->getResult();
$headerData = [
'0' => 'Employee Id',
'1' => 'Employee Name'
];
foreach ($compData as $compHeader) {
$headerData[] = $compHeader['payHeader'];
}
$headerData[] = 'PF';
$headerData[] = 'ESIC';
$headerData[] = 'Total';
return $headerData;
}
/**
* Get compensation detail data
*
* #param type $postData
* #return type
*/
public function getAllCTCCompensationData($postData)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('pc.pyComEmpid, pc.amount, pc.pyComPayitem, pi.payitemDesc, hn.empFname, hn.empMname, hn.empLname')
->from(PyCompensationDetails::class, 'pc')
->innerJoin(HrEmpid::class, 'he', 'with', 'pc.ouCode = he.ouCode
and pc.langCode = he.langCode
and pc.pyComEmpid = he.empId'
)
->innerJoin(HrEmpName::class, 'hn', 'with', 'pc.ouCode = hn.ouCode
and pc.langCode = hn.langCode
and pc.pyComEmpid = hn.empId'
)
->innerJoin(PyPayItem::class, 'pi', 'with', 'pc.ouCode = pi.ouCode
and pc.langCode = pi.langCode
and pc.pyComPayitem = pi.payitemCode'
)
//->innerJoin(SmartlistData::class,'sd','with','sd.dataCode = pi.smartlistPayitemtype'
//)
->leftJoin(PyPayItemPaygroupMap::class, 'ppipm', 'with', 'ppipm.payitemCode = pi.payitemCode '
. 'AND ppipm.ouCode = pi.ouCode '
. 'AND ppipm.langCode= pi.langCode '
. 'AND ppipm.pgCode= pc.pgCode')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.isModified = ?4')
->andWhere('he.smartlistEmpstatus != ?5')
->andWhere('pi.smartlistPayitemtype IN (94,99,100)')
->orderBy('ppipm.orderofProcessing', 'ASC')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', 0)
->setParameter('5', 56);
// ->orderBy('pc.pyComEmpid');
// echo $queryBuilder->getQuery()->getSQL();
//exit;
$compData = $queryBuilder->getQuery()->getResult();
// echo '<pre>';
//print_r($compData);
// exit;
$data = [];
if (!empty($compData)) {
$total = 0;
foreach ($compData as $dataC) {
$data[$dataC['pyComEmpid']]['Employee Id'] = $dataC['pyComEmpid'];
$data[$dataC['pyComEmpid']]['Employee Name'] = sprintf('%s %s %s', $dataC['empFname'], $dataC['empMname'], $dataC['empLname']);
$data[$dataC['pyComEmpid']][$dataC['pyComPayitem']] = $dataC['amount'];
$statData = $this->getStatuoryData($postData, $dataC['pyComEmpid']);
//echo '<pre>';
// print_r($statData);
//exit;
if(isset($statData['pf']) && ($statData['pf'] == 1)){
$parameterData = $this->getParamaterData($postData, 'pf', $dataC['pyComEmpid']);
$data[$dataC['pyComEmpid']]['PF'] = $this->getPFData($postData, $parameterData);
} else {
$data[$dataC['pyComEmpid']]['PF'] = 0;
}
if(isset($statData['esic']) && ($statData['esic'] == 1)){
$parameterData = $this->getParamaterData($postData, 'esic', $dataC['pyComEmpid']);
$data[$dataC['pyComEmpid']]['ESIC'] = $this->getESICData($postData, $dataC['pyComEmpid']);
} else {
$data[$dataC['pyComEmpid']]['ESIC'] = 0;
}
$data[$dataC['pyComEmpid']]['Total'] = $this->getCTCCompensationSum($postData, $dataC['pyComEmpid'], $data[$dataC['pyComEmpid']]['PF'], $data[$dataC['pyComEmpid']]['ESIC']);
}
}
//echo "<pre>";
//print_r($data);
//exit;
return $data;
}
/**
* Get compensation sum
*
* #param array $postData
* #param string $pyComEmpid
* #return type
*/
public function getCTCCompensationSum($postData, $pyComEmpid, $pf, $esic)
{
$amountTotal = 0;
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('SUM(pc.amount) as amount')
->from(PyCompensationDetails::class, 'pc')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.pyComEmpid = ?4')
->andWhere('pc.isModified = ?5')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', $pyComEmpid)
->setParameter('5', 0);
$compData = $queryBuilder->getQuery()->getOneOrNullResult();
$amount = isset($compData['amount']) ? $compData['amount'] : 0;
$amountTotal = $amount + $pf + $esic;
return $amountTotal;
}
}
This is PayrollspendManagerFactory.php
<?php
namespace Dashboard\Service\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Dashboard\Service\PayrollspendManager;
class PayrollspendManagerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
// Instantiate the service and inject dependencies
return new PayrollspendManager($entityManager);
}
}
This is PayrollspendForm
<?php
namespace Dashboard\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
//use Application\Entity\TmTask;
/**
* This form is used to collect post data.
*/
class PayrollspendForm extends Form
{
public $session;
public $entityManager;
public $ouCode;
public $langCode;
public function __construct()
{
// Define form name
parent::__construct('payrollspend-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'form-horizontal');
$this->setAttribute('id', 'payrollspend-form');
//$this->edit = $edit;
// $this->ouCode = $session->ouCode;
// $this->langCode = $session->langCode;
// $this->entityManager = $entityManager;
$this->addElements();
$this->addInputFilter();
}
protected function addElements()
{
$this->add([
'type' => 'select',
'name' => 'payPeriod',
'attributes' => [
'id' => 'payPeriod',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'text',
'name' => 'payCalender',
'attributes' => [
'id' => 'payCalender',
'class'=>'form-control',
'disabled' => 'disabled'
]
]);
$this->add([
'type' => 'select',
'name' => 'companyCode',
'attributes' => [
'id' => 'companyCode',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'select',
'name' => 'payGroup',
'attributes' => [
'id' => 'payGroup',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'text',
'name' => 'startDate',
'attributes' => [
'id' => 'startDate',
'class' => 'form-control dpd1',
'data-date-format' => "dd-mm-yyyy"
]
]);
$this->add([
'type' => 'text',
'name' => 'endDate',
'attributes' => [
'id' => 'endDate',
'class' => 'form-control dpd1',
'data-date-format' => "dd-mm-yyyy"
]
]);
$this->add([
'type' => 'select',
'name' => 'groupby',
'attributes' => [
'id' => 'groupby',
'class'=>'form-control',
'placeholder'=>''
],
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
'id' => 'submitbutton',
'class' => 'btn btn-primary'
],
]);
}
private function addInputFilter()
{
$inputFilter = new InputFilter();
$this->setInputFilter($inputFilter);
}
public function buildPayGroupData($payGroup)
{
$payGroupData = [];
foreach($payGroup as $data){
$payGroupData[$data->pgCode] = $data->pgSdesc;
}
$this->get('payGroup')->setEmptyOption('select')->setValueOptions($payGroupData);
}
public function buildCompanyData($companys)
{
$companyData = ['' => 'Select'];
foreach($companys as $data){
$companyData[$data->companyCode] = $data->companyName;
}
$this->get('companyCode')->setValueOptions($companyData);
}
public function defaultDate()
{
$this->get('startDate')->setValue(date('d-m-Y'));
}
}
Assuming the call in PayrollspendController::addAction() is the problem.
$compData = $this->payrollspendManager->hello($postData);
This is because the $this->payrollspendManager variable has not been defined.
You can see in the PayrollspendControllerFactory::__invoke you have requested the service from the dependency injection container; but do not inject it into the constructor of the PayrollspendController.
// PayrollspendControllerFactory::__invoke()
$entityManager = $container->get('doctrine.entitymanager.orm_default');
$payrollspendManager = $container->get(PayrollspendManager::class);
return new PayrollspendController($entityManager);
You should update the factory :
return new PayrollspendController($entityManager, $payrollspendManager);
And also the constructor of the controller to allow the new argument (while you are there you can also type hint on the expected interface)
use \Doctrine\ORM\EntityManager;
use \Dashboard\Service\PayrollspendManager;
class PayrollspendController extends AbstractActionController
{
// ...
private $entityManager;
private $payrollspendManager;
public function __construct(
EntityManager $entityManager,
PayrollspendManager $payrollspendManager
){
$this->entityManager = $entityManager;
$this->payrollspendManager = $payrollspendManager;
}
// ...
}
I have an Address DataObject:
class Address extends DataObject{
private static $db = array(
'Address' => 'varchar(255)',
);
private static $many_many = array(
'Countries' => 'Country'
);
public function getCMSFields() {
$fields = FieldList::create(TabSet::create('Root'));
$fields->addFieldsToTab('Root.Main', array(
TextField::create('Name'),
ListBoxField::create('Countries', 'Countries')->setMultiple(true)->setSource(Country::get()->map('ID', 'Name'))
));
return $fields;
}
}
And a Country dataObject:
class Country extends DataObject{
private static $belongs_many_many = array(
'Addresses' => 'Address',
);
private static $countries = array(
"AF" => array("Name"=>"Afghanistan","PhoneExtension"=>"+93"),...
);
public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null, $containerClass = 'DataList') { $return = new ArrayList();
$i = 1; //if I do 0 it always populates the admin field.
foreach (self::$countries as $key => $value) {
$return->add(new ArrayData(array('ID' => $i, 'Acronym' => $key, 'Name' => $value['Name'])));
$i++;
}
return $return;
}
}
** UPDATED **
In the database this saves correctly however it doesn't return correctly in the CMS admin. What am I missing?
After installing prestashop custom module getting Fatal error: Call to undefined method when clicking the menu which is created by the module
Fatal error: Call to undefined method querydr::viewAccess() in D:\xampp\htdocs\raffleV1.3\oknr9hexztcseff5\functions.php on line 279
<?php
if (!defined('_PS_VERSION_')) exit;
class querydr extends Module
{
protected $config_form = false;
public $html;
public $tabName = 'renderForm';
public function __construct()
{
$this->name = 'querydr';
$this->tab = 'others';
$this->version = '1.0.0';
$this->author = 'xyz';
$this->need_instance = 1;
$this->module_key = 'f35950b303e7cbcda7fd8e56bb100d77121';
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Query DR');
$this->description = $this->l('Allow your Back Office to Query the transactions ');
$this->confirmUninstall = $this->l('You want to Uninstall Query DR ?.');
$this->_tabsArray = array(
'Querydr' => 'Query DR',
);
if (!Configuration::get('QUERYDR'))
$this->warning = $this->l('No name provided');
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
include(dirname(__FILE__).'/sql/install.php');
return parent::install() &&
Configuration::updateValue('QUERYDR','Query Dr')
&& $this->_installTabs();
}
private function _installTabs()
{
$parentTab = new Tab();
foreach (Language::getLanguages() as $language) $parentTab->name[$language['id_lang']] = 'Query Dr';
$parentTab->class_name = 'Querydr';
$parentTab->module = $this->name;
$parentTab->id_parent = 0;
if (!$parentTab->save()) return false;
else {
$idTab = $parentTab->id;
//$idEn = Language::getIdByIso('en');
foreach ($this->_tabsArray as $tabKey => $name) {
$childTab = new Tab();
foreach (Language::getLanguages() as $language) $childTab->name[$language['id_lang']] = $name;
$childTab->class_name = $tabKey;
$childTab->module = $this->name;
$childTab->id_parent = $idTab;
if (!$childTab->save()) return false;
}
}
return true;
}
public function uninstall()
{
include(dirname(__FILE__).'/sql/uninstall.php');
Configuration::deleteByName('QUERYDR');
Configuration::deleteByName('QUERYDR_MERCHANT_ID');
Configuration::deleteByName('QUERYDR_SECRET_KEY');
$this->_uninstallTabs();
if (!parent::uninstall())
return false;
return true;
}
private function _uninstallTabs()
{
foreach ($this->_tabsArray as $tabKey => $name) {
$idTab = Tab::getIdFromClassName($tabKey);
if ($idTab != 0) {
$tab = new Tab($idTab);
$tab->delete();
}
}
$idTab = Tab::getIdFromClassName('QueryDr');
if ($idTab != 0) {
$tab = new Tab($idTab);
$tab->delete();
}
return true;
}
public function getContent()
{
if (Tools::isSubmit('submitQueryDrModule')) {
Configuration::updateValue('QUERYDR_MERCHANT_ID', Tools::getValue('QUERYDR_MERCHANT_ID'));
Configuration::updateValue('QUERYDR_SECRET_KEY', Tools::getValue('QUERYDR_SECRET_KEY'));
$this->html .= $this->displayConfirmation($this->l('Settings Updated'));
$this->tabName = 'renderForm';
}
if ($this->tabName) {
$this->html .= '<script>$(document).ready(function(){$("#'.$this->tabName.'").addClass("active");$(".'.$this->tabName.'").parents(".nav-tabs > li").addClass("active");});</script>';
} else {
$this->html .= '<script>$(document).ready(function(){$("#renderForm").addClass("active"); $(this).attr("href").indexOf("#renderForm").addClass("active");});</script>';
}
$this->html .= '<ul class="nav nav-tabs" role="tablist"><li ><a class="renderForm" href="#renderForm" role="tab" data-toggle="tab">SETTINGS</a></li></ul>';
$this->html .= '<div class="tab-content"><div class="tab-pane " id="renderForm">'.$this->renderForm_1_6().'</div></div>';
$this->html .='<style>div.flash.fail {color: #cd0a0a;background-color: #fef1ec;border: #cd0a0a 1px solid; padding: 0.5em;margin: 0 3px;margin-top: 22px;margin-bottom: 12px;text-align: center;border-radius: 2px 2px 2px 2px;}</style>';
return $this->html;
}
protected function renderForm_1_6()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 3,
'type' => 'text',
'desc' => $this->l('Your merchant ID ex: 201408191000001'),
'name' => 'QUERYDR_MERCHANT_ID',
'label' => $this->l('MERCHANT ID'),
), array(
'col' => 3,
'type' => 'text',
'desc' => $this->l('Your key provided by network international'),
'name' => 'QUERYDR_SECRET_KEY',
'label' => $this->l('SECRET KEY'),
)
),
'submit' => array(
'title' => $this->l('Save'),
),
)
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitQueryDrModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array(
$fields_form));
}
protected function getConfigFormValues()
{
return array(
'QUERYDR_MERCHANT_ID' => Configuration::get('QUERYDR_MERCHANT_ID'),
'QUERYDR_SECRET_KEY' => Configuration::get('QUERYDR_SECRET_KEY'),
);
}
}
My module link is here --
https://www.dropbox.com/s/juyhcu5zub8p9fi/querydr.zip?dl=0
I am not sure if it gonna help you but ... try to prefix your admin controller name with "Admin" like "AdminQuerydrController"and change it also in your tab installation
tab->class_name = 'AdminQuerydrController';
make sure to change also your controller php file name
"AdminQuerydrController.php"
I've got a syntax error on my foreach. I want to select from my backoffice a text file which write all eamil from site. I want to only get email from my database and put them into a text file write in my hard disk.
<?php
if (!defined('_PS_VERSION_'))
exit;
class SuperModule extends Module
{
public function __construct()
{
$this->name = 'supermodule';
$this->tab = 'administration';
$this->version = 1.0;
$this->author = 'Lelu Matthias';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('My super module');
$this->description = $this->l('This module is super !');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('MYMODULE_NAME'))
$this->warning = $this->l('No name provided.');
}
public function install()
{
if (Shop::isFeatureActive())
Shop::setContext(Shop::CONTEXT_ALL);
return parent::install() &&
$this->registerHook('displayNav') &&
$this->registerHook('header') &&
Configuration::updateValue('MYMODULE_NAME', 'super module') &&
Configuration::updateValue('MOD_SUPERMODULE_OPENINGHOURS', 'Ouvert de 9h a 19h') && Configuration::updateValue('MOD_SUPERMODULE_NEWSLETTER', '0');
}
public function uninstall()
{
return parent::uninstall();
}
public function getContent()
{
$output = null;
if (Tools::isSubmit('submit_openinghours'))
{
$supermodule_openinghours = Tools::getValue('MOD_SUPERMODULE_OPENINGHOURS');
if (!$supermodule_openinghours || empty($supermodule_openinghours) || !
Validate::isGenericName($supermodule_openinghours))
$output .= $this->displayError( $this->l('Invalid Configuration value') );
else
{
Configuration::updateValue('MOD_SUPERMODULE_OPENINGHOURS',
$supermodule_openinghours);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
}
if (Tools::isSubmit('submit_exportnewsletter'))
{
$id_option = Tools::getValue('MOD_SUPERMODULE_NEWSLETTER');
$output .=$id_option;
$txt="";
if($id_option ==1)
{
(foreach $newsletter as $row)
{
$text.=$row['email'];}
$table='newsletter';
}
else
{
(foreach $customer as $row)
{
$text.=$row['email'];
}
$table='customer';
}
$date = gmdate('dmY');
$file = fopen(dirname(__FILE__).'/export-newsletter-'.$table.'-'.
$date.'.txt', 'w');
fputs($file, $txt);
fclose($file);
}
return $output.$this->displayForm1().$this->displayForm2();
}
public function displayForm1()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form[0]['form'] = $this->formulaire1();
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true;
$helper->toolbar_scroll = true;
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->
name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::
$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['MOD_SUPERMODULE_OPENINGHOURS'] =
Configuration::get('MOD_SUPERMODULE_OPENINGHOURS');
return $helper->generateForm($fields_form);
}
protected function formulaire1()
{
return array(
'legend' => array(
'title' => $this->l('Opening hours'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Opening hours'),
'name' => 'MOD_SUPERMODULE_OPENINGHOURS',
'size' => 20,
'required' => true
),
),
'submit' => array(
'name' => 'submit_openinghours',
'title' => $this->l('Save')
)
);
}
protected function formulaire2()
{
$options = array(
array(
'id_option' => 0,
'name' => $this->l('Customer table')
),
array(
'id_option' => 1,
'name' => $this->l('Newsletter table')
),
);
return array(
'legend' => array(
'title' => $this->l('Newsletter export'),
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Choice a table'),
'name' => 'MOD_SUPERMODULE_NEWSLETTER',
'desc' => $this->l('Please choice a table.'),
'options' => array(
'query' => $options,
'id' => 'id_option',
'name' => 'name'
),
),
),
'submit' => array(
'name' => 'submit_exportnewsletter',
'title' => $this->l('Save')
)
);
}
public function displayForm2()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form[0]['form'] = $this->formulaire2();
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true;
$helper->toolbar_scroll = true;
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href'=>AdminController::$currentIndex.'&configure='.$this->name.
'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::
$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['MOD_SUPERMODULE_NEWSLETTER'] =
Configuration::get('MOD_SUPERMODULE_NEWSLETTER');
return $helper->generateForm($fields_form);
}
public function hookDisplayNav($params)
{
$ma_variable = Configuration::get('MOD_SUPERMODULE_OPENINGHOURS');
$this->context->smarty->assign(array(
'ma_variable' => $ma_variable
));
return $this->display(__FILE__, 'supermodulenav.tpl');
}
public function hookDisplayHeader()
{
$this->context->controller->addCSS($this->_path.'css/supermodule.css', 'all');
}
public function GetMailNewsLetter()
{
$sql='SELECT email FROM '._DB_PREFIX_.'newsletter';
$newsletter=Db::getInstance()->executeS($sql);
return $newsletter;
}
public function GetMailCustomer()
{
$sql='SELECT email FROM '._DB_PREFIX_.'customer';
$customer=Db::getInstance()->executeS($sql);
return $customer;
}
}
Try this
foreach ($newsletter as $row)
Check the Manual here
Hey only change your (foreach $newsletter as $row) to foreach($newsletter as $row)
something like this
<?php
if (!defined('_PS_VERSION_'))
exit;
class SuperModule extends Module
{
public function __construct()
{
$this->name = 'supermodule';
$this->tab = 'administration';
$this->version = 1.0;
$this->author = 'Lelu Matthias';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('My super module');
$this->description = $this->l('This module is super !');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('MYMODULE_NAME'))
$this->warning = $this->l('No name provided.');
}
public function install()
{
if (Shop::isFeatureActive())
Shop::setContext(Shop::CONTEXT_ALL);
return parent::install() &&
$this->registerHook('displayNav') &&
$this->registerHook('header') &&
Configuration::updateValue('MYMODULE_NAME', 'super module') &&
Configuration::updateValue('MOD_SUPERMODULE_OPENINGHOURS', 'Ouvert de 9h a 19h') && Configuration::updateValue('MOD_SUPERMODULE_NEWSLETTER', '0');
}
public function uninstall()
{
return parent::uninstall();
}
public function getContent()
{
$output = null;
if (Tools::isSubmit('submit_openinghours'))
{
$supermodule_openinghours = Tools::getValue('MOD_SUPERMODULE_OPENINGHOURS');
if (!$supermodule_openinghours || empty($supermodule_openinghours) || !
Validate::isGenericName($supermodule_openinghours))
$output .= $this->displayError( $this->l('Invalid Configuration value') );
else
{
Configuration::updateValue('MOD_SUPERMODULE_OPENINGHOURS',
$supermodule_openinghours);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
}
if (Tools::isSubmit('submit_exportnewsletter'))
{
$id_option = Tools::getValue('MOD_SUPERMODULE_NEWSLETTER');
$output .=$id_option;
$txt="";
if($id_option ==1)
{
foreach ($newsletter as $row)
{
$text.=$row['email'];
}
$table='newsletter';
}
else
{
foreach ($customer as $row)
{
$text.=$row['email'];
}
$table='customer';
}
$date = gmdate('dmY');
$file = fopen(dirname(__FILE__).'/export-newsletter-'.$table.'-'.
$date.'.txt', 'w');
fputs($file, $txt);
fclose($file);
}
return $output.$this->displayForm1().$this->displayForm2();
}
public function displayForm1()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form[0]['form'] = $this->formulaire1();
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true;
$helper->toolbar_scroll = true;
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->
name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::
$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['MOD_SUPERMODULE_OPENINGHOURS'] =
Configuration::get('MOD_SUPERMODULE_OPENINGHOURS');
return $helper->generateForm($fields_form);
}
protected function formulaire1()
{
return array(
'legend' => array(
'title' => $this->l('Opening hours'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Opening hours'),
'name' => 'MOD_SUPERMODULE_OPENINGHOURS',
'size' => 20,
'required' => true
),
),
'submit' => array(
'name' => 'submit_openinghours',
'title' => $this->l('Save')
)
);
}
protected function formulaire2()
{
$options = array(
array(
'id_option' => 0,
'name' => $this->l('Customer table')
),
array(
'id_option' => 1,
'name' => $this->l('Newsletter table')
),
);
return array(
'legend' => array(
'title' => $this->l('Newsletter export'),
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Choice a table'),
'name' => 'MOD_SUPERMODULE_NEWSLETTER',
'desc' => $this->l('Please choice a table.'),
'options' => array(
'query' => $options,
'id' => 'id_option',
'name' => 'name'
),
),
),
'submit' => array(
'name' => 'submit_exportnewsletter',
'title' => $this->l('Save')
)
);
}
public function displayForm2()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form[0]['form'] = $this->formulaire2();
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true;
$helper->toolbar_scroll = true;
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href'=>AdminController::$currentIndex.'&configure='.$this->name.
'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::
$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['MOD_SUPERMODULE_NEWSLETTER'] =
Configuration::get('MOD_SUPERMODULE_NEWSLETTER');
return $helper->generateForm($fields_form);
}
public function hookDisplayNav($params)
{
$ma_variable = Configuration::get('MOD_SUPERMODULE_OPENINGHOURS');
$this->context->smarty->assign(array(
'ma_variable' => $ma_variable
));
return $this->display(__FILE__, 'supermodulenav.tpl');
}
public function hookDisplayHeader()
{
$this->context->controller->addCSS($this->_path.'css/supermodule.css', 'all');
}
public function GetMailNewsLetter()
{
$sql='SELECT email FROM '._DB_PREFIX_.'newsletter';
$newsletter=Db::getInstance()->executeS($sql);
return $newsletter;
}
public function GetMailCustomer()
{
$sql='SELECT email FROM '._DB_PREFIX_.'customer';
$customer=Db::getInstance()->executeS($sql);
return $customer;
}
}
I think it help you
You are using wrong foreach syntax.follow the given below code.also check this and this
(foreach $newsletter as $row) // it is not a correct syntax
foreach ($newsletter as $row) // this is a correct syntax
(foreach $customer as $row) // it is not a correct syntax
foreach ($customer as $row) // this is a correct syntax
wrong syntax:
(foreach $newsletter as $row)
Correct Syntax
foreach($newsletter as $row)
The correct syntax of foreach is
foreach($newsletter as $row)
{
}
Not
(foreach $newsletter as $row)
I am using prestashop version 1.6 in localhost. I need to add our own video section in admin / back office to manage and display those videos in a separate page in front end. For example, about us and term and conditions pages like that.
I have developed my own module upto configuration section of the module. Now i need to add my own form fields like title, embedcode and submit button. I dont know how to add our own form fields with "helper class" of prestashop. Also i have read the documentation but could not able to get. Can you guide me please ? Thanks in advance and sorry for my english.
Here is my code:
videomodule.php:
<?php
if (!defined('_PS_VERSION_'))
exit;
class VideoModule extends Module
{
public function __construct()
{
$this->name = 'videomodule';
$this->tab = 'video';
$this->version = 1.0;
$this->author = 'Dinesh Kumar';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Video Module');
$this->description = $this->l('It is really an awesome experience');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
Configuration::updateValue('video', serialize(array(true, true, false)));
if (!Configuration::get('videomodule'))
$this->warning = $this->l('No name provided');
// echo Configuration::get('videoid');
}
public function getContent()
{
$output = null;
if (Tools::isSubmit('submit'.$this->name))
{
$my_module_name = strval(Tools::getValue('videomodule'));
if (!$my_module_name
|| empty($my_module_name)
|| !Validate::isGenericName($my_module_name))
$output .= $this->displayError($this->l('Invalid Configuration value'));
else
{
Configuration::updateValue('videomodule', $my_module_name);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
}
return $output.$this->displayForm();
}
public function displayForm()
{
// Get default language
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
// Init Fields form array
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Settings'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Configuration value'),
'name' => 'videomodule',
'size' => 20,
'required' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
$helper = new HelperForm();
// Module, Token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// title and Toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->fields_value['videomodule'] = Configuration::get('videomodule');
return $helper->generateForm($fields_form);
}
public function install()
{
if (Shop::isFeatureActive())
Shop::setContext(Shop::CONTEXT_ALL);
if (!parent::install() ||
!$this->registerHook('leftColumn') ||
!$this->registerHook('header') ||
!Configuration::updateValue('videomodule', 'my friend')
)
return false;
return true;
}
public function uninstall()
{
if (!parent::uninstall() ||
!Configuration::deleteByName('videomodule')
)
return false;
return true;
}
public function hookLeftColumn( $params )
{
global $smarty;
return $this->display(__FILE__,'videomodule.tpl');
}
public function hookRightColumn($params)
{
return $this->hookLeftColumn($params);
}
}