Magento export categories -> import with magmi - magento

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 />";
}

Related

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

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);
?>

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;
}
}

How do I get bundle option selection SKU?

<?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();
}
}
}
}

How to write Some Data in CSV file in Magento?

I am trying print some shipment details as a CSV file and I am almost done in implementing this but it does not gives the the option for downloading.It automatically create the file and save it in the directory mentioned.
I think I am missing _prepareDownloadResponse() function but how do I implement this.
I am using this code ->
$file_path = 'sample_shipment.csv';
$mage_csv = new Varien_File_Csv();
$mage_csv->saveData($file_path, $content);
Edit:
All this code is in my indexcontroller.php
full code in indexcontroller.php ->
class Company_Manifestupload_IndexController extends Mage_Adminhtml_Controller_Action
{
public function indexAction() {
echo 'Manifestupload Index!';
}
public function bluedartmanifestuploadAction() {
$request = $this->getRequest();
$shipmentIds = $request->getPost('shipment_ids', array());
$file_path = 'manifest_upload_'.Mage::getSingleton('core/date')->date('d-m-Y_H-i-s').'_csv.csv';
$mage_csv = new Varien_File_Csv();
$shipment_csv=array();
/* Putting data in $shipment_csv[] */
$mage_csv->saveData($file_path, $shipment_csv);
}
In order to make the csv file downloadable, just put the following code inside the related controller action:
$fileName = 'filename.csv';
$content = $csvData; //prepare the csv data and return as string
$this->_prepareDownloadResponse($fileName, $content); //this will make the csv file downloadable with the $content as contents in it.
Hope this helps.
Edit:
Please find the updated controller action code.
public function bluedartmanifestuploadAction() {
$request = $this->getRequest();
$shipmentIds = $request->getPost('shipment_ids', array());
$fileName = 'manifest_upload_'.Mage::getSingleton('core/date')->date('d-m-Y_H-i-s').'_csv.csv';
//prepare csv contents
#prepare header
$csv = '';
$_columns = array(
"field1",
"field2",
//...
);
$data = array();
foreach ($_columns as $column) {
$data[] = '"'.$column.'"';
}
$csv .= implode(',', $data)."\n";
#prepare data
foreach($dataFromShipmentIds as $_data){ //just dummy loop
$data = array();
$data[] = $_data['field1'];
$data[] = $_data['field2'];
//...
$csv .= implode(',', $data)."\n";
}
//now $csv varaible has csv data as string
$this->_prepareDownloadResponse($fileName, $csv);
}
Edit 2: The above code will only work properly in ideal case.It will not generate proper Csv when there "\n"s and ","s in the fields .To make it work properly one can use code from varien file CSV .I'll add it here-
First make array of values in $data[] as above then instead of using $csv.=implode(',',$data)."\n" use the below code.
foreach ($data 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 {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
$str = substr($str,0,-1);
$str .= "\n";
If you want to create downloadable csv of you ordered item's you can use following script.
$orders = Mage::getModel("sales/order")->getCollection();
// prepare CSV header
$csv = '';
$_columns = array(
"Order Id",
"Product Name",
"Sku",
"Price"
);
$data = array();
// prepare CSV header...
foreach ($_columns as $column) {
$data[] = '"'.$column.'"';
}
$csv .= implode(',', $data)."\n";
foreach ($orders as $order) {
$items = $order->getAllItems();
foreach ($items as $item) {
$loadProduct = Mage::getModel('catalog/product')->load($item->getProductId());
//prepare csv contents
$data = array();
$data[] = $order->getId();
$data[] = $loadProduct['name'];
$data[] = $loadProduct['sku'];
$data[] = $loadProduct['price'];
$csv .= implode(',', $data)."\n";
//now $csv varaible has csv data as string
}
}
$this->_redirect('*/*/');
$this->_prepareDownloadResponse('file.csv', $csv, 'text/csv');
For more info visit here

Resources