Showing posts with label magento. Show all posts
Showing posts with label magento. Show all posts

Monday, 16 October 2017

How to Cancel order programatically in Magento 2 ?



Hi by default Magento don't provide the cancel order from front-end . But its a great feature to have on the website to make customer more trust on the website .

To achieve this you can create your custom controller and follow the below code.In this i am posting a order id from the account page to my controller

<?php
 Nmaespace\Modulename\Controller\Action;

class Cancelorder  extends \Magento\Framework\App\Action\Action
{
  protected $orderManagement;
  public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Sales\Api\OrderManagementInterface $orderManagement

) {
    $this->orderManagement = $orderManagement;
    parent::__construct($context); 
}

public function execute()
{
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
       
        $customerSession = $objectManager->get('Magento\Customer\Model\Session');
        if(!$customerSession->isLoggedIn()) {
                $this->_redirect('/');
                die;
        }
       
        /*get request params */
        $get_customer_id = $customerSession->getCustomer()->getId();
       
        $get_order_id = $this->getRequest()->getParam('order_id');
        /*get request params */
        //die;
        $order = $objectManager->create('Magento\Sales\Model\Order')->load($get_order_id);
        $getcustomerid = $get_customer_id;
        $orderdata  = $order->getData();
        $order_status = $orderdata["status"];
        //print_r($orderdata);
        $cus_id =  $orderdata["customer_id"];
        if($getcustomerid != $cus_id){
            echo "We cant Cancel this order at this time" ;
            //die("go back");
        }
        if($order_status == "pending"){
            $this->orderManagement->cancel($get_order_id); 
            echo "Order Cancelled successfully" ;
        }
        else{
            echo "We cant Cancel this order at this time" ;
           
        }
}


}



thanks. Hope this will help .

Wednesday, 11 October 2017

How to upgrade Magento 2

Hi as magento 2 is still in a development phase and there are continuous releases are comming.
So we must have update Magento 2 timely for being safe and updated with all the features.
 
Fortunately upgrading Magento 2 is really very starlight forward and easy to do 
To upgrade Magenbto 2 we can use composer and below are the commads we need to 
run to upgrade magento to our desired version.
  
In this i am upgrading to magento 2.0.2  and you can change the version according to your needs 
 
composer require magento/product-community-edition 2.0.2 --no-update
composer update
rm -rf var/di var/generation
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento indexer:reindex
 
After upgrade, check your Magento version with the following command:

php bin/magento --version
 
 
 

Wednesday, 3 August 2016

How to get full product url from ID Magento ?

$store = Mage::app()->getStore();
$product_id = "1"// change your product id here 
 $path = Mage::getResourceModel('core/url_rewrite')
    ->getRequestPathByIdPath('product/'.$product_id, $store);

$url = $store->getBaseUrl($store::URL_TYPE_WEB) . $path;

Wednesday, 29 June 2016

How to create multiple custom options programmatically Magento ?


 To create a multiple custom options of a product in single time you can use  below  piece of code

<?php
require_once 'app/Mage.php';
Mage::app();
$productId = 905;   // your product id
$product = Mage::getModel('catalog/product')->load($productId);
                    $options = array(
                        array(
                        'title' => 'Color',
                        'type' => 'drop_down',
                        'is_required' => 1,
                        'sort_order' => 0,
                        'values' => array(
                                        array(
                                            'title' => 'Red',
                                            'price' => 10.50,
                                            'price_type' => 'fixed',
                                            'sku' => '',
                                            'sort_order' => 0,
                                        ),
                                        array(
                                            'title' => 'Gold',
                                            'price' => 0,
                                            'price_type' => 'fixed',
                                            'sku' => '',
                                            'sort_order' => 0,
                                        )
                                    )
                        ),
                        array('title' => 'size',
                        'type' => 'drop_down',
                        'is_required' => 1,
                        'sort_order' => 0,
                        'values' => array(
                                        array(
                                            'title' => 'small',
                                            'price' => 10.50,
                                            'price_type' => 'fixed',
                                            'sku' => '',
                                            'sort_order' => 0,
                                        ),
                                        array(
                                            'title' => 'large',
                                            'price' => 0,
                                            'price_type' => 'fixed',
                                            'sku' => '',
                                            'sort_order' => 0,
                                        )
                                    )
                        )
            );
