Magento 1.4 Load By Category Not Working - php

I have a Magento helper class I wrote that works wonderfully in 1.3. However, we're working on a new install of 1.4 and filtering by category won't work for some reason.
function __construct()
{
Mage::app();
$this->model = Mage::getModel('catalog/product');
$this->collection = $this->model->getCollection();
$this->collection->addAttributeToFilter('status', 1);//enabled
$this->collection->addAttributeToSelect('*');
}
function filterByCategoryID($catID)
{
$this->collection->addCategoryFilter(Mage::getModel('catalog/category')->load($catID));
}
I can't figure out why this isn't working in 1.4. Has anyone else come into this issue?

Based on what you posted, my guess would be there's something else in your code that's adding/removing filters to/from your collection. I ran the following code on a 1.4 install
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('status', 1)
->addCategoryFilter(Mage::getModel('catalog/category')->load(8))
->addAttributeToSelect('*');
and the product collection was filtered as expected.
Expanding your question to show how you're using your helper and what you expect it to do vs what it does would help.

I was able to get it working with the code below...
function __construct()
{
Mage::app();
}
function filterByCategoryID($catID)
{
//$this->collection->addCategoryFilter(Mage::getModel('catalog/category')->load($catID));
$this->collection = Mage::getModel('catalog/category')->load($catID);
}

Related

Magento2 - Newbie Select product

I have a site running Magento 2.2.1. I need to create a very simple PHP page that will look up a given product. I want to look up the product based on the SKU and just print the price and product URL out.
I have NO idea how to even start this. I have tried using this to test loading a product with ID = 1
//Get Object Manager Instance
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//Load product by product id
$product = $objectManager->create('Magento\Catalog\Model\Product')->load(1);
but all that does is throw an exeception that ObjectManager is not found. So I tried including the /app/bootstrap.php file beforehand, and that throws an error that the ObjectManager isn't initialized.
Can anyone provide me with a simple example that I can drop into the root of my site that will allow me to look up a single product by sku? Or point me in the direction of some useful documentation?
The solution to load a product programmatically in simple PHP file by using ObjectManager, but this solution is not recommended by Magento 2.
<?php
include('app/bootstrap.php');
use Magento\Framework\App\Bootstrap;
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productId = 1;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
echo $product->getName();
?>
Recommended Solution (Magento 2)
In Magento 2, the recommended way of loading product is by using ProductRepository and ProductFactory in a proper custom module instead of simple PHP file. Well, by using below (recommended) code, you can load product in your custom block.
ProductFactory Solution
<?php
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Model\ProductFactory;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productloader;
public function __construct(
ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
}
public function getLoadProduct($id)
{
return $this->_productloader->create()->load($id);
}
}
In Magento 2.1
ProductRepository Solution
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
public function getProduct($id)
{
return $product = $this->productRepository->getById($id);
}
}
and, your .phtml file should look like this:
$productId = 1;
$product = $this->getLoadProduct($productId);
echo $product->getName();
I hope, you already know how to create a custom module in Magento 2 or if you want then just read this blog post How to create a basic module in Magento 2
You Cant just Load a Page By simple PHP file in magento Here is the procedure
1)create a layout file in you theme
2)register it inside layout.xml
3)add phtml to your layout file
4)add you code(in your question ) in that phtml file
the 2nd way is quite complecated
create module and in module controller render your code

Using JToolbar or JToolbarHelper for CRUD in Joomla frontend for the custom component

