Magento2 get product images externally - quotes

I have a external script i use to fetch the current quote products (as external cart for example) This works perfect.
In this code i use the following:
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote();
$helper = $obj->get('\Magento\Checkout\Helper\Cart');
$quote = $helper->getQuote();
$quoteitems = $quote->getAllItems();
$cart= $helper->getCart();
foreach ($quoteitems as $item)
{
$_imagehelper = $obj->get('\Magento\Catalog\Helper\Image');
$product = $item->getProduct();
$img = $_imagehelper->init($product,'category_page_list',array('height' => '100' , 'width'=> '100'))->getUrl();
}
This results in: /pub/static/frontend/_view/nl_NL/Magento_Catalog/images/product/placeholder/.jpg
While in a layout block i use the following and that works perfect:
$helper = $this->helper('\Magento\Checkout\Helper\Cart');
$quote = $helper->getQuote();
$quoteitems = $quote->getAllItems();
$cart= $helper->getCart();
foreach ($quoteitems as $item)
{
$_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
$product = $item->getProduct();
$img = $_imagehelper->init($product,'category_page_list',array('height' => '100' , 'width'=> '100'))->getUrl();
}
Im out of ideas.

use the following code
// your product's id here
$pid = 7;
// set image width and height
$imagewidth = 500;
$imageheight = 500;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($pid);
$imageHelper = $objectManager->get('\Magento\Catalog\Helper\Image');
$image_url = $imageHelper->init($_product, 'product_page_image_small')->setImageFile($_product->getFile())->resize($imagewidth, $imageheight)->getUrl();

Use below code to get product image externally
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$pid=1;
$_product = $objectManager->create('\Magento\Catalog\Model\Product')->load($pid);
$data=$_product->getData();
echo $imageurl=$_product->getImage();
//print_r($data);
?>
<img src="<?php echo $mediaurl.'catalog/product'.$imageurl;?>">

Related

function str_slug is deprecated and not working, what should i do?

I was trying to use Str_slug but it is not working in laravel 5.8.
I am using PhpStorm latest version.
$product->slug = Str_slug('$request->title');
Check the image for more
public function ProductStore(StoreValidation $request){
$product = new product();
$product->category_id = 1;
$product->brand_id = 1;
$product->title = $request->title;
$product->desc = $request->desc;
$product->slug = Str_slug('$request->title');
$product->quantity = $request->quantity;
$product->price = $request->price;
$product->offer_price = $request->offer;
$product->status = 1;
$product->admin_id = 1;
// Saving Product information into product table
$product->save();
if ($request->hasFile('uploadFile')){
$image = $request->file('uploadFile');
$img = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('image/product/' .$img);
$img_ins = Image::make($image)->resize(220,294);
$img_ins->save($location);
$product_img = new product_image();
$product_img->product_id = $product->id;
$product_img->image_name = $img;
$product_img->save();
}
return redirect()->route('admin_panel.pages.admin-addProduct');
}
You should use Str::slug() (Illuminate\Support\Str) instead of deprecated str_slug().
https://laravel.com/docs/5.8/helpers#method-str-slug

Magento products from attribute

I have the following code, which will get all products from all orders for one logged in customer which works fine. I want to add to this code so that it only returns products from a specified attribute set. I believe I have both bits of code that I need they just won't work together.
Code I want to add to is:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
echo various variables here;
}
}
}
?>
Code I have used before to get products from a specified attribute set
$attrSetName = 'Beer';
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->load($attrSetName, 'attribute_set_name')
->getAttributeSetId();
//Load product model collecttion filtered by attribute set id
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('name')
->addFieldToFilter('attribute_set_id', $attributeSetId);
You can add this piece of code to make your script work in the foreach loop.
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();
if(0 == strcmp($attributeSetName, 'Beer') {
//add your logic
}else{
continue;
}
Update:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection =
Mage::getModel('sales/order')->getCollection();
$collection->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
$item->getProduct()->getSku();
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($item->getProduct()->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();
if(0 == strcmp($attributeSetName, 'Beer')) {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
// echo various variables here;
}else{
continue;
}
}
}
}
print_r($uniuqProductSkus);
?>

add bundle products items qty to cart programatically Magento

