Saturday 23 April 2016

Magento adding existing attribute to all attribute sets

<?php
require_once "app/Mage.php";
Mage::app();
$attSet = Mage::getModel('eav/entity_type')->getCollection()->addFieldToFilter('entity_type_code','catalog_product')->getFirstItem(); // This is because the you adding the attribute to catalog_products entity ( there is different entities in magento ex : catalog_category, order,invoice... etc )
    $attSetCollection = Mage::getModel('eav/entity_type')->load($attSet->getId())->getAttributeSetCollection(); // this is the attribute sets associated with this entity
    $attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
        ->setCodeFilter('attribute_code') //insert your attribute code here
        ->getFirstItem();
    $attCode = $attributeInfo->getAttributeCode();
    $attId = $attributeInfo->getId();
    foreach ($attSetCollection as $a)
    {
        $set = Mage::getModel('eav/entity_attribute_set')->load($a->getId());
        $setId = $set->getId();
        $group = Mage::getModel('eav/entity_attribute_group')->getCollection()->addFieldToFilter('attribute_set_id',$setId)->setOrder('attribute_group_id',"ASC")->getFirstItem();
        $groupId = $group->getId();
        $newItem = Mage::getModel('eav/entity_attribute');
        $newItem->setEntityTypeId($attSet->getId()) // catalog_product eav_entity_type id ( usually 10 )
                  ->setAttributeSetId($setId) // Attribute Set ID
                  ->setAttributeGroupId($groupId) // Attribute Group ID ( usually general or whatever based on the query i automate to get the first attribute group in each attribute set )
                  ->setAttributeId($attId) // Attribute ID that need to be added manually
                  ->setSortOrder(10) // Sort Order for the attribute in the tab form edit
                  ->save()
        ;
        echo "Attribute ".$attCode." Added to Attribute Set ".$set->getAttributeSetName()." in Attribute Group ".$group->getAttributeGroupName()."<br>\n";
    }

Wednesday 20 April 2016

How To Export and Import Categories in Magento

Step 1 of 4: Write the following code in export-category.php and place it to root directory. Run this file at browser http://www.yourdomain.com/export-category.php. It will generate a CSV file  Categories.csv (export all categories).


<?php
ini_set("memory_limit","10000M");
require_once "app/Mage.php";
umask(0);
Mage::app();
$category = Mage::getModel ( 'catalog/category' );
$tree = $category->getTreeModel ();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
if ($ids) {
 $string='';
 $heading = '"store","categories","cat_id","is_active","meta_title","meta_keywords","meta_description","include_in_menu","is_anchor","description",';
 foreach ($ids as $id){
  if($id>0)
  {
   $cate_cre = Mage::getModel('catalog/category');
   $cate_cre->load($id);
   $treeurl='';
   $cate_cre1=Mage::getModel('catalog/category')->load($id);
   $treeurl=$cate_cre->getName();
   if($cate_cre1->getParentId()>0)
   {
   for($i=0; ;$i++)
   {
   if($cate_cre1->getParentId()>0)
   {
   $abc=Mage::getModel('catalog/category')->load($cate_cre1->getParentId());
   $pCat=$abc->getName();
   if($abc->getId()>1){
   $treeurl=$pCat.'/'.$treeurl;
   }
   $cate_cre1=$abc;
   }
   else{
   break;
   }
   }
   }
   $store = "default";
   $string .='"'.$store.'","'.$treeurl.'","'.$id.'","'.$cate_cre->getIsActive().'","'.$cate_cre->getMetaTitle().'","'.$cate_cre->getMetaKeywords().'","'.$cate_cre-

>getMetaDescription().'","'.$cate_cre->getIncludeInMenu().'","'.$cate_cre->getIsAnchor().'","'.$cate_cre->getDescription().'"';
   $string.="\n";
  }
 }
 $csv_output = $heading ."\n".$string;
 $filename = "Categories";
 header("Content-type: application/vnd.ms-excel");
 header("Content-disposition: csv" . date("Y-m-d") . ".csv");
 header( "Content-disposition: filename=".$filename.".csv");
 print $csv_output;
}
?>

Step 2 of 4:  Import the categories :-
create config.xml  at app\code\local\Lky\Catalog\etc\config.xml
create Category.php at app\code\local\Lky\Catalog\Model\Convert\Adapter\Category.php
create Lky_All.xml  at  app\etc\modules