For which cases are these classes suitable? I've been trying to use both, but none of them works.
The component skeleton was generated, and there are CRUD operations in the administrator's side. I tried using JToolbarHelper from this generated code, like this in mycomponent/view.html.php:
// Overwriting JView display method
function display($tpl = null)
{
// Include helper submenu
InvoiceHelper::addSubmenu('invoice');
// Assign data to the view
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))){
JError::raiseError(500, implode('<br />', $errors));
return false;
};
// Set the toolbar
$this->addToolBar();
// Show sidebar
$this->sidebar = JHtmlSidebar::render();
// Display the view
parent::display($tpl);
}
protected function addToolBar()
{
JLoader::register('JToolbarHelper', JPATH_ADMINISTRATOR.'/includes/toolbar.php');
$canDo = InvoiceHelper::getActions();
JToolBarHelper::title(JText::_('Invoice Manager'), 'invoice');
if($canDo->get('core.create')){
JToolBarHelper::addNew('invoic.add', 'JTOOLBAR_NEW');
};
if($canDo->get('core.edit')){
JToolBarHelper::editList('invoic.edit', 'JTOOLBAR_EDIT');
};
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'invoice.delete', 'JTOOLBAR_DELETE');
};
}
But it doesn't even appear on the page.
Then I came across this tutorial http://docs.joomla.org/J3.x:Using_the_JToolBar_class_in_the_frontend and it kindof works, except I can't imagine implementing something like a list of entities with checkboxes and operations for each. And it's unclear for me how to handle form submissions using this approach, seems like it happens through JS, do I get it right?
So, please tell, what's the difference and why doesn't the first approach even make the toolbar appear?
I know this is a long time ago, but I was looking to achieve the same result and found the following to loads the toolbar on the page. Using the above code:
protected function addToolBar()
{
JLoader::register('JToolbarHelper', JPATH_ADMINISTRATOR.'/includes/toolbar.php');
$canDo = InvoiceHelper::getActions();
JToolBarHelper::title(JText::_('Invoice Manager'), 'invoice');
if($canDo->get('core.create')){
JToolBarHelper::addNew('invoic.add', 'JTOOLBAR_NEW');
}
if($canDo->get('core.edit')){
JToolBarHelper::editList('invoic.edit', 'JTOOLBAR_EDIT');
}
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'invoice.delete', 'JTOOLBAR_DELETE');
}
$this->toolbar = JToolbar::getInstance(); // <<<---------- ADD THIS TO METHOD!
}
Then in your view do this:
<?php echo $this->toolbar->render(); ?>
Hope this helps!!! enjoy.

How set module view for custom searcher in prestashop 1.6