//print_r($options);die;
 foreach($options as $options1){
$product->getOptionInstance()->unsetOptions();
$optionsnew = array($options1);
$product->setProductOptions($optionsnew);
$product->setCanSaveCustomOptions(true);
$product->save();
}
?>

Wednesday, 6 January 2016

Declaration of Zend_Pdf_FileParserDataSource_File::__construct() must be compatible with Zend_Pdf_FileParserDataSource::__construct()

Recently i was printing the pdf from magento admin and i got the following error


Declaration of Zend_Pdf_FileParserDataSource_File::__construct() must be compatible with Zend_Pdf_FileParserDataSource::__construct()

and on searching the issue i have found

This an incompatibility issue between PHP Version 5.4.4 and zend Framwork .

you can fix it by

change in this function lib/Zend/Pdf/FileParserDataSource.php.

change
abstract public function __construct();
to
abstract public function __construct($filePath);

Wednesday, 16 December 2015

How to use helpers in magento ?

In magento helpers is very useful functionality.Basically we can call helper functions anywhere in the site .

Each module has its own helper function

like in magento you use a below cart helper function to get cart url 

Mage::helper('checkout/cart')->getCartUrl()

the above helper function is created at below location

app/code/core/Mage/Checkout/Helper/Cart.php 

Lets create one new helper function in the end of Cart.php 

let say we need a function in which we need to get all ordered product items data 

 
For this i have create a new function as below

public function getordered_products_data($order_id){
        $cart =  Mage::getModel('sales/order')->load($order_id);
        print_r($cart->getData());die;
        foreach ($cart->getAllItems() as $item) {
        $loadproduct =     Mage::getModel('catalog/product')->load($item->getProduct()->getId());
        print_r($loadproduct->getData());
        }

}


and now we can use this function anywhere in the site as below

Mage::helper('checkout/cart')->getordered_products_data($your_order_id); // pass your order id here

and with this you can see all products data in order anywhere in the site by using above function.

thanks and hope it will help the magento comunity 


Friday, 30 October 2015

Magento - blocks not showing problems after installing SUPEE-6788

Hi recently i have install a latest patch from magento  SUPEE-6788 in my magento store.
But it has causes  block not render problem, no  blocks was visible on frontend .

than i troubleshoot it and found that in this patch magento has added a 2 new tables named as

permission_variable   and   permission_block 

  • first of all check if these tables exist in your database or not
  •  if they exist than check in permission_block table that your  block value exist in that table or not like below


 you will need to be insert your block name in the permission_block  as above
once you will  done with your block name and your blocks should be visible on frontend



Sunday, 25 October 2015

how to check admin is logged in or not in Magento

 Hi with the below peace of code you can check admin user is logged in or not anywhere is magento

$sesId = isset($_COOKIE['adminhtml']) ? $_COOKIE['adminhtml'] : false ;
$session = false;
if($sesId){
    $session = Mage::getSingleton('core/resource_session')->read($sesId);
}
$loggedIn = false;
if($session)
{
    if(stristr($session,'Mage_Admin_Model_User'))
    {
        $loggedIn = true;
    }
}
var_dump($loggedIn);// this will be true if admin logged in and false if not

Thursday, 8 October 2015

How to get category tree structure in Magento programatically ?