Code of config.xml :-
<?xml version="1.0"?>
<config>
  <global>
    <models>
      <catalog>
        <rewrite>
        <convert_adapter_category>Lky_Catalog_Model_Convert_Adapter_Category</convert_adapter_category>
    </rewrite>
   </catalog>
  </models>
 </global>
</config>

Code of Category.php :-

<?php
class Lky_Catalog_Model_Convert_Adapter_Category extends Mage_Eav_Model_Convert_Adapter_Entity
{
 protected $_categoryCache = array();
 protected $_stores;
 /**
 * Category display modes
 */
 protected $_displayModes = array( 'PRODUCTS', 'PAGE', 'PRODUCTS_AND_PAGE');

 public function parse()
 {
 $batchModel = Mage::getSingleton('dataflow/batch');
 $batchImportModel = $batchModel->getBatchImportModel();
 $importIds = $batchImportModel->getIdCollection();
 foreach ($importIds as $importId){
  $batchImportModel->load($importId);
  $importData = $batchImportModel->getBatchData();
  $this->saveRow($importData);
 }
 }
 /**
 * Save category (import)
 * @param array $importData
 * @throws Mage_Core_Exception
 * @return bool
 */
 public function saveRow(array $importData)
 {
 if (empty($importData['store'])) {
   if (!is_null($this->getBatchParams('store'))) {
   $store = $this->getStoreById($this->getBatchParams('store'));
   } else {
   $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
   Mage::throwException($message);
   }
 }else{
  $store = $this->getStoreByCode($importData['store']);
 }
 if ($store === false){
  $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
  Mage::throwException($message);
 }
 $rootId = $store->getRootCategoryId();
  if (!$rootId) {
  return array();
  }
 $rootPath = '1/'.$rootId;
  if (empty($this->_categoryCache[$store->getId()])) {
  $collection = Mage::getModel('catalog/category')->getCollection()
              ->setStore($store)
              ->addAttributeToSelect('name');
 $collection->getSelect()->where("path like '".$rootPath."/%'");
 foreach ($collection as $cat) {
  $pathArr = explode('/', $cat->getPath());
  $namePath = '';
  for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) {
  $name = $collection->getItemById($pathArr[$i])->getName();
  $namePath .= (empty($namePath) ? '' : '/').trim($name);
  }
  $cat->setNamePath($namePath);
 }
  $cache = array();
  foreach ($collection as $cat) {
  $cache[strtolower($cat->getNamePath())] = $cat;
  $cat->unsNamePath();
  }
  $this->_categoryCache[$store->getId()] = $cache;
  }
  $cache =& $this->_categoryCache[$store->getId()];
  $importData['categories'] = preg_replace('#\s*/\s*#', '/', trim($importData['categories']));
  if (!empty($cache[$importData['categories']])) {
  return true;
  }
  $path = $rootPath;
  $namePath = '';
  $i = 1;
 $categories = explode('/', $importData['categories']);
 /*$IsActive = $importData['IsActive'];*/
 $IsActive = $importData['is_active'];
 $IsAnchor =$importData['is_anchor'];
 $Description =$importData['description'];
 $IncludeInMenu=$importData['include_in_menu'];
 $MetaTitle=$importData['meta_title'];
 $MetaKeywords=$importData['meta_keywords'];
 $MetaDescription=$importData['meta_description'];
 $Image=$importData['image'];
 $URlkey=$importData['url_key'];
  foreach ($categories as $catName) {
  $namePath .= (empty($namePath) ? '' : '/').strtolower($catName);
  if (empty($cache[$namePath])) {
  $dispMode = $this->_displayModes[2];
    $cat = Mage::getModel('catalog/category')
    ->setStoreId($store->getId())
    ->setPath($path)
    ->setName($catName)
    ->setIsActive($IsActive)
    ->setIsAnchor($IsAnchor)
    ->setDisplayMode($dispMode)->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $cat->setIncludeInMenu($IncludeInMenu);
   $cat->setDescription($Description);
   $cat->setMetaTitle($MetaTitle).
    $cat->setMetaKeywords($MetaKeywords);
    $cat->setMetaDescription($MetaDescription);
    $cat->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_title']=$MetaTitle;
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_description']=$MetaDescription;
   $data['url_key']= $URlkey;
   $cat->addData($data);
   $cat->save();
  $cache[$namePath] = $cat;
  }
  $catId = $cache[$namePath]->getId();
  $path .= '/'.$catId;
  $i++;
  }
  return true;
 }

 /**
 * Retrieve store object by code
 *
 * @param string $store
 * @return Mage_Core_Model_Store
 */
 public function getStoreByCode($store)
 {
  $this->_initStores();
  if (isset($this->_stores[$store])) {
  return $this->_stores[$store];
  }
  return false;
 }

 /**
 * Init stores
 *
 * @param none
 * @return void
 */
 protected function _initStores ()
 {
  if (is_null($this->_stores)) {
  $this->_stores = Mage::app()->getStores(true, true);
  foreach ($this->_stores as $code => $store) {
  $this->_storesIdCode[$store->getId()] = $code;
  }
  }
 }
}