I'm trying to integrate Fotolia Api with Prestashop 1.6.0.9.
I already make module with custom tab, but I have no idea how set view from module folder for this tab. Sorry to say, but "documentation for developers" SUCKS.
I can't find any working solution.
public function install() {
if (!parent::install()
|| !$this->registerHook('backOfficeHeader')
|| !$this->registerHook('header')
) return false;
$tab = new Tab();
$tab->class_name = 'AdminFotoliaSelector';
$tab->id_parent = 0;
$tab->module = $this->name;
$tab->name[(int)(Configuration::get('PS_LANG_DEFAULT'))] = 'Fotolia Selector';
$tab->add();
return true;
}
I had big problem with make proper controller, and now I just can't load anything/ I have no idea how do this.
<?php
if (!defined('_PS_VERSION_'))
exit;
class AdminFotoliaSelectorController extends ModuleAdminController {
public $name;
public function __construct() {
$this->lang = (!isset($this->context->cookie) || !is_object($this->context->cookie)) ? intval(Configuration::get('PS_LANG_DEFAULT')) : intval($this->context->cookie->id_lang);
parent::__construct();
}
public function initContent() {
parent::initContent();
$this->renderForm();
}
public function renderForm() {
$path = _MODULE_DIR_."fotoliaselector";
$more = $this->module->display($path, 'views/templates/admin/fotoliaselector.tpl');
return $more.parent::renderForm();
}
When I try die($more) it gives me content of .tpl, anyway when I click tab in back office it's still empty.
I have debug options on, compiling on, cache off.
So just enlight me please, how am I supose to show ANYTHING there?
I think the problem is that you don't display tab's content at all.
I don't know what module->display method does, but I think you should change in initContent() method line:
$this->renderForm();
into
echo $this->renderForm();
If it won't help you should look at this documentation and try to do it without external classes - only try to use Smarty to display simple content without using Tab class or AdminFotoliaSelector
Well i know it will sounds weird but you need to take some similar modules, and read his code and will see some methods names are the same in each module.
Then copy that, install and play with some changes etc.
Imho you miss standard method getContent() form where you need to pass some data for smarty:
public function getContent()
{
global $smarty, $cookie;
......
//some code
......
$this->_html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>';
$this->_html .= '<h1>My module title or stuff</h1>';
$this->_html .= $this->getMyCoolFormOrConfig();
$smarty->assign('errors', $this->errors);
$smarty->assign('message', $this->message);
$this->_html .= $this->display(__FILE__, 'name_of_tpl_file.tpl');
return $this->_html;
}
to simple add tab in BackOffice code like this:
$id_tab=Tab::getIdFromClassName('AdminPayment');
$newtab=new Tab();
$newtab->id_parent=$id_tab;
$newtab->module=$this->name;
$newtab->class_name='MyClassName'; //will be same like MyClassName.php in folder of you module where you need to create you class and extend the AdminTab and from there with function you need to echo you name module
$newtab->position=Tab::getNbTabs($id_tab)+1;
$newtab->name[$cookie->id_lang]=$this->l("Name of you stuff");
$newtab->name[Configuration::get('PS_LANG_DEFAULT')]=$this->l("Name of you stuff");
$newtab->add();
Study this file there /controllers/admin/AdminModulesController.php
and you see what methods are using in each module
Take a look greater feature to generate you module structure (register requeired) https://validator.prestashop.com/generator

What replaces get_course_category_tree() in Moodle 2.5?

I've followed a Tutorial on Moodle.org on how to extend the custom menu and I'm receiving this error message in Moodle 2.5:
Function get_course_category_tree() is deprecated, please use course renderer or coursecat class, see function phpdocs for more info
The code works, but I would like to upgrade the code for Moodle 2.5. I've found documentation on replacement functions.
Below is the code directly from the tutorial. I need to replace get_category_tree().
class theme_mytheme_core_renderer extends core_renderer {
protected function render_custom_menu(custom_menu $menu) {
global $CFG;
require_once($CFG->dirroot.'/course/lib.php');
$branch = $menu->add(get_string('courses', 'theme_mytheme'), null, null, 10000);
$categorytree = get_course_category_tree();
foreach ($categorytree as $category) {
$this->add_category_to_custommenu($branch, $category);
}
return parent::render_custom_menu($menu);
}
}
Here is the documentation for the new functions. I've tried all three of the following functions with no success. Does anyone have any thoughts or pointers?
core_course_renderer::coursecat_coursebox()
core_course_renderer::coursecat_courses()
core_course_renderer::coursecat_tree()
You can use $courses = get_courses($categoryid) to get the result.

Why I can't load models in modules?! [Using HMVC in codeigniter 2.1.2]

I hope someone can help me with this one before I jump off the window. I spent few hours on this one and don't know what am I doing wrong.
Basically, I've installed HMVC in CodeIgniter 2.1.2 and everything works fine, BUT for some reason I can't load models the same way I'm doing it in standard controllers. In the old codeigniter 1.7.1 I could use it simply by invoking $this->load->model('my_model') but now I can't?!
Every single time I'm trying to load model I get this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Special_cart::$db
Filename: core/Model.php
Line Number: 51
I have had installed it step-by-step according to the instructions. I got third_party next to modules folder. In modules I have few modules stored like this:
modules
--boxes
----controller
----models
----views
I invoke module in my code like this:
<?=modules::run('boxes/special_cart/index');?>
My module controller code looks like this:
class Special_cart extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
if ($this->session->userdata('cart'))
{
# get product id's and each quantity
$cart_product_list = array_count_values($this->session->userdata('cart'));
# get list of product_id
$product_list = array_keys($cart_product_list);
# get product details
$this->load->model('productmodel');
$this->load->model('stockmodel');
$cart_products = $this->productmodel->cart_get_products_details($product_list);
$final_cart_array = array();
foreach($cart_products as $cart_product){
$product_stock = $this->stockmodel->view_product_stock($cart_product["id"]);
if(empty($product_stock) || $product_stock["UNITS"]<=0)
$cart_product["UNITS"] = 0;
else{
if($cart_product_list[$cart_product["id_web"]]>$product_stock["UNITS"])
$cart_product["UNITS"] = $product_stock["UNITS"];
else{
$cart_product["UNITS"] = $cart_product_list[$cart_product["id_web"]];
}
}
$final_cart_array[] = $cart_product;
}
$refresh_cart_array = array();
foreach($final_cart_array as $cart_product){
for($i=1;$i<=$cart_product["UNITS"];$i++){
$refresh_cart_array[] = $cart_product["id_web"];
}
}
$this->load->view("special_cart",array(
'refresh_cart_array' => $refresh_cart_array,
'final_cart_array' => $final_cart_array
));
} else {
$this->load->view("special_cart",array(
'refresh_cart_array' => NULL,
'final_cart_array' => NULL
));
}
}
}
I've tried every possible solution found on internet - none of them work....
I hope you understand my problem but in case you need some further explanation please ask me. Can anyone help?
Looks like the model you're trying to load wants to connect to the db, but the database driver is not available. If you use database queries in your application, why don't you load the database driver automatically?
Just insert "database" in the "libraries" array in application/config/autoload.php file. Don't forget to insert your database credentials into application/config/database.php.
$autoload['libraries'] = array('database');
If you need database connection just in one single model, load it before trying to access database library.
$this->load->database();
Try loading the model stating the module name as follows
$this->load->model('module_name/productmodel');
Class Models extends MX_Loader{
function getUser($username){
$sql="SELECT * FROM user WHERE username = ? ";
return $this->db->query($sql,array($username))->row();
}
}
you must using extends MX_Loader because i don't know if using CI_Model the database core cant be load in Codeigniter,,,
Try to use extend MX_Controller class (not CI_Contoller like you are doing atm)
Based on what you have wrote in comment above, I figured that you tried to create new instance of DB in module (based on chrises comment).
Do it on constuctor of Special_cart
So update current construct to be like
public function __construct()
{
parent::__construct();
$this->load->database('default');
}
(I'm writing this from top of my head, so check the methods)
Now for sure db driver should be available in your models.
Regarding issue with HMVC I dont think there are any. I'm using HMVC for a while now, and I found no problems in it (working with databases)
I had the same problem and mistake. I missed to extend controllers to MX_Controller. So the solution would be to change CI_Controller to MX_Controller like this:
class Special_cart extends MX_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('productmodel');
$this->load->model('stockmodel');
}
public function index()
{
if ($this->session->userdata('cart'))
{
# get product id's and each quantity
$cart_product_list = array_count_values($this->session->userdata('cart'));
# get list of product_id
$product_list = array_keys($cart_product_list);
# get product details
$cart_products = $this->productmodel->cart_get_products_details($product_list);
$final_cart_array = array();
foreach($cart_products as $cart_product){
$product_stock = $this->stockmodel->view_product_stock($cart_product["id"]);
if(empty($product_stock) || $product_stock["UNITS"]<=0)
$cart_product["UNITS"] = 0;
else{
if($cart_product_list[$cart_product["id_web"]]>$product_stock["UNITS"])
$cart_product["UNITS"] = $product_stock["UNITS"];
else{
$cart_product["UNITS"] = $cart_product_list[$cart_product["id_web"]];
}
}
$final_cart_array[] = $cart_product;
}
$refresh_cart_array = array();
foreach($final_cart_array as $cart_product){
for($i=1;$i<=$cart_product["UNITS"];$i++){
$refresh_cart_array[] = $cart_product["id_web"];
}
}
$this->load->view("special_cart",array(
'refresh_cart_array' => $refresh_cart_array,
'final_cart_array' => $final_cart_array
));
} else {
$this->load->view("special_cart",array(
'refresh_cart_array' => NULL,
'final_cart_array' => NULL
));
}
}
}
this is also explained in the documentation
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/
, here the quote:
Notes:
To use HMVC functionality, such as Modules::run(), controllers must
extend the MX_Controller class. To use Modular Separation only,
without HMVC, controllers will extend the CodeIgniter Controller
class. You must use PHP5 style constructors in your controllers. ie:
<?php
class Xyz extends MX_Controller
{
function __construct()
{
parent::__construct();
}
}

Categories