Thursday, 27 February 2020

save new customer magento2

class Index extends \Magento\Framework\App\Action\Action
{
    protected $storeManager;
    protected $customerFactory;
    protected $messageManager;
 
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Framework\Message\ManagerInterface $messageManager
    ){
        $this->storeManager     = $storeManager;
        $this->customerFactory  = $customerFactory;
$this->messageManager = $messageManager;
        parent::__construct($context);
    }

    public function execute()
    {
$post = $this->getRequest()->getPostValue();/*******post request*************/
if(isset($post['name'])){
$websiteId  = $this->storeManager->getWebsite()->getWebsiteId();
try {
      $customer   = $this->customerFactory->create();
      $customer->setWebsiteId($websiteId);
      $customer->setEmail($post['email']);
      $customer->setFirstname($post['name']);
      $customer->setLastname($post['name']);
      $customer->setTelephone($post['phone']);
      $password = rand();
      $newhash = hash('sha256', $password);
                  $customer->setPassword($newhash);
          $customer->save();
      $this->messageManager->addSuccess(__("Customer added successfully"));
      $customer->sendNewAccountEmail();
}
}catch (Exception $e) {
echo $e->getMessage();
}

}
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

Tuesday, 18 June 2019

Success page on payment gateway response magento2

inplement csrf interface in controller

class Success extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface
{
protected $_order;
protected $order;
protected $pageFactory;
protected $salesOrder;
protected $checkoutSession;

    public function __construct(Context $context)
    {
        parent::__construct($context);
}



public function createCsrfValidationException(
    RequestInterface $request
): ?InvalidRequestException {
    return null;
}

public function validateForCsrf(RequestInterface $request): ?bool
{
    return true;
}

public function execute()
    {
/**********************/
                     write your code
/**********************/
    } 

}

Wednesday, 18 February 2015

add filter on custom module collection

$collection  = Mage::getModel("seller/seller")->getCollection()->addFieldToFilter('email',$email);

Friday, 23 January 2015

Dispatch event

Suppose I like to add an event on payment save

do not add code in core file add it in overwrite file this is just an example


then i will add this code
magento\app\code\core\Mage\Checkout\controllers\OnepageController.php" 

on savePaymentAction function

 Mage::dispatchEvent('on_payment_methode_save', array('data' => $data));



 public function savePaymentAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        try {
            if (!$this->getRequest()->isPost()) {
                $this->_ajaxRedirectResponse();
                return;
            }
   
   

            $data = $this->getRequest()->getPost('payment', array());
            $result = $this->getOnepage()->savePayment($data);
    Mage::dispatchEvent('on_payment_methode_save', array('data' => $data)); 
            // get section and redirect data
            $redirectUrl = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();
            if (empty($result['error']) && !$redirectUrl) {
                $this->loadLayout('checkout_onepage_review');
                $result['goto_section'] = 'review';
                $result['update_section'] = array(
                    'name' => 'review',
                    'html' => $this->_getReviewHtml()
                );
            }
            if ($redirectUrl) {
                $result['redirect'] = $redirectUrl;
            }
        } catch (Mage_Payment_Exception $e) {
            if ($e->getFields()) {
                $result['fields'] = $e->getFields();
            }
            $result['error'] = $e->getMessage();
        } catch (Mage_Core_Exception $e) {
            $result['error'] = $e->getMessage();
        } catch (Exception $e) {
            Mage::logException($e);
            $result['error'] = $this->__('Unable to set Payment Method.');
        }
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }











now  add an event in your config XML file


<events>
 <on_payment_methode_save>
    <observers>
     <Company_Module_Model_Observer>
      <class>Company_Module_Model_Observer</class>
      <method>onPaymentSave</method>
     </Company_Module_Model_Observer>
    </observers>
    </on_payment_methode_save>
  </events>




and further in your Model/observer.php file


public function orderGridLodBefore(Varien_Event_Observer $observer){
    $event = $observer->getEvent()->getData();

}


Thursday, 31 July 2014

override adminhtml block magento

Go to custom module config.xml

this will overrite Mage/adminhtml/block/customer/group/edit/form.php
<config>
     <global>
              <blocks>
            <adminhtml>
                <rewrite><customer_group_edit_form>Bill_Checked_Block_Adminhtml_Customer_Group_Edit_Form</customer_group_edit_form>
                </rewrite>
            </adminhtml>
        </blocks>
     </global>