In many places we will need to get the category tree in magento programmatically. With the below peace of code you can get the tree anywhere in magento



   $rootCatId = Mage::app()->getStore()->getRootCategoryId(); // it will fetch your current store root id
   $catlistHtml = getTreeCategories($rootCatId, false);
   echo $catlistHtml;

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')  // is acategory active
                ->addAttributeToFilter('include_in_menu','1') //  to check include_in_menu yes or no
                ->addAttributeToFilter('parent_id',array('eq' => $parentId))  // filter parent id
                ->addAttributeToSort('position', 'asc');
              
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    $html .= '<ul class="'.$class.'">';
    foreach($allCats as $category)
    {
        $html .= '<li><span>'.$category->getName()."</span>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}


Please let me know if there is other such easy way to do this.I will love to hear and update my post.

thanks

Wednesday, 7 October 2015

How to get products of particular category in Magento ?

Hi it is very easy to get products of particular category in magento.
Check the below peace of code , with this you can get the products of your desored category


$products =
              Mage::getModel('catalog/category')->load('put your category id here')
            ->getProductCollection()
            ->addAttributeToSelect('*') ;
          

                foreach($products as $productsss){
                                  print_r($productsss->getData());
                    }


you can also add the filters in the above collection to get your desired products
like if you want to get only enabled products in the particular category like

$products = Mage::getModel('catalog/category')->load($catid)
            ->getProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('status', 1) ;


with this only products enabled will be show in list. You can add as many as filters you want.

Hope it will help somebody.

Thanks


Sunday, 31 May 2015

How to get customer session in external file Magento ?

Hi sometime we need to access the customer session in nexternal file and with the below code you can access


<?php
// Include Magento application
require_once ( "path_to_your_magento/app/Mage.php" );
umask(0);

// Initialize Magento
Mage::app();

// You have two options here,
// "frontend" for frontend session or "adminhtml" for admin session
Mage::getSingleton("core/session", array("name" => "frontend"));

$session = Mage::getSingleton("customer/session");

if($session->isLoggedIn())
{
    echo "Logged in";
}else{
    echo "Not logged in";
}

Monday, 25 May 2015

Copy products from one category to another in Magento

Hi sometime we need to copy the products from one caegory to another in magento , but by default there is no such option like this in magento. So we can do this programatically with the below code




<?php
$category = Mage::getModel('catalog/category');
$category->load('2'); // Preset category id
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$product->getId();// Now get category ids and add a specific category to them and save?
$categories = $product->getCategoryIds();
$categories[] = 3; // Category to add
$product->setCategoryIds($categories);
$product->save();

}

Thursday, 21 May 2015

Programatically create order in Magebto ?

HI sometime we need to create a orders grammatically in magento and with the below code you can easily


Create a new file in magento root and add the below code in that
<?php
require_once('../app/Mage.php'); //Path to Magento
umask(0);
Mage::app();


$productids=array(1,2); // products you want to add in order
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$order=1;
 // Start New Sales Order Quote
 $quote = Mage::getModel('sales/quote')->setStoreId($store->getId());

 // Set Sales Order Quote Currency
 $quote->setCurrency($order->AdjustmentAmount->currencyID);
 $customer = Mage::getModel('customer/customer')
             ->setWebsiteId($websiteId)
             ->loadByEmail('demo@gmail.com');
 if($customer->getId()==""){
     $customer = Mage::getModel('customer/customer');
     $customer->setWebsiteId($websiteId)
             ->setStore($store)
             ->setFirstname('rohit')
             ->setLastname('goel')
             ->setEmail('any@gmail.com')
             ->setPassword("123456");
     $customer->save();
 }

 // Assign Customer To Sales Order Quote
 $quote->assignCustomer($customer);

     // Configure Notification
 $quote->setSendCconfirmation(1);
 foreach($productids as $id){
     $product=Mage::getModel('catalog/product')->load($id);
     $quote->addProduct($product,new Varien_Object(array('qty'   => 1)));
 }

 // Set Sales Order Billing Address
 $billingAddress = $quote->getBillingAddress()->addData(array(
     'customer_address_id' => '',
     'prefix' => '',
     'firstname' => 'john',
     'middlename' => '',
     'lastname' =>'Deo',
     'suffix' => '',
     'company' =>'',
     'street' => array(
             '0' => 'Patiala',
             '1' => 'Sector 64'
         ),
     'city' => 'Noida',
     'country_id' => 'IN',
     'region' => 'PB',
     'postcode' => '147001',
     'telephone' => '9464532670',
     'fax' => 'gghlhu',
     'vat_id' => '',
     'save_in_address_book' => 1
 ));
 $shipprice=10;
 // Set Sales Order Shipping Address
