Magento2 - Newbie Select product - php

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

Related

Rendered view is not displaying in my back office in PS 1.7

I am trying to create a view in the back office tab that I created in the installation of my Module. My Module adds the tab like this:
protected function _installTabs()
{
if(!$tabId = \Tab::getIdFromClassName('IezonPortfolio')) {
$tab = new \Tab();
$tab->class_name = 'IezonPortfolio';
$tab->module = $this->name;
$tab->id_parent = \Tab::getIdFromClassName('ShopParameters');
$tab->active = 1;
foreach (Language::getLanguages(false) as $lang):
$tab->name[(int) $lang['id_lang']] = 'My Portfolio';
endforeach;
return $tab->save();
}
new \Tab((int) $tabId);
return true;
}
This works fine and I can navigate to my Shop Parameters and click the My Portfolio tab. The issue I'm having is that it is blank. My ModuleAdminController looks like this:
class IezonPortfolioController extends ModuleAdminController {
private $_module;
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->_module = \Module::getInstanceByName('iezonportfolio');
}
public function indexAction()
{
return $this->render('#Modules/iezonportfolio/views/templates/admin/display.html.twig', array(
'contents_iezonportfolio' => $this->_module->selectAll()
));
}
}
My display.html.twig just has test in it to see if it would output anything which it didn't. On looking at the Docs it doesn't mention anything other than using the render function and returning it. Any help would be appreciated. I just get a blank Tab.
EDIT: After looking at some of the pre-installed modules and referencing them to the Docs, I saw that I was missing my route configuration. My Controller is in the documented directory set-up: iezonportfolio/controllers/admin/iezonportfolio.php so I made my route like this:
iezonportfolio:
path: iezonportfolio
methods: [GET]
defaults:
_controller: 'IezonPortfolio\Controllers\Admin\Controller::indexAction'
_legacy_controller: 'IezonPortfolioController'
_legacy_link: 'IezonPortfolioController:index'
This has still not yet fixed the blank display so I tried to dig deeper into some other modules and have now updated my display.html.twig to show this:
{% extends '#PrestaShop/Admin/layout.html.twig' %}
{% block content %}
Test
{% endblock %}
This did not fix the blank display either. I hope this addition is useful for future viewers.
This is not how the modern controllers works, you are extending legacy ModuleAdminController, take a look here:
https://github.com/PrestaShop/example-modules
you have a plenty of module examples, here's a little snippet from one of those modules:
declare(strict_types=1);
namespace PrestaShop\Module\DemoControllerTabs\Controller\Admin;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\Response;
class MinimalistController extends FrameworkBundleAdminController
{
/**
* #return Response
*/
public function indexAction()
{
return $this->render('#Modules/democontrollertabs/views/templates/admin/minimalist.html.twig');
}
}
I recommend you to think wether you want to use, or not, modern controller. It depends on wether you want to sell your module, use it in client projects etc.

TYPO3 v8. Override function in Core class

I need to override the function
protected function getLanguageParameter()
{
$states = $this->getBackendUser()->uc['moduleData']['web_view']['States'];
$languages = $this->getPreviewLanguages();
$languageParameter = '';
if (isset($states['languageSelectorValue']) && isset($languages[$states['languageSelectorValue']])) {
$languageParameter = '&L=' . (int)$states['languageSelectorValue'];
}
$languageParameter = '&L=1';
return $languageParameter;
}
in the class TYPO3\CMS\Viewpage\Controller\ViewModuleController. It get called when you are open the View in the backend.
Lets say I would extend the class in my own extension. I already need a Hook that calls the function?
But how can I get that hook?
If the function has no hook yet you can try to insert it: make a patch and wait for it to become merged.
As 8 LTS already receives only 'priority bugfixes' it probably will not get merged.
The other way would be XClassing.

Get at a categories image in PHP | Magento2