HI i need to add a bundle product with its items qty to cart programaticaaly. For this i am using the below code
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = $this->getRequest()->getParams();
$productId = 3801 ;//3857;
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId);
if($product->getTypeId() == "bundle"){
$bundled_items = array();
$optionCollection = $product->getTypeInstance()->getOptionsCollection();
$selectionCollection = $product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance()->getOptionsIds());
$options = $optionCollection->appendSelections($selectionCollection);
$childsku = array('testing','staging');
foreach($options as $option) {
$_selections = $option->getSelections();
foreach($_selections as $selection) {
//print_r($selection);
$bundled_items[$option->getOptionId()][] = $selection->getSelectionId();
$bundled_qty[$selection->getSelectionId()][] = 2;
}
}
print_r($bundled_items);
print_r($bundled_qty);
$params = array('bundle_option' => $bundled_items,
'bundle_option_qty'=>$bundled_qty,
'qty' => 1,'product'=>$productId);
}
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$cart->addProduct($product, $params);
$cart->save();
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
this code add the product to cart properly with all its items i
need to sprcify the each option qty
but it sets all options qty to 1
.
can you please suggest me where i am doing the mistake or what i should try.
thanks
ok i have fix the issue by doing some changes in the script
$cart = Mage::getModel('checkout/cart');
$cart->init();
$bundled_items = array();
$optionCollection = $_product->getTypeInstance()->getOptionsCollection();
$selectionCollection = $_product->getTypeInstance()->getSelectionsCollection($_product->getTypeInstance()->getOptionsIds());
$options = $optionCollection->appendSelections($selectionCollection);
foreach($options as $option) {
$_selections = $option->getSelections();
foreach($_selections as $selection) {
foreach($cusarray as $cusarraykey=> $cusarrayvalue) {
if($selection->getSku()== $cusarrayvalue){
print_r($selection->getSku());
echo $selection->getSku()."<br/>";
$bundled_items[$option->getOptionId()][] = $selection->getSelectionId();
$bundled_qty[$option->getOptionId()] = $cusqtyarray[$cusarraykey];
}
}
}
}
$params = array('bundle_option' => $bundled_items,
'bundle_option_qty' => $bundled_qty,
'qty' => $proqty,'product'=>$_productId);
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$_product = new Mage_Catalog_Model_Product();
$_product->load($_productId);
$cart->addProduct($_product, $params);
$cart->save();
thanks
"$bundled_qty[$option->getOptionId()] = $cusqtyarray[$cusarraykey];"
is this how you fixed.

Return products if Category is not Active

How can I make $cat->getProductCollection(); to return products if the category is NOT ACTIVE
It's been a very long time. I could not make this to work.
This is what I am doing. But no Luck
private function _getCollection() {
$category = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('is_active',array('eq'=>False))
->addAttributeToFilter('entity_id',array('eq'=>'61'))
->load();
foreach($category as $cat){
$Prods = $cat->getProductCollection();
$Prods->addWebsiteFilter();
$Prods->addAttributeToSelect('*');
}
return $Prods;
}
Try this code
$cat = Mage::getModel('catalog/category')->getCollection()->addAttributeToFilter('is_active', 1);
foreach ($cat as $category){
$cat_id = $category->getId();
$category = new Mage_Catalog_Model_Category();
$category->load($cat_id);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $_product) {
echo $_product->getName();
}
}

code igniter pagination for displaying specific data from database?

I want to display some specific data from database through pagination using CI.but pagination by default passess parameter in function which creates problem for me.
Here is my Controller
function page($catagoryid){
$this->load->library('pagination');
$config['base_url'] = base_url().'index.php/pagination/page/';
$count = $this->db->query("select * from tbl_products where category_id='$categoryid'");
$total=$count->num_rows();
$per_page = 4;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->model("mpagination");
$data['list'] = $this->mpagination->get_s(,$categoryid,$config['per_page'],$this->uri->segment(3));
if ($data['list']!== null){
$this->load->view('pagination_view', $data);
}
else {
$this->load->view('noresult');
}
}
Here is my Model
function get_s($categoryid,$num, $offset) {
$this->db->select ('*');
->where('category_id',$categoryid); // field name
$sql = $this->db->get('tbl_products',$num, $offset); // table name
if ($sql->num_rows () >0) {
return $sql->result();
}
else {
return null;
}
}
Here is my view
<?php
foreach($list as $row):?>
<?php echo $row->_prduct_id." ".$row->name." ".$row->description;?>
<br/>
<?php endforeach;?>
<br/>
<?php echo $pagination; ?>
This code work at first but when i clicked on second link of pagination it will not work because by default pagination sends its value to url as parameter and doesnot show data.
what can i do?
I didn't understand your code properly but this is the way you need to do pagination.
public function page($category_id)
{
$result = $this->model_file->model_function($category_id);
$start_index = 0;
$total_rows = count($result);
$items_per_page = 10;
$filtered = array_splice($result,$start_index,$items_per_page);
$model['data'] = $filtered;
$model['page_link'] = create_page_links (base_url()."/controller_file_name/page", $items_per_page, $total_rows);
$this->load->view('view_file_name_path',$model);
}
function create_page_links($base_url, $per_page, $total_rows) {
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
Try like this
public function index($offset = 0)
{
$language_id = 1;
$this->load->library('pagination');
$limit = 10;
$total = $this->legend_model->get_legend_count($language_id);
$config['base_url'] = base_url().'legend/index/';
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['first_link'] = '<< First';
$config['last_link'] = 'Last >>';
$config['next_link'] = 'Next ' . '>';
$config['prev_link'] = '<' . ' Previous';
$config['num_tag_open'] = '<span class="number">';
$config['num_tag_close'] = '</span>';
$config['cur_tag_open'] = '<span class="current"><a href="#">';
$config['cur_tag_close'] = '</a></span>';
$this->pagination->initialize($config);
$data['offset'] = $offset;
$data['legends'] = $this->legend_model->get_legend($language_id, $limit, $offset);
$this->template->write('title', 'Legend : Manage Legend');
$this->template->write_view('content', 'legend/index', $data);
$this->template->render();
}

Resources