$shippingAddress = $quote->getShippingAddress()->addData(array(
     'customer_address_id' => '',
     'prefix' => '',
     'firstname' => 'Rohit',
     'middlename' => '',
     'lastname' =>'Goel',
     'suffix' => '',
     'company' =>'',
     'street' => array(
             '0' => 'Patiala',
             '1' => 'Sector 64'
         ),
     'city' => 'Patiala',
     'country_id' => 'IN',
     'region' => 'PB',
     'postcode' => '147001',
     'telephone' => '9464532670',
     'fax' => 'gghlhu',
     'vat_id' => '',
     'save_in_address_book' => 1
 ));
 if($shipprice==0){
     $shipmethod='freeshipping_freeshipping';
 }

 // Collect Rates and Set Shipping & Payment Method
 $shippingAddress->setCollectShippingRates(true)
                 ->collectShippingRates()
                 ->setShippingMethod('flatrate_flatrate')
                 ->setPaymentMethod('checkmo');

 // Set Sales Order Payment
 $quote->getPayment()->importData(array('method' => 'checkmo'));

 // Collect Totals & Save Quote
 $quote->collectTotals()->save();

 // Create Order From Quote
 $service = Mage::getModel('sales/service_quote', $quote);
 $service->submitAll();
 //$increment_id = $service->getOrder()->getRealOrderId();

 // Resource Clean-Up
 //$quote = $customer = $service = null;

 // Finished
 //return $increment_id;



?>

Friday, 8 May 2015

Get collection count in magento

HI you can get the colection count by below code


Mage::getModel('catalog/product')->getCollection()->getSize();  :)

Tuesday, 4 November 2014

How to add a product to cart through parameters in url in magento

Hi sometime we need to add the product to cart by passing parameters to the url without actual adding to cart through default process. Fortunately we can do this in magento very easily.

Here is how we can do this


For simple product

www.yoursite.com/checkout/cart/add?product=[id]&qty=[qty]
 
id = your product id 
qty = number od items you ned to add to cart //  eg 1 , 2 or 3 
 
 


For simple product with custom optionss
 
http://magentoserver.com/checkout/cart/add?product=13&
qty=1&options[12]=57 
 

You can get the options id and value by viewing the source of the simple product page and it’s dropdowns.

By SKU

To add a product by SKU we must first instantiate an instance of the Mage::app() outside of the present application. You can do this as such:
  1. <?php
  2. include_once 'app/Mage.php';
  3. Mage::app();
  4. Mage::getSingleton('core/session', array('name' => 'frontend'));
By adding a $_GET variable we can get the sku and use an instance of the Product model to get the Magento ID for us.
  1. $cProd = Mage::getModel('catalog/product');
  2. $id = $cProd->getIdBySku("$sku");
Now that we have our ID we can do something useful with it - such as add it to the cart with the default of 1 product as the quantity. You can use other $_GET variables and conditions to simulate the adding of the quanitity to the querystring using the PHP Header Redirect:
  1. header('Location: '. Mage::getUrl('checkout/cart/add', array('product' => $id)));



For bundle product 





The standard URL format for adding a bundle item to the cart via URL is as such:
/path/to/app/checkout/cart/add/product/[id]/?bundle_option
[[option_id]][]=[selection_id]

  1. $w = Mage::getSingleton('core/resource')->getConnection('core_write');
  2. $result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where `parent_product_id`=$id");

his will provide us with our dataset. Using PDO and looping for each individual SKU inside of a given bundle ID we find that the following code will build the parameters for the cart add and then redirect to it:

$_product = Mage::getModel('catalog/product')->load($id);

if ($_product->getTypeId() == 'bundle') {
$w = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where `parent_product_id`=$id");
$route = "checkout/cart/add";
$params = array('product' => $id);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$params['bundle_option['. $row[option_id] .']'][] = $row['selection_id'];
};

header("Location: ". Mage::getUrl($route, $params));
}    

www.your_domain.com/checkout/cart/add?product=68&qty=1&super_attribute[528]=55&super_attribute[525]=56




For configurable product
http://www.your_domain.com/checkout/cart/add?product=68&qty=1&
super_attribute[528]=55&supe
r_attribute[525]=56
 
 
 

 
Hope this will help .thanks :)



Tuesday, 27 May 2014

Get cart details in Magento

You can get the cart details with the following code