</config>





then create file in   app\code\local\Package\Module\Block\Adminhtml\Customer\Group\Edit\Form.php


use code


class Package_Module_Block_Adminhtml_Customer_Group_Edit_Form extends Mage_Adminhtml_Block_Customer_Group_Edit_Form
{
    protected function _prepareLayout()
    {
     ///Youre code is here
     }
}

Wednesday, 30 July 2014

Add multiple product images Magento

$newProduct = Mage::getModel(''catalog/product'')->load(productid)
$artworkhid = "image1.jpg,image2.jpg,image3.jpg";
$newProduct->setMediaGallery (array('images'=>array (), 'values'=>array ()));
$imgs = explode(',',$artworkhid);
 $i = 1;
foreach($imgs as $ims){
$previewImage = '/image_path/'.$ims;
     if(file_exists($previewImage)){
 if($i==1){
            $newProduct->addImageToMediaGallery ($previewImage, array ('thumbnail','small_image','image'), false, false);
      }else{
            $newProduct->addImageToMediaGallery ($previewImage, null, false, false);
  }
 $i++;
 }
}

Tuesday, 3 June 2014

Sunday, 18 May 2014

magento basics concept

Magento built in zend framework on object orient concept in MVC architecture Based on EDA(Event Driven Architecture).
Whent an event happens element listen event and sent to event engine.  

Thursday, 6 March 2014

Index management magento programmatically


get All Index process collection

$allIndex= Mage::getSingleton('index/indexer')->getProcessesCollection();

foreach ($allIndex as $index) {
if ($index->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX) {
$index->reindexEverything();
//echo "<pre>"; print_r($index->getProcess_id()); echo "</pre>";
}
}

Tuesday, 10 December 2013

get payment method in cart magento

for handling payment method display in cart we use event handling  we use config.xml in module or in custom module

app/code/local/regitration/field/etc/config.xml

<?xml version="1.0"?>
<config>
<frontend>
<events>
    <payment_method_is_active>
        <observers>
            <Regitration_Field_Model_observer>
                <class>Regitration_Field_Model_observer</class>
                <method>payment_method_is_active</method>
            </Regitration_Field_Model_observer>
        </observers>
    </payment_method_is_active>
</events>
  </frontend>
</config>



define action in observer file


app/code/local/regitration/field/model/observer.php

<?php
class Regitration_Field_Model_observer {

public function payment_method_is_active($observer){
     $event           = $observer->getEvent();
    $method          = $event->getMethodInstance();
    $result          = $event->getResult();
    $session = Mage::getSingleton('checkout/session')->getQuote();
$shippiingcarriers =  $session->getShippingAddress()->getShippingMethod();
            if ($shippiingcarriers == 'flatrate_flatrate' ){
                    if($method->getCode() == 'cashondelivery' OR $method->getCode() == 'checkmo' OR $method->getCode() == 'paypal_standard' or $method->getCode()=='purchaseorder'){
                        $result->isAvailable = false;
                    }else{
                        $result->isAvailable = true;
                }
            }

}
}
 ?>

Wednesday, 27 November 2013

get cross cell product collection magento

$cart = Mage::getModel('checkout/cart')->getQuote();
$productid = array();
$crossc = array();
foreach ($cart->getAllItems() as $item) {
    $productid[] = $item->getProduct()->getId();
foreach($item->getProduct()->getCrossSellProducts() as $crosscell){
$crossc[] = $crosscell['entity_id'];
}
}
$crossce = array_diff($crossc, $productid);
$collection = Mage::getResourceModel('catalog/product_collection')->addAttributeToSelect('*');
$collection->addIdFilter($crossce);
$collection->setPageSize(4);

upcell product collection magento

$pid = 2;
$product = Mage::getModel('catalog/product')->load($pid);
$collect = $this->getProduct()->getUpSellProductCollection();
$collect->getItems();

Friday, 1 November 2013

custom price in cart Magento

Add event in module  etc/config.xml

