How do I get bundle option selection SKU? - magento

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
foreach ($order->getAllItems() as $item){
$productOptions = $item->getProductOptions();
echo $product_id = $item->product_id;
$_product=Mage::getModel('catalog/product')->load($product_id);
if ($_product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
if (isset($productOptions['bundle_options']))
{
foreach ($productOptions['bundle_options'] as $productOption)
{
echo $value = $productOption['value'][0]['title'];
echo ' || ';
echo $value = $productOption['value'][0]['qty'];
echo ' || ';
echo $value = $productOption['value'][0]['price'];
echo "<br>";
}
}
}
}
I am able to get the title, qty and the price of product, I also want to get the product SKU.

Bundle products can have options, options can have selections. This is 'two-tier' structure. If you just want to get all selections without options, you can use something like this:
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach($selections as $selection){
echo $selection->getSku();
}
But if you want get full information about options and their selections, use next way (based on your example):
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
$store_id = $order->getStoreId();
foreach ($order->getAllItems() as $item){
$product = Mage::getModel('catalog/product')->setStoreId($store_id)->load($item->product_id);
$options = Mage::getModel('bundle/option')->getResourceCollection()
->setProductIdFilter($item->product_id)
->setPositionOrder();
$options->joinValues($store_id);
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach ($options->getItems() as $option) {
$option_id = $option->getId();
echo 'Option: ' . $option->getTitle() . ' [id: ' . $option_id . ']<br />';
foreach($selections as $selection){
if($option_id == $selection->getOptionId()){
$selection_id = $selection->getId();
$selection_name = $selection->getName();
$selection_qty = $selection->getSelectionQty();
$selection_sku = $selection->getSku();
$selection_product_id = $selection->getProductId();
$selection_weight = $selection->getWeight();
$selection_price = $selection->getPrice();
$data = 'Selection Name: ' . $selection_name;
$data .= ', SKU: ' . $selection_sku;
$data .= ', Qty: ' . $selection_qty;
$data .= ', ID: ' . $selection_id;
$data .= ', Product ID: ' . $selection_product_id;
$data .= ', Weight: ' . $selection_weight;
$data .= ', Price: ' . $selection_price;
echo $data . '<br />';
}
}
}
}
?>

Here we go,
To get product sku by selected option id:
$optionId = "selected option id";
$bundleTable = Mage::getSingleton('core/resource')->getTableName('catalog_product_bundle_selection');
$collection=Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect(array('name', 'price'));
$collection->getSelect()->joinLeft(array('bundleselect'=> $bundleTable),"entity_id = bundleselect.product_id","product_id");
$collection->getSelect()->where(" bundleselect.selection_id IN (".$optionId.") " );
$origPrice = '0';
foreach($collection as $prod) {
$origPrice += $prod->getSku();
}
echo $origSku;

Magento 2 get bundle options with their selections details.
Class BundleItemDetails
public function __construct(
\Magento\Catalog\Model\ProductRepository; $productRepository
)
{
$this->productRepository = $productRepository;
}
public function execute(){
$product = $this->productRepository->get("test-bundle-product");
$optionsCollection = $product->getTypeInstance(true)
->getOptionsCollection($product);
$optionDetails = [];
foreach ($optionsCollection as $option){
$selections = $product->getTypeInstance(true)
->getSelectionsCollection(
$option->getOptionId(),$product
);
//selection details by optionids
foreach ($selections as $selection) {
$optionDetails[$option->getOptionId()] = $selection->getSku();
}
}
}
}

Related

magento configrable product collection 1500 with pagination but showing time out not loading