<?php
$cart = Mage::getModel('checkout/cart')->getQuote(); //to get cart detail
foreach ($cart->getAllItems() as $item) {
   echo  $productId = $item->getProduct()->getId(); // product id in cart
   echo $productPrice = $item->getProduct()->getPrice(); // product price in cart
$product = Mage::getModel('catalog/product')->load($productId); // load product to get all details of product
//load the categories of this product
$categoryCollection = $product->getCategoryCollection();
$catIds = $product->getCategoryIds(); // to get all category ids of products in cart
$catCollection = Mage::getResourceModel('catalog/category_collection')  // to get all all details of categories of products in cart
                     //->addAttributeToSelect('name')
                     //->addAttributeToSelect('url')
                     ->addAttributeToSelect('*')
                     ->addAttributeToFilter('entity_id', $catIds)
                     ->addIsActiveFilter();

foreach($catCollection as $cat){
 // print_r($cat->getData());
 $catname[] =  $cat->getName();
  //echo $cat->getUrl();
}

}
print_r($catname); //category names array
?>

Friday, 23 May 2014

import product image from external url in magento 1.8

Hi in some project i need to import the csv of products in that i have he values of product images is like

http://www.example.com/image.jpg

i need to import that by default there is no mechanism in magento to import external image.

for doinmg this we have to edit the import function in below file

app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php

around line 754 you will see some code like this

  foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
             if (isset($importData[$mediaAttributeCode])) {
                 $file = trim($importData[$mediaAttributeCode]);
                 if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                    $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                 }
            }
         }


you simply need to replace this dunction with the below one 

foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                        if (isset($importData[$mediaAttributeCode])) {
                            $file = trim($importData[$mediaAttributeCode]);
                            if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                                // Start Of Code To Import Images From Urls
                                if (preg_match('%http?://[a-z0-9\-./]+\.(?:jpe?g|png|gif)%i', $file)) {
                                    $path_parts = pathinfo($file);
                                    $html_filename = DS . $path_parts['basename'];
                                    $fullpath = Mage::getBaseDir('media') . DS . 'import' . $html_filename;
                                    if(!file_exists($fullpath)) {
                                        file_put_contents($fullpath, file_get_contents($file));}
                                    $arrayToMassAdd[] = array('file' => trim($html_filename), 'mediaAttribute' => $mediaAttributeCode);
                                }
                                else
                                {
                                    $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                                }
                                // End Of Code To Import Images From URLs
                            }
                        }
                        }

Hope this will help you. thanks





Tuesday, 20 May 2014

Get current product data in custom file in magento

HI in some project i need to develop a module through which i need to insert a newly created product attribute  on product page with the modue xml file . For that i need to havethe current product data in my module file.

for that i have use the below function

$product_id = Mage::registry('current_product')->getId(); 
 
with this when your file will include in the porduct view page.it will load
 product id from your file.You can get any value from this.

Wednesday, 9 April 2014

Show popular search terms in sidebar Magento

Hi in some project i need to show the popular search terms in the sidebar . For that i have use the following code


  <reference name="right">
            <!-- Search Terms -->
            <block type="catalogsearch/term" after="cart.sidebar" name="catalogsearch.term" template="catalogsearch/term.phtml"/>
        </reference>


you can place this code in the  catalog.xml file of your theme

Friday, 7 March 2014

Move Magento from one server to another


Hi You can easily  move Magento website from one server to another server in 3 very easy steps.

1. Delete the content of the folder /var   // it contains cache and session files dont worry about this just delete this

2. Change the values of the file /app/etc/local.xml There you can find your connection string data (database user, host and name).

3. Once you got your database uploaded, you need to make some changes.
Run this query:
You gonna get something like this:
Now, change that values for your new url, run below query.
If you run the first query, now you gonna get something like this:

PgSQL
1
2
3
4
5
6
+-----------+---------+----------+-----------------------+------------------------------+
| config_id | scope   | scope_id | path                  | value                        |
+-----------+---------+----------+-----------------------+------------------------------+
|         2 | default |        0 | web/unsecure/base_url | http://www.somedomain.com/ |
|         3 | default |        0 | web/secure/base_url   | http://www.somedomain.com/ |
+-----------+---------+----------+-----------------------+------------------------------+