I am trying to get at a categories image from within PHP / a .phtml file.
Here is my code:
$_category = $this->getCurrentCategory();
$_children = $_category->getChildrenCategories();
foreach( $_children as $child ){
if( $child->getIsActive() ){
echo "<p>" . $child->getImageUrl() . "</p>";
This last line results in an empty string. When I var_dump it, I get the following:
bool(false)
Upon further investigation, this getImageUrl function is defined in /vendor/magento/module-catalog/Model/Category.php on line 656, like so:
public function getImageUrl(){
$url = false;
$image = $this->getImage();
if ($image) {
The problem here is that $this->getImage() returns NULL. Nowhere in Category.php can I find the function getImage, and all of this makes me think that there is no getImage function in the Category class.
Is this correct? Do we need to add a getImage method to the class to make getImageUrl work?
Or is getImage inherited from elsewhere? And in this case, why is it returning NULL?
Disclaimers:
This is Magento 2.0.2.
I am not about to alter core code, I already have a theme of my own, and if I was to add a new function to the Category class I would extend the core code in my theme.
I have re-indexed, I have cleared caches, I have re-deployed.

Override Prestashop Module Changes not Visible

I am attempting to override a module in Prestashop but the changes are just not appearing.
I have overridden a template file and a controller so I have added the following files:
\override\modules\blockwishlist\views\templates\front\mywishlist.tpl
\override\modules\blockwishlist\controllers\front\mywishlist.php
These are very simple changes where I add another column to a table that contains a button. When the button is clicked the controller generates a CSV file.
Any idea why these changes are just not being shown?
Note: I have turned on 'Force Compile' and turned of caching.
Edit:
Re overridding a controller is it:
class BlockWishListMyWishListModuleFrontController extends BlockWishListMyWishListModuleFrontControllerCore // extends ModuleFrontController
or
class BlockWishListMyWishListModuleFrontControllerOverride extends BlockWishListMyWishListModuleFrontController
okay, I did some code research (maybe thre is exists easiest way, not sure), so:
in code Dispatcher class we have
// Dispatch module controller for front office
case self::FC_MODULE :
$module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
$module = Module::getInstanceByName($module_name);
$controller_class = 'PageNotFoundController';
if (Validate::isLoadedObject($module) && $module->active) {
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$module_name.'/controllers/front/');
if (isset($controllers[strtolower($this->controller)])) {
include_once(_PS_MODULE_DIR_.$module_name.'/controllers/front/'.$this->controller.'.php');
$controller_class = $module_name.$this->controller.'ModuleFrontController';
}
}
$params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 1);
break;
where we see that controllers loaded without overrides, but from other side below in code we see hook execution:
// Loading controller
$controller = Controller::getController($controller_class);
// Execute hook dispatcher
if (isset($params_hook_action_dispatcher)) {
Hook::exec('actionDispatcher', $params_hook_action_dispatcher);
}
so one of possible solution (without overriding core class) :
how to override module and hope you have core version >= 1.6.0.11
in blockwishlist.php in install() method add
this->registerHook('actionDispatcher')
to condition with other hooks, so it will looks like ... !this->registerHook('actionDispatcher') || ... because this hook not registered by default and we can't just place module there.
create method (can't beautify code here)
public function hookActionDispatcher($params)
{
if ('blockwishlistmywishlistModuleFrontController' == $params['controller_class']) {
include_once(_PS_OVERRIDE_DIR_ . 'modules/' . $this->name . '/controllers/front/mywishlist.php');
$controller = Controller::getController('BlockWishListMyWishListModuleFrontControllerOverride');
}
}
you already have override/modules/blockwishlist/controllers/front/mywishlist.php file by this path
reinstall module.
it works!
more about overriding some behaviors in docs
Turns out that to override a module you dont place your files in:
~/overrides/module/MODULE_NAME
Instead you place it in:
~/themes/MY_THEME/modules/MODULE_NAME
Now the changes are exhibiting themselves.
Does anyone know if/when the module is auto-updated, will my changes get lost/overrwritten?

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