Showing posts with label import. Show all posts
Showing posts with label import. Show all posts

Saturday 23 June 2018

How to Import / Insert / Add product image from URL in Magento 2

use Magento\Framework\App\Action\Context;

class Createproduct extends \Magento\Framework\App\Action\Action {

    protected $directoryList;
    protected $file;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Filesystem\Io\File $file) {

        $this->_resultpageFactory = $pageFactory;
        $this->directoryList = $directoryList;
        $this->file = $file;
        return parent::__construct($context);
    }


    protected function getMediaDirTmpDir()
    {
        return $this->directoryList->getPath($this->directoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
    }

    public function setImage($product, $imageUrl, $visible = false, $imageType = [])
    {
        $tmpDir = $this->getMediaDirTmpDir();

        $this->file->checkAndCreateFolder($tmpDir);

        $newFileName = $tmpDir . baseName($imageUrl);


        $result = $this->file->read($imageUrl, $newFileName);
        if ($result) {
            $product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
        }
        return $result;
    }

    public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product')->load(1);
        $imagePath = "https://domain.com/image.jpg"; // path of the image
            $this->setImage($product, $imagePath, false, $imageType = ['image', 'small_image', 'thumbnail']);
            $product->save();
    }
}

Monday 23 January 2017

How to import Big SQL file usign PHP with shell command into hosting server

<?php

error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');

$dbinfo = array(
    "host" => 'localhost',
    "user" => 'magentom_jaydip',
    "pass" => 'rmO22RQ%UbW0',
    "dbname" => 'magentom_jaydip'
);


// Database Config
$sqlhost = $dbinfo["host"];
$dbuser = $dbinfo["user"];
$dbpassword = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];

// filename
$file = "mg_jaydip.sql";

shell_exec("mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file");

echo 'Finished!<br/>';
?>

Thursday 31 March 2016

How to create import functionality on grid page in magneto


Open Grid.php
protected function _prepareMassaction()
    {
..................
..................
//Upload your csv file into var/import directory
$dir = new DirectoryIterator(Mage::getBaseDir() . DS . 'var' . DS . 'import' . DS);
$extensions = "csv";
$csv = array();
foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile() && stristr($extensions, $fileinfo->getExtension())) {
        $csv[$fileinfo->getFilename()] = $fileinfo->getFilename();
    }            
}
$csv = array_merge(array(''=>'Please select'),$csv);
$this->getMassactionBlock()->addItem('import', array(
    'label'        => Mage::helper('metizsoft_taxgenerate')->__('Import'),
    'url'          => $this->getUrl('*/*/massCsv', array('_current'=>true)),
    'confirm'  => Mage::helper('metizsoft_taxgenerate')->__('Are you sure?'),
    'additional'   => array(
        'subgroup'    => array(
            'name'     => 'csv',
            'type'     => 'select',
            'class'    => 'required-entry',
            'label'    => Mage::helper('customer')->__('Select Csv'),
            'values'   => $csv
        )
    )
));
return $this;
}

Open your controller file. and put this code.public function massCsvAction()
{
$csvfile = $this->getRequest()->getParam('csv');
if (!$csvfile) {
  Mage::getSingleton('adminhtml/session')->addError(
      Mage::helper('metizsoft_taxgenerate')->__('Please select statetaxs.')
  );
} else {
  try {
     $csv = new Varien_File_Csv;
     $csvpath = Mage::getBaseDir() . DS . 'var' . DS . 'import' . DS . $csvfile;
             
     $datas = $csv->getData($csvpath);
     print_r($datas);
   } catch (Mage_Core_Exception $e) {
     Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
   } catch (Exception $e) {
     Mage::getSingleton('adminhtml/session')->addError(
        Mage::helper('metizsoft_taxgenerate')->__('There was an error updating statetaxs.')
     );
     Mage::logException($e);
   }
}
$this->_redirect('*/*/index');
}

Monday 8 June 2015

Import “Not Logged In” Pricing in Magento

<?php
/**
 * Class Tier price processor
 * @author dweeves
 *
 * This imports tier prices for columns names called "group_price:"
 */
class GrouppriceProcessor extends Magmi_ItemProcessor
{
    protected $_tpcol=array();
    protected $_singlestore=0;
    protected $__pricescope=2;

    public function getPluginInfo()
    {
        return array(
            "name" => "Group price importer",
            "author" => "Dweeves,bepixeld,Jason",
            "version" => "0.0.1",
            );
    }

    