please visite my url and seee
https://staging.raptorsupplies.com/catalogsearch/result/?q=baldwin
you click on first product also you can see this product showing
enter image description here
if click on then it will be showing error like
and if click on other product then it open and working, because variation/collection list have less but it is in 1500 variation
i have create pagination for this request but i am still facing error
you can see my code where is error i think error in pagination but i am get it show please any one can help me
[enter image description here][2]
public function getConfigAttribOption($childProductList, $attribbid = NULL, $AllchildProductList = null) {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$storeId = Mage::app()->getStore()->getStoreId(); //die;
if ($attribbid > 0) {
$SqlAttributeID = "select distinct attribute_id from eav_attribute_option where option_id in($attribbid)";
$RowAttributeID = $this->executeQuery($SqlAttributeID);
foreach ($RowAttributeID as $arrKey => $Arrval) {
$arrAttributeId[] = $Arrval['attribute_id'];
}
$attributeids = implode(',', $arrAttributeId);
$sqlConfigurableAttribute = "select a.attribute_id as id,a.frontend_label as label,a.attribute_code as attribute_code,group_concat(distinct i.value) as option_id,GROUP_CONCAT(DISTINCT o.value SEPARATOR '&|&') as option_value from catalog_product_entity_int as i join eav_attribute as a on i.attribute_id=a.attribute_id JOIN eav_attribute_option_value AS o ON i.value=o.option_id where o.store_id=".$storeId." and (a.attribute_id in(81,92) OR a.attribute_id>20000) and entity_id in($childProductList) AND a.attribute_id NOT IN($attributeids) group by i.attribute_id having count(distinct i.value)>1";
$arrCount = 0;
mysql_query('SET SESSION group_concat_max_len=10000');
foreach ($arrAttributeId as $key => $val) {
if ($arrCount == count($attribbid) - 1) {
$sqlCheckedAttribute.=" union all SELECT a.attribute_id AS id,a.frontend_label AS label,a.attribute_code AS attribute_code,IF(COUNT(DISTINCT i.value)>1,GROUP_CONCAT(DISTINCT i.value),'') AS option_id,GROUP_CONCAT(DISTINCT o.value SEPARATOR '&|&') AS option_value FROM catalog_product_entity_int AS i JOIN eav_attribute AS a ON i.attribute_id=a.attribute_id JOIN eav_attribute_option_value AS o ON i.value=o.option_id WHERE o.store_id=".$storeId." and (a.attribute_id in(81,92) OR a.attribute_id>20000) AND entity_id in(" . $AllchildProductList . ") AND a.attribute_id=" . $val . " GROUP BY i.attribute_id ";
} else {
$sqlCheckedAttribute.=" union all SELECT a.attribute_id AS id,a.frontend_label AS label,a.attribute_code AS attribute_code,IF(COUNT(DISTINCT i.value)>1,GROUP_CONCAT(DISTINCT i.value),'') AS option_id,GROUP_CONCAT(DISTINCT o.value SEPARATOR '&|&') AS option_value FROM catalog_product_entity_int AS i JOIN eav_attribute AS a ON i.attribute_id=a.attribute_id JOIN eav_attribute_option_value AS o ON i.value=o.option_id WHERE o.store_id=".$storeId." and (a.attribute_id in(81,92) OR a.attribute_id>20000) AND entity_id in(" . $AllchildProductList . ") AND a.attribute_id=" . $val . " GROUP BY i.attribute_id ";
}
$arrCount = $arrCount + 1;
}
$sqlConfigurableAttribute = $sqlConfigurableAttribute . $sqlCheckedAttribute;
} else {
$sqlConfigurableAttribute = "select a.attribute_id as id,a.frontend_label as label,a.attribute_code as attribute_code,group_concat(distinct i.value) as option_id,GROUP_CONCAT(DISTINCT o.value SEPARATOR '&|&') as option_value from catalog_product_entity_int as i join eav_attribute as a on i.attribute_id=a.attribute_id JOIN eav_attribute_option_value AS o ON i.value=o.option_id where o.store_id=$storeId and (a.attribute_id in(81,92) OR a.attribute_id>20000) and entity_id in($childProductList) group by i.attribute_id having count(distinct i.value)>1";
}
$sqlConfigurableAttribute = $sqlConfigurableAttribute . " order by id"; //die;
$productAttributeOptions = $readConnection->fetchAll($sqlConfigurableAttribute);
return $productAttributeOptions;
}
public function executeQuery($query) {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
return $readConnection->fetchAll($query);
}
function getRelativeOptionBlock($productId = null, $attribbid = null, $pageno = null) {
$encrypted_string=$this->getRequest()->getParam('active_filters');
$decrypted_string=urldecode(base64_decode($encrypted_string));
if($decrypted_string){
$attribbid=$decrypted_string;
$productId= $this->getProduct()->getId();
}
if ($attribbid && $productId) {
//$childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($productId);
//$childProductList = implode(',', $childProducts[0]);
$AllchildProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($productId);
$AllchildProductList = implode(',', $AllchildProducts[0]);
$attribb = explode(',', $attribbid);
$query = 'SELECT eav_attribute.attribute_code FROM eav_attribute JOIN eav_attribute_option ON eav_attribute.attribute_id=eav_attribute_option.attribute_id WHERE option_id IN(' . $attribbid . ')';
$results = $this->executeQuery($query);
$attribvalue = $results['0']['attribute_code'];
$product = Mage::getModel('catalog/product')->load($productId);
$childProductsColl = Mage::getModel('catalog/product_type_configurable')
->getUsedProductCollection($product)
->addAttributeToSelect('*');
foreach ($results as $res) {
$childProducts = $childProductsColl->addFieldToFilter($res['attribute_code'], $attribb);
}
$childProductList = array();
foreach ($childProducts as $cp2) {
$childProductList[] = $cp2->getId();
}
$childProductList = implode(',', $childProductList);
} elseif ($productId) {
$childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($productId);
$childProductList = implode(',', $childProducts[0]);
} else {
$childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($this->getProduct()->getId());
$childProductList = implode(',', $childProducts[0]);
}
$attributeOptions = array();
$productAttributeTh = array();
$productAttributeId = array();
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$querytemp="SET group_concat_max_len=100000";
$writeConnection->query($querytemp);
$productAttributeOptions = $this->getConfigAttribOption($childProductList, $attribbid, $AllchildProductList);
Mage::getSingleton('core/session')->setOptionlength(count($productAttributeOptions));
$html = "";
$html .= "<div class='box-container list' style='margin-left: 40px;'>";
foreach ($productAttributeOptions as $productAttribute) {
$productAttributeTh[] = $productAttribute['label'];
$productAttributeThId[] = $productAttribute['id'];
$productAttributeThCode[] = $productAttribute['attribute_code'];
$productAttributeId = array();
$productAttributeVal = array();
$productAttributeId = explode(',', $productAttribute['option_id']);
$productAttributeVal = explode('&|&', $productAttribute['option_value']);
if((int)$productAttribute['id'] == 81)
{
$this->brandcount = count($productAttributeVal);
}
if((int)$productAttribute['id'] == 81 && count($productAttributeVal) ==1)
continue;
$attribute_to= count($productAttributeId);
$attribute_option=array();
for($i=0;$i<$attribute_to;$i++){
$attribute_option[$productAttributeId[$i]]=$productAttributeVal[$i];
}
asort($attribute_option);
$label =$productAttribute['label'];
$html .= "<div class='inner-box-container list-content'>";
$html .= "<p class='new_align' title='".ucwords($productAttribute['label'])."'>" .ucwords($label) . "</p>";
///$productAttributeLbel = $productAttribute['label'];
$productAttributeLbel = preg_replace('/[^A-Za-z0-9\-]/', '', $productAttribute['label']);
$html .= "<script> multiselected('" . str_replace(' ', '', $productAttributeLbel) . "')</script>";
$html .= "<select class='" . str_replace(' ', '', $productAttributeLbel) . "'>";
//echo"<select >";
foreach ($attribute_option as $OptionKey => $OptionVal) {
if((int)$productAttribute['id'] == 81 && count($attribute_option) ==1)
continue;
$attridarray = explode(',', $attribbid);
if (in_array($OptionKey, $attridarray)) {
//echo $attribbid.$OptionVal; die;
$html .= "<option value='" . $OptionKey . "' title='title'>". $OptionVal . "</option>";
} else {
$html .= "<option value='" . $OptionKey ."' >" . $OptionVal . "</option>";
}
}
$html .= "</select>";
$html .= "</div>";
}
Mage::getSingleton('core/session')->setAttributeIds($productAttributeThId);
$html .= "</div><br class='clearBoth' />";
return $html;
}
function getRelativeHeaderBlock($productId = null, $attribbid = null) {
$encrypted_string=$this->getRequest()->getParam('active_filters');
$decrypted_string=urldecode(base64_decode($encrypted_string));
if($decrypted_string){
$attribbid=$decrypted_string;
$productId= $this->getProduct()->getId();
}
if ($productId) {
$childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($productId);
} else {
$childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($this->getProduct()->getId());
}
$childProductList = implode(',', $childProducts[0]);
$productAttributeTh = array();
$attribidvalue= array();
if ($attribbid) {
$attribb = explode(',', $attribbid);
$query = 'SELECT * FROM eav_attribute_option where option_id in(' . $attribbid . ')';
$results = $this->executeQuery($query);
foreach($results as $key=>$val){
$attribidvalue[]=$val['attribute_id'];
}
//$attribidvalue = $results['0']['attribute_id'];
}
$productAttributeOptions = $this->getConfigAttribOption($childProductList);
foreach ($productAttributeOptions as $productAttribute) {
$productAttributeTh[$productAttribute['id']] = $productAttribute['label'];
}
$Productdetail = Mage::getModel('catalog/product')->load($productId);
?>

Magento export categories -> import with magmi

we need to change the categories of some products and it is easier for us to do this with a csv file.
Is there a way to export the categories in magmi format?
sku,categories
"abc","cat1/cat2;;cat5/cat6/cat1"
"bgb","cat1/cat2"
or is there maybe a small tool to manage the products in categories?
Edit:
this is the current code which is displaying the category names.
But I am trying to display the category path like this:
FirstCat/Tools/Screwdriver
But it is displaying like this:
FirstCat/Screwdriver/Tools
so the categoryid is not sorted.
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
$fp = fopen('exports.csv', 'w');
$csvHeader = array("sku", "category_ids");
fputcsv( $fp, $csvHeader,",");
foreach ($products as $product){
$sku = $product->getSku();
$i = 2;
$len = count($product->getCategoryIds());
$str = "";
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$name = $category->getName();
$str .= $name;
if($i <= $len) {
$str = $str .= "/";
}
$i++;
}
fputcsv($fp, array($sku, $str), ",");
}
fclose($fp);
I use this code to export out categories. You can try to run it, don't forget to modify your path to your mage/app.php:
<?php
require_once('../yourpath/app/Mage.php');
Mage::app('admin');
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::register("isSecureArea", true);
function saveData($file, $data) {
$fh = fopen($file, 'w');
foreach ($data as $dataRow) {
fputcsva($fh, $dataRow);
}
fclose($fh);
return $this;
}
function fputcsva(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
$str = '';
$escape_char = '\\';
foreach ($fields as $value) {
if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i = 0; $i < $len; $i++) {
if ($value[$i] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2 . $delimiter;
} else {
if (strlen($value)):
$str .= $enclosure . $value . $enclosure . $delimiter;
else:
$str .= $value . $delimiter;
endif;
}
}
$str = substr($str, 0, -1);
$str .= "\n";
return fwrite($handle, $str);
}
function geturl($connect, $value){
$id= $value;
if ($id) {
$sql = "SELECT value FROM magento.catalog_category_entity_url_key where entity_id=$id;";
$result = $connect->query($sql)->fetchObject();
} else {
return "";
}
return $result->value;
}
$modifiedarray = array();
$configpricearray=array();
$coreResource = Mage::getSingleton('core/resource');
$connect = $coreResource->getConnection('core_write');
$sql = "SELECT entity_id FROM catalog_category_entity;";
$category_row = $connect->query($sql);
$i=1;
$problematiccats=array(394,395,397,398);
$problematiccolumn=array('path','parent_id','level', 'position');
while ($row = $category_row->fetch()) {
$catid=$row['entity_id'];
echo "Category id: ".$catid.PHP_EOL;
if (in_array($catid,$problematiccats)): continue; endif;
$catsql="SELECT
ce.entity_id,
ce.parent_id,
ce.path,
ce.level,
ce.position,
ce.children_count,
ea.attribute_id,
ea.attribute_code,
CASE ea.backend_type
WHEN 'varchar' THEN ce_varchar.value
WHEN 'int' THEN IFNULL (eav_option.value,ce_int.value)
WHEN 'text' THEN ce_text.value
WHEN 'decimal' THEN ce_decimal.value
WHEN 'datetime' THEN ce_datetime.value
ELSE ea.backend_type
END AS value,
ea.is_required AS required
FROM catalog_category_entity AS ce
LEFT JOIN eav_attribute AS ea
ON ce.entity_type_id = ea.entity_type_id
LEFT JOIN catalog_category_entity_varchar AS ce_varchar
ON ce.entity_id = ce_varchar.entity_id
AND ea.attribute_id = ce_varchar.attribute_id
AND ea.backend_type = 'varchar'
AND ce_varchar.store_id = 0
LEFT JOIN catalog_category_entity_int AS ce_int
ON ce.entity_id = ce_int.entity_id
AND ea.attribute_id = ce_int.attribute_id
AND ea.backend_type = 'int'
AND ce_int.store_id = 0
LEFT JOIN catalog_category_entity_text AS ce_text
ON ce.entity_id = ce_text.entity_id
AND ea.attribute_id = ce_text.attribute_id
AND ea.backend_type = 'text'
AND ce_text.store_id = 0
LEFT JOIN catalog_category_entity_decimal AS ce_decimal
ON ce.entity_id = ce_decimal.entity_id
AND ea.attribute_id = ce_decimal.attribute_id
AND ea.backend_type = 'decimal'
AND ce_decimal.store_id = 0
LEFT JOIN catalog_category_entity_datetime AS ce_datetime
ON ce.entity_id = ce_datetime.entity_id
AND ea.attribute_id = ce_datetime.attribute_id
AND ea.backend_type = 'datetime'
LEFT JOIN eav_attribute_option_value as eav_option
ON eav_option.option_id=ce_int.value
AND eav_option.store_id=0
WHERE ce.entity_id = '$catid';";
$category_info = $connect->query($catsql);
$csvrow=array();
if ($i==1): $csvrow['entity']='entity_id';$csvrow['parent']='parent_id'; $csvrow['path']='path';
$csvrow['level']='level';
$csvrow['position']='position';
$csvrow['children_count']='children_count';endif;
while ($catrow = $category_info->fetch()) {
if (in_array($catrow['attribute_code'],$problematiccolumn)): continue; endif;
if ($i==1):
$csvrow[]=$catrow['attribute_code'];
else:
$csvrow['entity']=$catrow['entity_id'];
$csvrow['parent']=$catrow['parent_id'];
$csvrow['path']=$catrow['path'];
$csvrow['level']=$catrow['level'];
$csvrow['position']=$catrow['position'];
$csvrow['children_count']=$catrow['children_count'];
$csvrow[$catrow['attribute_code']]=($catrow['value']?$catrow['value']:"");
if ($catrow['attribute_code']=="url_key"):
if (strlen($catrow['url_key'])<3):
$csvrow['url_key']=geturl($connect,$catid);
endif;
endif;
endif;
}
$csv[]=$csvrow;
$i++;
}
$file_path = 'categoryexport.csv';
try {
saveData($file_path, $csv);
} catch (Exception $e) {
echo "[ERROR] Creating sale report file: " . $e->getMessage() . PHP_EOL;
}
In this solution the db was'n in very well state, so the url needs to grabbed separately, you can remove that part if not necessary for you.
I used this on EE 1.13.0.2
You can run it from the shell.
Now here is my solution. Its displaying the csv in the browser. After that you can reimport with magmi
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
foreach ($products as $product){
$sku = $product->getSku();
echo $sku.",";
$i = 2;
$anzahl = count($product->getCategoryIds());
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$path = $category->getPath();
$ids = explode("/", $path);
$name = "";
$i2 = 2;
$anzahl2 = count($ids);
foreach($ids as $id_2) {
$category = Mage::getModel('catalog/category')->load($id_2);
$name .= $category->getName();
echo $category->getName();
if($i2 <= $anzahl2) {
$name .= "/";
echo "/";
}
$i2++;
}
if($i <= $anzahl) {
$name .= ";;";
echo ";;";
}
$i++;
}
echo "<br />";
}

