I have added a field to my Prestashop registration form and I want to display and update it from the user interface. I already have a good part since the field appears, we can fill it and it is displayed in the database. The problem is that I am missing an essential part; the possibility to display it in the user interface and the update, can someone help me ? I have a get function and I think I need a set function too to be able to update, but I don't know what to write in it
My module files
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
use PrestaShop\PrestaShop\Adapter\Presenter\Object\ObjectPresenter;
require_once dirname(__FILE__) . '/classes/CustomerFonction.php';
class AddJob extends Module
{
public function __construct()
{
$this->name = 'addjob';
$this->tab = 'others';
$this->version = '1.0.0';
$this->author = 'advisa';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.6',
'max' => '1.7.99',
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('AddJob');
$this->description = $this->l('Add job in registration form');
}
public function install()
{
return parent::install() &&
$this->installSql() &&
$this->registerHook('additionalCustomerFormFields') &&
$this->registerHook('actionCustomerAccountAdd');
}
public function uninstall()
{
return (
parent::uninstall()
);
}
/*
public function installSql()
{
$sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "customer "
. "ADD fonction VARCHAR(255) NULL";
return Db::getInstance()->execute($sqlInstall);
} */
public function installSql()
{
$sqlQuery = array();
$sqlQuery[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'addjob_addfonction` (
`id_addfonction` INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
`id_customer` INT(10),
`fonction` VARCHAR(255)
)';
$db = Db::getInstance();
foreach ($sqlQuery as $query) {
if (!$db->execute($query)) {
return false;
}
}
return true;
}
public function hookAdditionalCustomerFormFields($param)
{
$field = array();
$field['fonction'] = (new FormField())
->setName('fonction')
->setType('text')
//->setRequired(true)
->setLabel($this->l('Fonction'));
if($this->context->customer->id !== null){
$data = new CustomerFonction($this->context->customer->id);
$field['fonction']->setValue($data->fonction ?? '');
}
return $field;
}
public function hookActionCustomerAccountAdd($param)
{
$customeField = new CustomerFonction();
$customeField->id_customer = $param['newCustomer']->id;
$customeField->fonction = Tools::getValue('fonction', '');
$customeField->add();
}
public function hookActionCustomerAccountUpdate($param)
{
$customerId = $this->context->customer->id;
$customerField = new CustomerFonction($customerId);
$customerField->id_customer = $customerId;
$customerField->fonction = Tools::getValue('fonction', '');
$customerField->save();
}
}
And my ObjectModel classes
<?php
class CustomerFonction extends ObjectModel
{
public $id_addfonction;
public $id_customer;
public $fonction;
public static $definition = [
'table' => 'addjob_addfonction',
'primary' => 'id_addfonction',
'multilang' => false,
'fields' => [
'id_customer' => ['type' => self::TYPE_INT],
'fonction' => ['type'=>self::TYPE_STRING, 'size'=> 255],
],
];
public static function getFonctionByCustomer($id_customer): ?string
{
$sql = new DbQuery();
$sql->select('fonction');
$sql->from('addjob_fonction');
$sql->where('id_customer = ' . $id_customer);
return Db::getInstance()->getValue($sql);
}
public static function getByCustomerId(): self
{
}
public static function setFonctionByCustomer(string $fonction, $id): self
{
}
}
Related
Typo3 10.4
I created Models, Repositories and Controller. Values are getting written from the backend into the database but I can't get a bunch of values to the frontend. It's not all values that don't work but some.
class Element extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
protected $type = "";
protected $name = "";
protected $beschreibung = "";
protected $customRender = "";
protected $mehrHtml = "";
protected $formsUsingThisElement = "";
public function __construct(string $type='', string $name='', string $beschreibung = '', string $customRender = '') {
$this->setType($type);
$this->setName($name);
$this->setBeschreibung($beschreibung);
$this->setCustomRender($customRender);
}
public function setType(string $type):void {
$this->type = $type;
}
public function getType():string {
return $this->type;
}
public function setName(string $name):void {
$this->name = $name;
}
public function getName():string {
return $this->name;
}
public function setBeschreibung(string $beschreibung):void {
$this->beschreibung = $beschreibung;
}
public function getBeschreibung():string {
return $this->beschreibung;
}
public function setCustomRender(string $customRender):void {
$this->customRender = $customRender;
}
public function getCustomRender():string {
return $this->customRender;
}
public function setMehrHtml(string $mehrHtml) {
$this->mehrHtml = $mehrHtml;
}
public function getMehrHtml() {
return $this->mehrHtml;
}
public function setFormsUsingThisElement(string $formsUsingThisElement):void {
$this->formsUsingThisElement = $formsUsingThisElement;
}
public function getFormsUsingThisElement(): string {
return $this->formsUsingThisElement;
}
}
Both $mehrHtml and $customRender actually have values but I can only get the other variables from the database.
While $type is of type select, $name and $beschreibung are of types input the two variables which I can not get the value of are config.type='text' in the TCA. But that shouldn't matter as I got another model which holds a text which is readable but an integer which I, too, can not get the value.
EDIT
Thomas remarked that the TCA might be misconfigured. Indeed were the columns in the Database in lowerCamelCase instead of snake_case which is why I didn't get any values from the database.
return [
'ctrl' => [
//... ,
],
'columns' => [
'default_options' => [ //IMPORTANT HERE. snake_case instead of camelCase like in variable names.
'exclude' => true,
'label' => 'Standardangaben',
'config' => [
//....
],
],
],
];
I have a simple ACL configures in an acl.global.php like this:
return [
'acl' => [
'roles' => [
'guest' => null,
'member' => 'guest',
'admin' => 'member'
],
'resources' => [
'allow' => [
'Application\Controller\Index' => ['all' => 'member'],
'Application\Controller\Error' => ['all' => 'member'],
'Item\Controller\Process' => [
'index' => 'member',
'create' => 'member',
'showItem' => 'member', // website.tld/item/:id
'showList' => 'member' // website.tld/list-items
]
]
],
]
];
A parser iterates through the configuration and generates from the array elements calls to Zend\Permissions\Acl#allow(...) like $this->allow($role, $controller, $action);.
Now I need additionally to restrict the access of the users to the item's single view (mydomain.tld/item/:id). A user should only get the access, if its id equals to the item.user_id (means: the user is the author/owner).
The way I see to implement this requirement is to extend the config
'Item\Controller\Process' => [
'index' => 'member',
'create' => 'member',
'showItem' => [
'role' => 'member',
'assertion' => 'UserIsOwner'
]
'showList' => 'member'
]
and to inject the Assertion to Zend\Permissions\Acl#allow(...): $this->allow($role, $controller, $action, $assertion);.
namespace Authorization\Acl\Assertion;
use ...
class UserIsOwner implements AssertionInterface
{
protected $userId;
// To inject the $userId can be the job of the factory.
public function __construct(int $userId)
{
$this->userId = $userId;
}
public function assert(Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null)
{
return return $this->userId === ???;
}
}
But now I have no idea, how the assertion should get the item.user_id injected. The example in the docu doesn't have this problem, since it assets against the $_SERVER['REMOTE_ADDR'].
I can inject the ItemService to find out the item.user_id:
public function assert(Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null)
{
return $this->isUserOwner();
}
protected function isUserOwner()
{
$itemId = ???;
$item = $this->itemService->findOne($itemId);
$itemOwnerId = $item->getUser()->getId();
return $this->userId == $itemOwnerId;
}
Though then I still need external data -- the current item.id.
At what place can/should the variable item's data (in this case the item.user_id or item.id) be injected to an assertion?
Finally I resolved the problem by injecting the variable data via the resource. Don't think, that it's the cleanest or a recommended solution. Anyway it works. But it would be nice to know, how to resolve it a clean / more elegant way.
UserIsOwner
namespace Authorization\Acl\Assertion;
use Zend\Permissions\Acl\Assertion\AssertionInterface;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\RoleInterface;
use Zend\Permissions\Acl\Resource\ResourceInterface;
use Item\Service\ItemService;
class UserIsOwner implements AssertionInterface
{
/**
*
* #var integer
*/
protected $userId;
/**
*
* #var ItemService
*/
protected $itemService;
public function __construct(int $userId, ItemService $itemService)
{
$this->userId = $userId;
$this->itemService = $itemService;
}
public function assert(Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null)
{
return isset($resource->getParams()['id']) ? $this->isUserOwner($resource->getParams()['id']) : false;
}
protected function isUserOwner($itemId)
{
$item = $this->itemService->findOne($itemId);
$itemOwnerId = $item->getUser()->getId();
return $this->userId == $itemOwnerId;
}
}
UserIsOwnerFactory
namespace Authorization\Acl\Assertion\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Authorization\Acl\Assertion\UserIsOwner;
class UserIsOwnerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$itemFieldsetService = $serviceLocator->get('Item\Service\ItemService');
$authenticationService = $serviceLocator->get('AuthenticationService');
$userId = !empty($authenticationService->getIdentity()['id']) ? $authenticationService->getIdentity()['id'] : null;
$service = new UserIsOwner($userId, $itemFieldsetService);
return $service;
}
}
ParametrizedResource
namespace Authorization\Acl\Resource;
use Zend\Permissions\Acl\Resource\GenericResource;
use Zend\Mvc\Router\Http\RouteMatch;
class ParametrizedResource extends GenericResource
{
/**
* #var array Params. Here the RouteMatch#params.
* #see RouteMatch
*/
protected $params;
public function __construct($resourceId, array $params = [])
{
parent::__construct($resourceId);
$this->setParams($params);
}
/**
*
* #return the $params
*/
public function getParams()
{
return $this->params;
}
/**
*
* #param multitype: $params
*/
public function setParams($params)
{
$this->params = $params;
}
}
Acl
...
// #todo refactor
protected function addResources(array $resources)
{
foreach ($resources as $permission => $controllers) {
foreach ($controllers as $controller => $actions) {
if ($controller == 'all') {
$controller = null;
} else {
if (! $this->hasResource($controller)) {
$this->addResource(new Resource($controller, $this->routeMatchParams));
}
}
foreach ($actions as $action => $roleConfig) {
if (is_array($roleConfig)) {
foreach ($roleConfig as $role => $assertion) {
if ($action == 'all') {
$action = null;
}
$assertion = !empty($this->assertions[$assertion]) ? $this->assertions[$assertion] : null;
if ($permission == 'allow') {
$this->allow($role, $controller, $action, $assertion);
} elseif ($permission == 'deny') {
$this->deny($role, $controller, $action, $assertion);
} else {
throw new \Exception('No valid permission defined: ' . $permission);
}
}
} elseif (is_string($roleConfig)) {
if ($action == 'all') {
$action = null;
}
if ($permission == 'allow') {
$this->allow($roleConfig, $controller, $action);
} elseif ($permission == 'deny') {
$this->deny($roleConfig, $controller, $action);
} else {
throw new \Exception('No valid permission defined: ' . $permission);
}
}
}
}
}
return $this;
}
...
AclFactory
namespace Authorization\Acl\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Authorization\Acl\Acl;
class AclFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$assertions = [
'UserIsOwner' => $serviceLocator->get('Assertion\UserIsOwner')
];
$routeMatch = $serviceLocator->get('Application')->getMvcEvent()->getRouteMatch();
$routeMatchParams = $routeMatch->getParams();
$service = new Acl($config, $assertions, $routeMatchParams);
return $service;
}
}
I don't know if you can apply my solution because I configure my Acl in a AclService Class which wraps the Zend\Permission\Acl.
In this AclService I have defined a $assertions variable, which is an array which stores an object of every assertion that I have to use.
namespace User\Service;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Zend\Permissions\Acl\Acl;
use User\Service\Assertion\RightLeagueAssertion;
use User\Service\Assertion\RightLeagueTeamAssertion;
class AclService {
const ROLE_GUEST = 'guest';
const ROLE_MEMBER = 'member';
const ROLE_COMISSIONER = 'comissioner';
const ROLE_ADMIN = 'admin';
const ROLE_GOD = 'god';
const ASSERTION_RIGHT_LEAGUE_TEAM = 'RightLeagueTeamAssertion';
protected $acl = null;
protected $assertions;
/**
* Constructor
*
* #param Acl $acl
* #return void
* #throws \Exception
*/
public function __construct($acl)
{
$this->acl = $acl;
$this->assertions[self::ASSERTION_RIGHT_LEAGUE_TEAM] = $rightLeagueTeam;
/* Declaramos los roles */
$this->acl->addRole(new Role(self::ROLE_GUEST));
$this->acl->addRole(new Role(self::ROLE_MEMBER), self::ROLE_GUEST);
$this->acl->addRole(new Role(self::ROLE_COMISSIONER), self::ROLE_MEMBER);
$this->acl->addRole(new Role(self::ROLE_ADMIN), self::ROLE_MEMBER);
//unique role for superadmin
$this->acl->addRole(new Role(self::ROLE_GOD));
/* Declaramos los recursos (module:controller) */
$this->acl->addResource(new Resource('application:index'));
$this->acl->addResource(new Resource('application:error'));
$this->acl->addResource(new Resource('user:user'));
$this->acl->addResource(new Resource('leueroneyear:league'));
$this->acl->addResource(new Resource('leueroneyear:team'));
/*** Permisos ***/
//'God' tiene permiso para todo
$this->acl->allow(self::ROLE_GOD);
//Una persona no logueada podrá ver solo el índice, errores, darse de alta y recuperar el password
$this->acl->allow(self::ROLE_GUEST, 'application:index', 'index');
$this->acl->allow(self::ROLE_GUEST, 'user:user', array('register','forgotpassword','resetpassword','login'));
$this->acl->allow(self::ROLE_GUEST, 'application:error');
$this->acl->allow(self::ROLE_GUEST, 'nba:test');
//Los usuarios sí que podrán visitar las páginas
$this->acl->allow(self::ROLE_MEMBER, 'user:user', array('get','edit', 'logout'));
$this->acl->allow(self::ROLE_MEMBER, 'leueroneyear:league', array('index','get','list','add','enter'));
$this->acl->allow(self::ROLE_MEMBER, 'leueroneyear:team', array('get','add'));
$this->acl->allow(self::ROLE_MEMBER, 'leueroneyear:team', 'index',$this->assertions[self::ASSERTION_RIGHT_LEAGUE_TEAM]);
}
public function getAcl()
{
return $this->acl;
}
public function isAllowed($role, $controller, $action)
{
$a = explode("\\",$controller);
$resource = strtolower($a[0]).":".strtolower($a[2]);
//\Zend\Debug\Debug::dump($resource); die();
return $this->acl->isAllowed($role, $resource, $action);
}
public function setRequestParams($params)
{
$a = explode("\\",$params["controller"]);
$controller = strtolower($a[2]);
switch ($controller) {
case 'team': $this->assertions[self::ASSERTION_RIGHT_LEAGUE_TEAM]->setRequestParams($params);
break;
}
}
}
When is time to check if somebody is allowed to use a resource, I inject the parameters of the route matched in the AclService which injects them in every assertion class previously instantiated (function 'setRequestParams').
/**
* #param MvcEvent $e
*/
public function onRoute(MvcEvent $event)
{
$matches = $event->getRouteMatch();
$controller = $matches->getParam('controller');
$action = $matches->getParam('action','index');
$auth = $this->authService;
/* #var $user User\Entity\User */
if ($user = $auth->getIdentity()) {
$session = new Container("League");
if (isset($session->isCommissioner) && $session->isCommissioner)
$role = AclService::ROLE_COMISSIONER;
else
$role = AclService::ROLE_MEMBER;
} else {
$role = AclService::ROLE_GUEST;
}
$acl = $this->aclService;
$acl->setRequestParams($matches->getParams());
if (!$acl->isAllowed($role,$controller, $action)) {
//El usuario no tiene los permisos necesarios
$app = $event->getTarget();
$route = $event->getRouteMatch();
$event -> setError(RouteGuard::ERROR)
-> setParam('route', $route->getMatchedRouteName());
$app->getEventManager()->trigger('dispatch.error', $event);
}
}
In this way, you can access these parameters in your assertion classes.
class RightLeagueTeamAssertion implements AssertionInterface
{
protected $requestParams;
public function setRequestParams($params)
{
$this->requestParams = $params;
}
/**
* Comprueba que el idTeam que pasan por parámetro pertenece a la liga en la que estás logueado
*/
public function assert(Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null) {
$appSession = new Container("Application");
$leagueSession = new Container("League");
$idLeague = $leagueSession->idLeague;
$idTeam = $this->requestParams['id'];
\Zend\Debug\Debug::dump($idTeam);
return false;
}
}
If you can not apply this solution directly, I hope it can point you to the right direction.
I tried to set up a sign up logic but suffer a problem said
Message: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'member_login' cannot be null, query was: INSERT INTO members (member_login) VALUES (?)enter image description here
After struggling for hours, still no ideas which go wrong. Here is my source code.
Anyone can give me some ideas?
My Model.php
<?php
class Application_Model_Member
{
protected $_id;
protected $_member_login;
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid member property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid member property');
}
return $this->$method();
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = (int) $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setMemberLogin($text)
{
$this->_member_login = (string) $text;
return $this;
}
public function getMemberLogin()
{
return $this->_member_login;
}
}
My MemberMapper.php
<?php
class Application_Model_MemberMapper
{
protected $_dbTable;
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Members');
}
return $this->_dbTable;
}
public function save(Application_Model_Member $member)
{
$data = array(
'member_login' => $member->getMemberLogin(),
);
if (null === ($id = $member->getId())) {
unset($data['member_id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('member_id = ?' => $id));
}
}
public function find($id, Application_Model_Member $member)
{
$result = $this->getDbTable()->find($id);
if (0 == count($result)) {
return;
}
$row = $result->current();
$member->setId($row->member_id)
->setMemberLogin($row->member_login);
}
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Member();
$entry->setId($row->member_id)
->setMemberLogin($row->member_login);
$entries[] = $entry;
}
return $entries;
}
}
DbTable:
class Application_Model_DbTable_Members extends Zend_Db_Table_Abstract
{
protected $_name = 'members';
}
Form: Registration.php
<?php
class Application_Form_Auth_Registration extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->addElement(
'text', 'member_login', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim')
));
$this->addElement('submit', 'register', array(
'ignore' => true,
'label' => 'Sign up'
));
}
}
Signup controller:
public function signupAction()
{
$request = $this->getRequest();
$regform = new Application_Form_Auth_Registration();
if ($this->getRequest()->isPost()) {
if ($regform->isValid($request->getPost())) {
$member = new Application_Model_Member($regform->getValues());
$mapper = new Application_Model_MemberMapper();
$mapper->save($member);
return $this->_helper->redirector('/books/view');
}
}
$this->view->regform = $regform;
}
Finally I fix the bug. It go wrong with the naming of Element. For example, in your database you have "member_login", then the Element name should be sth like memberLogin.
I'm a new user of Magento and i work on the creation of a module to do Cross-Selling.
I already take all of the command who have more than 1 product to make relation with that. But now, to complete my code and module i wanted to know how can i recovery the command with more than 1 article and take also all the command of the customer (a lot of customer have buy 1 by 1 some products).
Sorry for my english but i hope you have understand.
Right now, the module put in a table (work with a cron), all data every day but let see the code :
My block :
class MyCompany_Crosssell_Block_Crosssell extends Mage_Catalog_Block_Product_Abstract {
public function _prepareLayout() {
return parent::_prepareLayout();
}
public function getTitle() {
$title = Mage::getStoreConfig('catalog/crosssell/title');
return $title;
}
public function getEnable() {
return Mage::getStoreConfig('catalog/crosssell/enable');
}
public function getProductsBought(){
return Mage::getModel('MyCompany_crosssell/crosssell')
->getBoughtProducts(Mage::helper('MyCompany_crosssell')->getcollectProductBoughtId(Mage::registry('current_product')))
->setPageSize(Mage::getStoreConfig('catalog/crosssell/products'));
}
}
My Helper :
class Mycompany_Crosssell_Helper_Data extends Mage_Core_Helper_Abstract {
public function getcollectProductBoughtId($product){
return explode(',',Mage::getModel('Mycompany_crosssell/crosssell')->load($product->getId())->getProducttype());
}
}
Model :
class Mycompany_Crosssell_Model_Observer extends Varien_Event_Observer {
public function __construct() {
}
public function crosssell($observer) {
$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
$collection->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$collection->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$connexion = Mage::getSingleton('core/resource')->getConnection('core_write');
$connexion->query("TRUNCATE TABLE `crosssell_crosssell`");
$values = array();
$cpt = 0;
foreach ($collection as $product) {
$productids = Mage::getModel('Mycompany_crosssell/crosssell')->collectProductBoughtId($product);
/* $model = Mage::getModel('Mycompany_crosssell/crosssell');
$model->setData('productid', $product->getId());
$model->setData('producttype', implode(',', $productids));
$model->save(); */
if ($productids) {
$values[] = "(" . $product->getId() . ", '" . implode(',', $productids) . "')";
if ($cpt++ > 500) {
$connexion->query("
INSERT IGNORE INTO `crosssell_crosssell`(productid, producttype) VALUES " . implode(',', $values));
$cpt = 0;
$values = array();
}
}
}
$connexion->query("
INSERT IGNORE INTO `crosssell_crosssell`(productid, producttype) VALUES " . implode(',', $values));
}
}
class Mycompany_Crosssell_Model_Crosssell extends Mage_Core_Model_Abstract {
public function _construct() {
parent::_construct();
$this->_init('Mycompany_crosssell/crosssell');
}
public function collectProductBoughtId($product) {
$_order = '';
$_productOption = array();
$productOption = array();
$_orderId = '';
$_order = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('product_id', $product->getId());
foreach ($_order as $order) {
$_orderId[] = $order->getOrderId();
}
$_product = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('order_id', $_orderId)
->addAttributeToFilter('product_id', array('neq' => $product->getId()));
foreach ($_product as $_productData) {
$_productId[] = $_productData->getProductId();
}
return array_unique($_productId);
}
public function getBoughtProducts($product) {
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id', array('in', $product));
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
$collection->addAttributeToSelect($attributes)
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
return $collection;
}
}
class Mycompany_Crosssell_Model_Mysql4_Crosssell_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct(){
$this->_init('Mycompany_crosssell/crosssell');
}
}
class Mycompany_Crosssell_Model_Mysql4_Crosssell extends Mage_Core_Model_Mysql4_Abstract
{
protected function _construct()
{
$this->_init('Mycompany_crosssell/crosssell', 'productid');
}
}
SQL:
<?php
$installer = $this;
$installer->startSetup();
$table = $installer->getConnection()
->newTable($installer->getTable('Mycompany_crosssell/crosssell'))
->addColumn('productid', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'auto_increment' => false,
'identity' => false,
'unsigned' => true,
'nullable' => false,
'primary' => true,
), 'ID product')
->addColumn('producttype', Varien_Db_Ddl_Table::TYPE_VARCHAR, null, array(
'auto_increment' => false,
'identity' => false,
'unsigned' =>false,
'nullable' =>false,
'primary' =>false,
), 'type product');
$installer->getConnection()->createTable($table);
$installer->endSetup();
I created a standart class Loadercontent(controller) in Codeigniter.
Also in the same file a add abstract Search class and child class SearchDoctor:
When I try to get CI instance &get_instance(); at abstract constructor, I get NULL:
$this->_ci =&get_instance();
var_dump($this->_ci); // NULL
So after I can not use:
$this->_ci->load->view($this->view, $this->item);
because $this->_ci is empty. What is wrong in my code ot abstract class in CI? Also maybe you can ask something about code? Is it wrong?
The full code:
<?php
abstract class Search
{
protected $fields = array('country' => 'country', 'city' => 'city');
protected $table;
protected $limit = 20;
protected $offset = 0;
protected $items;
protected $rand = false;
protected $data;
protected $view;
protected $_ci;
public function __construct($input)
{
$this->_ci =&get_instance();
$this->data = $input;
$this->getPostGet();
}
public function getPostGet(){
if(empty($this->data)){
foreach($this->data as $key => $val){
$this->_check($val, $key);
}
}
}
public function _check($val, $key){
if(in_array($val, $this->fields)){
$this->items[] = $this->getField($val, $key);
}
}
public function getField($value, $key){
return $key. ' = '.$value;
}
public function doQuery(){
if(!empty($this->items)){
$limit = $this->formatLimit();
$this->items = $this->other_model->getItemsTable($this->query, $this->table, $limit);
}
}
public function formatLimit(){
$this->offset = (isset($this->data['limit'])) ? $this->data['limit'] : $this->offset;
$this->limit = (isset($this->data['limit'])) ? $this->offset + $this->limit : $this->limit;
return array('offset' => $this->limit, 'limit' => $this->limit);
}
public function addFields($array){
$this->fields = array_merge($this->fields, $array);
}
public function getView(){
$this->_ci->load->view($this->view, $this->item);
}
public function response(){
echo json_encode($this->view); die();
}
}
class SearchDoctor extends Search
{
protected $fields = array('name' => 'DetailToUsersName');
public function __construct($type)
{
$this->table = 'users';
$this->view = 'users/doctors_list';
$this->limit = 10;
$this->rand = true;
$this->addFields($this->fields);
parent::__construct($type);
}
}
/* Init class */
class Loadercontent {
public function index(){
if(isset($_GET) || isset($_POST)){
$class = 'Search';
if(isset($_POST['type'])){
$type = $_POST['type'];
$input = $_POST;
}
if(isset($_GET['type'])){
$type = $_GET['type'];
$input = $_GET;
}
$class = $class.$type;
if (class_exists($class)) {
$obj = new $class($input);
$obj->getView();
$obj->response();
}
}
}
}
?>