?>

Code of Lky_All.xml

<?xml version="1.0"?>
<config>
 <modules>
  <Lky_Catalog>
   <codePool>local</codePool>
   <active>true</active>
  </Lky_Catalog>
 </modules>
</config>

Step 3 of 4 : create dataflow advanced profile at admin > system > Import/Export > Dataflow - Advanced Profile and give the Profile Name is 'category import'.

place the following code to its Actions xml box :-

<action type="dataflow/convert_adapter_io" method="load">
     <var name="type">file</var>
     <var name="path">var/import</var>
     <var name="filename"><![CDATA[Categories.csv]]></var>
     <var name="format"><![CDATA[csv]]></var>
    </action>
    <action type="dataflow/convert_parser_csv" method="parse">
     <var name="delimiter"><![CDATA[,]]></var>
     <var name="enclose"><![CDATA["]]></var>
     <var name="fieldnames">true</var>
     <var name="store"><![CDATA[0]]></var>
     <var name="number_of_records">1</var>
     <var name="decimal_separator"><![CDATA[.]]></var>
     <var name="adapter">catalog/convert_adapter_category</var>
     <var name="method">parse</var>
    </action>

Step 4:  Put Categories.csv into var/import/ and removed cat_id colums from csv.
             remove first two rows.
            remove all Default Category/ from categories colunn in Categories.csv
           Now to Run Profile admin > system > Import/Export > Dataflow-Advanced Profile
           run 'category import' profile  from Run Profile > click 'Run Profile in Popup'
           import of category now start and automatically created category.

Wednesday 13 April 2016

drawing signature using canvas in jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script>
    var mousePressed = false;
var lastX, lastY;
var ctx;

function InitThis() {
    ctx = document.getElementById('myCanvas').getContext("2d");

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        mousePressed = false;
    });
        $('#myCanvas').mouseleave(function (e) {
        mousePressed = false;
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = 'black';
        ctx.lineWidth = '3';
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x; lastY = y;
}
   
function clearArea() {
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function imgcreate() {
//to append image in body
var can = document.getElementById('myCanvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
$("#imgct").html(img);
//image upload
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
     $('#sign').val(Pic);
    }
</script>

<body onLoad="InitThis();">
<form class="" action="form-submit.php" method="post">
<canvas id="myCanvas" width="500" height="200" style="border:2px solid black"></canvas>
<br /><br />
        <button onClick="javascript:clearArea();return false;">Refresh</button>
<input type="submit" value="Save" name="save" onMouseOver="return imgcreate();">
</form>
<div id="imgct"></div>
</body>
For upoad image to server create a php file with "form-submit.php" name. And use below code to save createed image :-
<?php
file_put_contents('images/test.png', base64_decode(substr($_POST['sign'], strpos($_POST['sign'], ",")+1)));
?>
After submit form image will be saved in images folder.

Monday 11 April 2016

Magento how to add new category attribute

Just copy paste the below code in header.phtml and run your magento once, your attribute will be created and you can see in backend under manage category. After you are done remove this code again.

<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

//Add selectbox attribure
$setup->addAttribute('catalog_category', 'add_slider', array(
    'group'         => 'Show home on slider',
    'input'         => 'select',
    'type'          => 'varchar',
    'label'         => 'Status',
    'option'        => array ('value' => array('optionone'=>array(0=>'Enable'),'optiontwo'=>array(0=>'Disable')) ),
    'backend'        => 'eav/entity_attribute_backend_array',
    'visible'       => 1,
    'required'      => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

//Add input type text attribure.
$setup->addAttribute(Mage_Catalog_Model_Category::ENTITY, 'slider_title', array(
    'group'         => 'Show home on slider',
    'input'         => 'text',
    'type'          => 'text',
    'label'         => 'Slider title',
    'backend'       => '',
    'visible'       => true,
    'required'      => false,
    'visible_on_front' => true,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
));

//Add image attribure
$setup->addAttribute('catalog_category', 'slider_image', array(
    'group'         => 'Show home on slider',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Slider image',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
)); ?>


To get attributes value paste following code in product list page (list.phtml) and you will get attribute value.

 <?php  $currentcategory = Mage::registry('current_category');
    $catId =  $currentcategory->getId();
    $current_category = Mage::getModel('catalog/category')->load($catId);
    $mediaUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."catalog/category/";
    echo $staus =  $current_category->getAddSlider()."<br/>";
    echo $title =  $current_category->getSliderTitle()."<br/>";
    echo $image =  $mediaUrl.$current_category->getSliderImage()."<br/>";
     ?>

Friday 8 April 2016

magento how to get sample file of downloadable products

 <?php $_myprodsamples = Mage::getModel('downloadable/sample');
 $download_fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."downloadable/files/samples";
$_mySampleCollection = $_myprodsamples->getCollection()
                   ->addProductToFilter($_product->getId())
                   ->addTitleToResult($_product->getStoreId());
?>



<?php foreach ($_mySampleCollection as $_sample1){
  //echo $_samplelink = $this->getUrl('downloadable/download/linkSample/link_id/'.$_sample ->getId());
   echo $_sample1->getSampleType(); //get file type
  echo $download_fileUrl.$_sample1->getSampleFile(); //Get file with url
  echo $_sample1->getSampleUrl();//get url if exist
   echo $_sample1->getTitle();
   print_r($_sample1); }?>

How to delete folder with contents in php

<?php

 function deletedir($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? deletedir("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }  
  deletedir("filePath");
  deletedir("../file");

?>

Friday 1 April 2016

Select All checkboxes using jQuery

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script>
var noc = jQuery.noConflict();
noc(document).ready(function () {
    noc("#ckbCheckAll").click(function () {
        noc(".checkBoxClass").prop('checked', noc(this).prop('checked'));
    });
     });
</script>

<input type="checkbox" id="ckbCheckAll" />
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>

simple paging in php

<?php
$vendor_count_data="SELECT COUNT(id) FROM tableName";
$vendor_data="SELECT * FROM tableName";

$pnn = "?pn=";
$sql = $vendor_count_data;
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$rows = $row[0]; // This is the number of results we want displayed per page
$page_rows = 2; // This tells us the page number of our last page
$last = ceil($rows/$page_rows); // This makes sure $last cannot be less than 1
if($last < 1){ $last = 1; } // Establish the $pagenum variable
$pagenum = 1; // Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){ $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']); }
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) { $pagenum = 1; } else if ($pagenum > $last) { $pagenum = $last; }
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
//$sql = "SELECT * FROM location_city WHERE status ='1' ORDER BY id DESC $limit";
$sql =$vendor_data." ".$limit;
$query = mysql_query($sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "$rows";
/* Showing 1 to 10 of 11 entries CUSTOM CODE */
//$textline2 = ($pagenum*10)." to ". $last;

if($pagenum==1)
{
$row_start=$pagenum;
}
else
{
$row_start=($page_rows*($pagenum-1))+1;
}
if(($pagenum*$page_rows)<$rows) {
$textline2 = $row_start." to ". ($pagenum*$page_rows);
}else
{
$textline2 = $row_start." to ". $rows;
}

$paginationCtrls = '';
if($last != 1){
$previous = $pagenum - 1;
if($pagenum!=1)
 {
 $paginationCtrls .= "<li><a href='".$pnn."1'>First</a></li><li><a href='".$pnn.$previous."'>Previous</a></li>";
 }
 
for($i = $pagenum-4; $i < $pagenum; $i++){ if($i > 0){ $paginationCtrls .= "<li><a href='".$pnn.$i."'>".$i."</a></li>"; /*}*/ } }
$paginationCtrls .= '<li><a href="javascript:void(0)" class="active">'.$pagenum.'</a></li>';
for($i = $pagenum+1; $i <= $last; $i++){ $paginationCtrls .= "<li><a href='".$pnn.$i."'>".$i."</a></li>";
if($i >= $pagenum+4){ break; } }
$next = $pagenum + 1;
if($last!=$pagenum)
{
$paginationCtrls .= "<li><a href='".$pnn.$next."'>Next</a></li> <li><a href='".$pnn.$last."'>Last</a></li>";
}

 } $list = '';

$i=$row_start;

while($row = mysql_fetch_array($query, MYSQL_ASSOC))
{ ?>
<p><?php echo $i; ?></p>
<p><?php echo $row['id']; ?> </p>

<?php $i++; } ?>
<?php //----show paging here------- ?>
<div class="pages-list">
<ul>
<?php echo $paginationCtrls; ?> 
</ul>
</div>
</div>