Like Query Is Not Working properly

In Code igniter Model I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
public function fetchdeal_products($id) {
$this->db->select('*');
$this->db->from('products');
$q = $this->db->like("name", $id);
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
//Controller
function ajaxdealcategorydata($id = NULL) {
$this->sma->checkPermissions('index');
$id = $this->input->get('id');
$subcategories = $this->pos_model->getdealcategory($id);
$scats = '';
foreach ($subcategories as $category) {
$scats .= "<button id=\"subcategory-" . $category->id . "\" type=\"button\" value='" . $category->id . "' class=\"btn-prni subcategory\" ><img src=\"assets/uploads/thumbs/" . ($category->image ? $category->image : 'no_image.png') . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded img-thumbnail' /><span>" . $category->name . "</span></button>";
}
$products = $this->ajaxdealproducts($id);
if (!($tcp = $this->pos_model->products_count($id))) {
$tcp = 0;
}
echo json_encode(array('products' => $products, 'subcategories' => $scats, 'tcp' => $tcp));
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
function ajaxdealproducts() {
$this->sma->checkPermissions('index');
if ($this->input->get('id') ) {
$id = $this->input->get('id');
} else {
$category_id = $this->pos_settings->default_category;
}
if ($this->input->get('subcategory_id')) {
$subcategory_id = $this->input->get('subcategory_id');
} else {
$subcategory_id = NULL;
}
if ($this->input->get('per_page') == 'n') {
$page = 0;
} else {
$page = $this->input->get('per_page');
}
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url() . "pos/ajaxdealproducts";
$config["total_rows"] = $subcategory_id ? $this->pos_model- >products_count($id, $subcategory_id) : $this->pos_model->products_count($id);
$config["per_page"] = $this->pos_settings->pro_limit;
$config['prev_link'] = FALSE;
$config['next_link'] = FALSE;
$config['display_pages'] = FALSE;
$config['first_link'] = FALSE;
$config['last_link'] = FALSE;
$this->pagination->initialize($config);
$products = $this->pos_model->fetchdeal_products($id, $config["per_page"], $page);
$pro = 1;
$prods = '<div>';
foreach ($products as $product) {
$count = $product->id;
if ($count < 10) {
$count = "0" . ($count / 100) * 100;
}
if ($category_id < 10) {
$category_id = "0" . ($category_id / 100) * 100;
}
$prods .= "<button id=\"product-" . $category_id . $count . "\" type=\"button\" value='" . $product->code . "' title=\"" . $product->name . "\" class=\"btn-prni btn-" . $this->pos_settings->product_button_color . " product pos-tip\" data-container=\"body\"><img src=\"" . base_url() . "assets/uploads/thumbs/" . $product->image . "\" alt=\"" . $product->name . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded' /><span>" . character_limiter($product->name, 15) . "</span></button>";
$pro++;
}
$prods .= "</div>";
if ($this->input->get('per_page')) {
echo $prods;
} else {
return $prods;
}
}
The database LIKE function only creates a LIKE in the SQL statement. You'll still need to call the GET mothod afterwards; Like this;
$this->db->like('name', $id);
$q = $this->db->get();
You are using $this->db_like() incorrectly.
$this->db->like('title', 'match');
// Produces: WHERE title LIKE '%match%'
(from documentation)
In your case the usage would be
$this->db->like('name', 'rice')
More info
public function fetchdeal_products($id)
{
$query = $this->db->query("Select products.* From products Where (products.name Like '%$id%')");
$result = $query->result_array();
return $result;
}
you have to write it as bellow.
public function fetchdeal_products($id) {
$this->db->like("name", $id);
$q = $this->db->get('products');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}

Magento Issues with category dropdown

I need to display all the subcategories under root category name using . I am unable to find the root category details. Root category name is displaying as '/' How to overcome this issue?
Currently i am getting all the categories including root categories (/).
My code is as in below:
public function toOptionArray()
{
$categories = array();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter(
'path',
array('neq' => '1')
);
foreach ($categoryCollection as $category) {
var_dump($category->getData());
echo '<br />';
$category = Mage::getModel('catalog/category')->load($category->getId());
$categories[$category->getId()] = $category->getUrlPath();
}
return $categories;
}
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($categories as $id => $name) {
$html .= sprintf(
'<option value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
$html .= '</select>';
return $html;
}
I need to add into the category dropdown, which is subcategories displaying under root category name.
Can anyone help me please.
Thank You.
I fixed the issue using following:
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$parentIdArray = array();
foreach ($categories as $id => $name) {
$category = Mage::getModel('catalog/category')->load($id);
$parentId = $category->getParentId();
if($parentId == 1){
$parentIdArray[] = $id;
}
}
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($parentIdArray as $parentId) {
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$name = $parentCategory->getName();
$html .= sprintf(
'<optgroup label="'.$name.'">
<option value="%s"%s>%s</option>
</optgroup>',
$this->escapeHtml($parentId),
$parentId == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
$categories = Mage::getModel('catalog/category')->getCategories($parentId);
$subCategories = $this->get_categories($categories);
foreach ($subCategories as $id => $name) {
$html .= sprintf(
'<option style="padding-left: 10px;" value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
}
$html .= '</select>';
return $html;
}
public function get_categories($categories) {
$subCategories = array();
foreach($categories as $category) {
$subCategory = Mage::getModel('catalog/category')->load($category->getId());
$subCategories[$subCategory->getId()] = $subCategory->getUrlPath();
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$childrenCategories = $this->get_categories($children);
foreach ($childrenCategories as $id => $name) {
$subCategories[$id] = $name;
}
}
}
return $subCategories;
}

How to list products in Magento Menu

Like this question:
Magento: HOW-TO add active products in a drop-down in Main Navigation Menu
...I want to list the products from a category in the main menu. I have attempted to use the code provided but it's still not working. I'm using Magento ver. 1.7.0.2 so I think this may be the issue.
Any help would be appreciated.
I had the same problem and after some hours I have a solution now. I'm using Magento 1.9.1 and I also needed to edit the Topmenu.php file. Probably it's not the best way to do it, but it works. I tried to comment everything, so maybe it's easier to understand.
I changed '_getHtml' function to include the products and to change classes of 'li'-tags, if necessary:
protected function _getHtml(Varien_Data_Tree_Node $menuTree, $childrenWrapClass, $correctClasses = 0)
{
$html = '';
$children = $menuTree->getChildren();
$parentLevel = $menuTree->getLevel();
$childLevel = is_null($parentLevel) ? 0 : $parentLevel + 1;
$counter = 1;
$childrenCount = $children->count();
$parentPositionClass = $menuTree->getPositionClass();
$itemPositionClassPrefix = $parentPositionClass ? $parentPositionClass . '-' : 'nav-';
foreach ($children as $child) {
$child->setLevel($childLevel);
$child->setIsFirst($counter == 1);
$child->setIsLast($counter == $childrenCount);
$child->setPositionClass($itemPositionClassPrefix . $counter);
$outermostClassCode = '';
$outermostClass = $menuTree->getOutermostClass();
if ($childLevel == 0 && $outermostClass) {
$outermostClassCode = ' class="' . $outermostClass . '" ';
$child->setClass($outermostClass);
}
// avoid 'last'-class if there are products after categories
$renderedAttributes = $this->_getRenderedMenuItemAttributes($child);
if($correctClasses = 1) {
$renderedAttributes = str_replace(' last', '', $renderedAttributes);
}
// add 'category' class to category elements
$renderedAttributes = str_replace('class="', 'class="type-category ', $renderedAttributes);
$html .= '<li ' . $renderedAttributes . '>';
$html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>' . $this->escapeHtml($child->getName()) . '</span></a>';
// check if there are more categories or products inside
$hasProducts = $this->hasProducts($child);
if ($child->hasChildren() || $hasProducts) {
if (!empty($childrenWrapClass)) {
$html .= '<div class="' . $childrenWrapClass . '">';
}
// build ul-wrapper
$html .= '<ul class="level' . $childLevel . '">';
// if categories and products are in this category
if($child->hasChildren() && $hasProducts) {
$correctClasses = 1;
$html .= $this->_getHtml($child, $childrenWrapClass, $correctClasses);
$html .= $this->getProducts($child, $childLevel, $correctClasses);
// if only categories are in this category
} elseif($child->hasChildren()) {
$html .= $this->_getHtml($child, $childrenWrapClass);
// if only products are in this category
} elseif($hasProducts) {
$html .= $this->getProducts($child, $childLevel);
}
$html .= '</ul>';
if (!empty($childrenWrapClass)) {
$html .= '</div>';
}
}
$html .= '</li>';
$counter++;
}
return $html;
}
Additionally I wrote 3 new functions to process everything.
One new small function to get the product collection from current category:
// get product collection
protected function getProductCollection($child) {
// get current category
$catId = str_replace('category-node-', '', $child->getId());
$curCategory = Mage::getModel('catalog/category')->load($catId);
// get prouct collection from current category
return Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($curCategory)->setOrder('position','ASC');
}
A function to check if there are any products in current category:
// check if there are products in this category
protected function hasProducts($child) {
// get number of products in current (sub-)category
$productCount = $this->getProductCollection($child)->count();
if($productCount > 0) {
return 1;
} else {
return 0;
}
}
And one function to build the html for the product list items:
// get product html
protected function getProducts($child, $level, $correctClasses = 0) {
$productCollection = $this->getProductCollection($child);
// set product counter
$p = 1;
// get number of products in current (sub-)category
$productCount = $productCollection->count();
$pChild = '';
if ($productCount > 0) {
$level++;
foreach ($productCollection as $product) {
// get current product in loop
$curProduct = Mage::getModel('catalog/product')->load($product->getId());
// check if current product in loop is activated
if ($curProduct->getStatus()) {
// build list-item with classes
$pChild .= '<li';
$pChild .= ' class="type-product level'.$level;
if ($p == 1 && $correctClasses == 0) {
$pChild .= ' first';
}
if ($p == $productCount) {
$pChild .= ' last';
}
$pChild .= '">'."\n";
$pChild .= ' '.$this->htmlEscape($curProduct->getName()).''."\n";
$pChild .= '</li>';
// increment product counter
$p++;
}
}
}
return $pChild;
}
Hopefully it helps someone! If someone has suggestions to write it more clean or to add some functionality, post something or comment it! :)

Resources