<?xml version="1.0"?>
<config>
</frontend>
        <events>
            <checkout_cart_product_add_after>
                <observers>
                    <Custom_Event_Model_Observer>
                        <type>singleton</type>
                        <class>Custom_Event_Model_Observer</class>
                        <method>Mytestmethod</method>
                    </Custom_Event_Model_Observer>
                </observers>
            </checkout_cart_product_add_after>
        </events>
</frontend>
</config>




calculate your price in Custom/Event/Model/Observer.php



class Custom_Event_Model_Observer {

    public function Mytestmethod(Varien_Event_Observer $observer) {
 $item = $observer->getQuoteItem();
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        $price = 66;
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);

    }
}





Thursday, 24 October 2013

Remove product image magento

$_product = Mage::getModel('catalog/product')->setStoreId($storeId)->load(2);
$removes[0] = a/b/aaa.png;
$removes[1] = a/c/bbb.png;
if(count($remove)>0){
 $attributes = $_product->getTypeInstance ()->getSetAttributes ();
 $gallery = $attributes ['media_gallery'];
$galleryData = $_product->getMediaGallery();
foreach($removes as $remove) {
foreach($galleryData['images'] as $image) {
if($remove==$image['file']){
$gallery->getBackend ()->removeImage( $_product, $image ['file'] );
}
}
}
$_product->save ();
}

Tuesday, 8 October 2013

multi select in custom module magento

$tool_cat_Arr = array(array('value' => '1', 'label' => 'Shirt'), array('value' => '2', 'label' => 'Tshirt'), array('value' => '3', 'label' => 'Custom'));


$fieldset->addField("tool_cat", "multiselect", array(
"label" => Mage::helper("storeinfo")->__("Tool Category"),
"name" => "tool_cat",
"values" => $tool_cat_Arr

));

filter in custom module magento

$stored = 25;

$storeinfo = Mage::getModel("storeinfo/storeinfo")->getCollection()->addFilter('storeowner_id',$stored)->load();

$storeinfoid = $storeinfo->getAllIds();

$Storeinfomodel = Mage::getModel("storeinfo/storeinfo")->load($storeinfoid[0]);

Wednesday, 18 September 2013

aad to cart product with custom option, super attribute magento

$cartarray = array($textaria_option => $instructions_text,
 $width_option_id => $width,
 $height_option_id => $height,
 $side_optionId => $side_optionVal,
 );
foreach($cartarray as $key=>$val){
if($val!= ''){
$arv[$key] = $val;
}
}

$productIdtoadd=$productDub->getId();
$cart = Mage::getSingelton('checkout/cart');
$cart->addProduct($productIdtoadd, array(
'qty' => $qty,
'total_price'=>$total,
'super_attribute' => array($attributeid =>$assproductColorOptionId),
'options' =>$arv
)
);

Tuesday, 17 September 2013

get product custom option magento

$priductid = 82;
$product = Mage::getModel('catalog/product')->load($priductid);

foreach ($product->getOptions() as $o) {
                              $values = $o->getValues();
$optionType = $o->getType();/*********TYPE************/
  $o->getId(); /************getId*****************/

                                     /* dropdown type custom option */
if ($optionType == 'drop_down') {
                                    foreach ($values as $k => $v) {
$drpdoption = $v->getData();
                                    }
                                }
                                       /* end dropdown type custom option */

}

Friday, 30 August 2013

save+Edit shipping title+name+Error Message magento

$shipmethods = Mage::getSingleton('shipping/config');

$title = "Aditya_title";
$name = "Aditya_Name";
$Errormessage= "This is shipping error Error Message";


$code = 'shipping_code';


$shipmethods->saveConfig('carriers/'.$code.'/title', "$title", 'stores');
$shipmethods->saveConfig('carriers/'.$code.'/name', "$name", 'stores');
$shipmethods->saveConfig('carriers/'.$code.'/specificerrmsg', "$Errormessage", 'stores');

magento get shipping method


$shippingmethods = Mage::getSingleton('shipping/config');
foreach($shippingmethods as $code =>$carrier){
     $shipTitle = Mage::getStoreConfig('carriers/'.$code.'/title');
     $shipName = Mage::getStoreConfig('carriers/'.$code.'/name');
     $shipErrorMsg = Mage::getStoreConfig('carriers/'.$code.'/specificerrmsg');
}