    public function processItemAfterId(&$item,$params=null)
    {

        $pid=$params["product_id"];

        $tpn=$this->tablename("catalog_product_entity_group_price");
        $tpcol=array_intersect(array_keys($this->_tpcol),array_keys($item));
        //do nothing if item has no group price info or has not change
        if(count($tpcol)==0  )
        {
            return true;
        }
        else
        {

         //it seems that magento does not handle "per website" tier price
// on single store deployments , so force it to "default"
          //so we test wether we have single store deployment
// or not.
          //bepixeld patch : check pricescope from general config
          if($this->_singlestore==0 && $this->_pricescope!=0)
          {
            $wsids=$this->getItemWebsites($item);
          }
          else
          {
            $wsids=array(0);
          }
          $wsstr=$this->arr2values($wsids);
            //clear all existing tier price info for existing customer groups in csv
           $cgids=array();
            foreach($tpcol as $k)
            {
                $tpinf=$this->_tpcol[$k];
                if($tpinf["id"]!=null)
                {
                    $cgids[]=$tpinf["id"];
                }
                else
                {
                    $cgids=array();
                    break;
                }

            }

            //if we have specific customer groups
            if(count($cgids)>0)
            {
                //delete only for thos customer groups
                $instr=$this->arr2values($cgids);

                //clear tier prices for 
//selected tier price columns
                $sql="DELETE FROM $tpn WHERE entity_id=? AND customer_group_id IN ($instr) AND website_id IN ($wsstr)";
                $this->delete($sql,array_merge(array($pid),$cgids,$wsids));
            }
            else
            {
                //delete for all customer groups
                $sql="DELETE FROM $tpn WHERE entity_id=? AND website_id IN ($wsstr)";
                $this->delete($sql,array_merge(array($pid),$wsids));
            }
        }

        foreach($tpcol as $k)
        {

        //get tier price column info
          $tpinf=$this->_tpcol[$k];
          //now we've got a customer group id
          $cgid=$tpinf["id"];
          //add tier price
          $sql="INSERT INTO $tpn
            (entity_id,all_groups,customer_group_id,value,website_id) VALUES ";
          $inserts=array();
          $data=array();

          if($item[$k]=="")
          {
            continue;
          }
          $tpvals=explode(";",$item[$k]);

          foreach($wsids as $wsid)
          {
                //for each tier price value definition
                foreach($tpvals as $tpval)
                {
                    $tpprice=str_replace(",",".",$tpval);
                    if($tpprice=="")
                    {
                        continue;
                    }
                    if(substr($tpprice,-1)=="%")
                    {
                        //if no reference price,skip % tier price
                        if(!isset($item["price"]))
                        {
                            $this->warning("No price define, cannot apply % on group price");
                            continue;
                        }
                        $fp=(float)(str_replace(",",".",$item["price"]));
                        $pc=(float)(substr($tpprice,0,-1));
                        $m=($pc<0?(100+$pc):$pc);
                        $tpprice=strval(($fp*($m))/100.0);
                    }
                    $inserts[]="(?,?,?,?,?)";
                    $data[]=$pid;
                    //if all , set all_groups flag
                    $data[]=(isset($cgid)?0:1);
                    $data[]=(isset($cgid)?$cgid:0);
                    $data[]=$tpprice;
                    $data[]=$wsid;
                }
          }
          if(count($inserts)>0)
          {
            $sql.=implode(",",$inserts);
            $sql.=" ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)";
            $this->insert($sql,$data);
          }
         }
        return true;
    }

    public function processColumnList(&$cols,$params=null)
    {
       //inspect column list for getting tier price columns info
        foreach($cols as $col)
        {
            if(preg_match("|group_price:(.*)|",$col,$matches))
            {
                $tpinf=array("name"=>$matches[1],"id"=>null);

                //if specific tier price 
                 if($tpinf["name"]!=="_all_")
                 {
                    //get tier price customer group id
                    $sql="SELECT customer_group_id from ".$this->tablename("customer_group")." WHERE customer_group_code=?";
                    $cgid=$this->selectone($sql,$tpinf["name"],"customer_group_id");
                    $tpinf["id"]=$cgid;
                }
                else
                {
                    $tpinf["id"]=null;
                }
                $this->_tpcol[$col]=$tpinf;
            }
        }
        return true;
    }

    public function initialize($params)
    {
     $sql="SELECT COUNT(store_id) as cnt FROM ".$this->tablename("core_store")." WHERE store_id!=0";
     $ns=$this->selectOne($sql,array(),"cnt");
     if($ns==1)
     {
      $this->_singlestore=1;
     }
     //bepixeld patch : check pricescope from general config
     $sql = "SELECT value FROM ". $this->tablename('core_config_data') ." WHERE path=?";
     $this->_pricescope = intval($this->selectone($sql, array('catalog/price/scope'), 'value')); //0=global, 1=website    

    }
}