Oh snap! You are using an old version of browser. Update your browser to get new awesome features. Click for more details.

How to call CLI command via Cron file and pass an object as param



Put this code in your cron file

/**
 * @var \Magento\Framework\Serialize\SerializerInterface
 */
private $serializer;

/**
 * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
 */
private $productCollectionFactory;

public function __construct(
    \Magento\Framework\Serialize\SerializerInterface $serializer,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
) {
    $this->serializer               = $serializer;
    $this->productCollectionFactory = $productCollectionFactory;
}

public function execute()
{
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection = $this->serializer->serialize($collection);
    //Set you CLI command here and pass product collection array in the --collection argument
    system('php bin/magento customer:product:update --collection='.escapeshellarg($collection));

}

How to get --collection data in CLI file

$collection = $input->getOption(self::COLLECTION_OBJECT);

$collection = $this->serializer->unserialize($collection);

Magento 2 How to add native captcha to a custom form

Follow some step for using magento captcha into custom module.

Step 1. Vendor/Module/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>

Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'

Select form and save

Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\Customform" name="custom-index" template="custom-form.phtml">
                <container name="form.additional.info" label="Captcha">
                    <block class="Magento\Captcha\Block\Captcha" name="captcha" after="-" cacheable="false">
                        <action method="setFormId">
                            <argument name="formId" xsi:type="string">custom_form</argument>
                        </action>
                        <action method="setImgWidth">
                            <argument name="width" xsi:type="string">230</argument>
                        </action>
                        <action method="setImgHeight">
                            <argument name="width" xsi:type="string">50</argument>
                        </action>
                    </block>
                </container>
            </block>
</referenceContainer>

        <referenceBlock name="head.components">
            <block class="Magento\Framework\View\Element\Js\Components" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
        </referenceBlock>
</body>
</page>

Step 4: Vendor/Moduel/view/frontend/templates/custom-form.phtml

<div>
    <form class="custom-form"
          action="<?php echo $block->getFormAction(); ?>"
          id="custom_form"
          name="custom_form"
          method="post"
          enctype="multipart/form-data"
          data-hasrequired="<?php echo __('* Required Fields') ?>"
          data-mage-init='{"validation":{}}'>

        <h3><?php echo __('Custom Form')?></h3>
        <fieldset class="fieldset rma-info">
            <div class="field email required">
                <label class="label" for="rma_email"><?php echo __('Email')?></label>
                <input name="rma_email" id="rma_email" value="<?php echo $block->getCustomerLoggedIn() ? $data->getEmail(): "" ;?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}" />
            </div>

            <div class="field name required">
                <label class="label" for="customer_name"><?php echo __('Name')?></label>
                <input name="customer_name" id="customer_name" value="<?php echo $block->getCustomerLoggedIn() ? $data->getFirstname(): "" ;?>" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field phone required">
                <label class="label" for="phone"><?php echo __('Phone Number') ?></label>
                <input name="phone" id="phone" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field address required">
                <label class="label" for="address"><?php echo __('Address') ?></label>
                <input name="address" id="address" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <!-- Display captcha -->
            <?php echo $block->getChildHtml('form.additional.info'); ?>
            <!-- Display captcha -->

        </fieldset>

        <div class="actions-toolbar">
            <div class="primary">
                <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary">
                    <span><?php echo __('Submit') ?></span>
                </button>
            </div>
        </div>
    </form>
</div>

Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.

Step 5: Vendor/Module/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_yourroute_index_post">
        <observer name="captcha_custom_form" instance="Vendor\Module\Observer\CheckCustomFormObserver" />
    </event>
</config>

Step 6: Vendor/Module/Observer/CheckCustomFormObserver.php

<?php
namespace Vendor/Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class CheckCaptchaFormObserver implements ObserverInterface {

    protected $_helper;

    protected $_actionFlag;

    protected $messageManager;

    protected $_session;

    protected $_urlManager;

    protected $captchaStringResolver;

    protected $redirect;

    public function __construct(
        \Magento\Captcha\Helper\Data $helper,
        \Magento\Framework\App\ActionFlag $actionFlag,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Session\SessionManagerInterface $session,
        \Magento\Framework\UrlInterface $urlManager,
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        \Magento\Captcha\Observer\CaptchaStringResolver $captchaStringResolver
    ) {
        $this->_helper = $helper;
        $this->_actionFlag = $actionFlag;
        $this->messageManager = $messageManager;
        $this->_session = $session;
        $this->_urlManager = $urlManager;
        $this->redirect = $redirect;
        $this->captchaStringResolver = $captchaStringResolver;
    }

    public function execute(\Magento\Framework\Event\Observer $observer) {
        $formId = 'custom_form';
        $captchaModel = $this->_helper->getCaptcha($formId);

        $controller = $observer->getControllerAction();
        if (!$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) {
            $this->messageManager->addError(__('Incorrect CAPTCHA'));
            $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
            $this->_session->setCustomerFormData($controller->getRequest()->getPostValue());
            $url = $this->_urlManager->getUrl('yourroute/index/index', ['_nosecret' => true]);
            $controller->getResponse()->setRedirect($this->redirect->error($url));
        }

        return $this;
    }
}


Reference URL

Magento 2 add google recaptcha in custom form


Add recaptcha js file in your xml
Path: app/code/Name_space/Module_name/view/frontend/layout

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="https://www.google.com/recaptcha/api.js" src_type="url" />
</head>
</page>


Add recaptcha code in your phtml file
Path: app/code/Name_space/Module_name/view/frontend/templates

First add onsubmit event in form, It's validate recaptcha field via javascript.

<form class="test-form"
      action="<?php echo $block->getFormAction(); ?>"
      id="test_form"
      method="post"
      enctype="multipart/form-data"
      onsubmit="return capatcheFunction()"
      data-hasrequired="<?php echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>



Add recaptcha field in form

<div class="field recaptcha">
    <div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="Put Your Google Captcha Site Key Here"></div>
</div>


Add JavaScript function after form

<script type="text/javascript">
function capatcheFunction() {
    var exists = document.getElementById("g-recaptcha-response");
    if(exists == null){

    } else{
        var check = document.getElementById("g-recaptcha-response").value;
        if(check=='' || check == null){
            document.getElementById("recaptcha").style.border = "1px solid #ea0e0e";
            return false;
        }
        else{
            document.getElementById("recaptcha").style.border = "none";
            return true;
        }
    }
}
</script>


Full code example is below

<div>
    <form class="form-rma"
          action="<?php echo $block->getFormAction(); ?>"
          id="rma_form"
          method="post"
          enctype="multipart/form-data"
          onsubmit="return capatcheFunction()"
          data-hasrequired="<?php echo __('* Required Fields') ?>"
          data-mage-init='{"validation":{}}'>

        <h3><?php echo __('Testing Form')?></h3>
        <fieldset class="fieldset rma-info">
            <div class="field name required">
                <label class="label" for="customer_name"><?php echo __('Name')?></label>
                <input name="customer_name" id="customer_name" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field email required">
                <label class="label" for="email"><?php echo __('Email')?></label>
                <input name="email" id="email" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}" />
            </div>

            <div class="field phone required">
                <label class="label" for="phone"><?php echo __('Phone Number') ?></label>
                <input name="phone" id="phone" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field address required">
                <label class="label" for="address"><?php echo __('Address') ?></label>
                <input name="address" id="address" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field recaptcha">
                <div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="Put Your Google Captcha Site Key Here"></div>
            </div>
        </fieldset>

        <div class="actions-toolbar">
            <div class="primary">
                <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary">
                    <span><?php echo __('Submit') ?></span>
                </button>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
function capatcheFunction() {
    var exists = document.getElementById("g-recaptcha-response");
    if(exists == null){

    } else{
        var check = document.getElementById("g-recaptcha-response").value;
        if(check=='' || check == null){
            document.getElementById("recaptcha").style.border = "1px solid #ea0e0e";
            return false;
        }
        else{
            document.getElementById("recaptcha").style.border = "none";
            return true;
        }
    }
}
</script>


Validate recaptcha in controller
Path: app/code/Name_space/Module_name/Controller/Index

public function execute()
{
    $post = $this->getRequest()->getParams();
    $request = $this->getRequest();
    $remoteAddress = new \Magento\Framework\Http\PhpEnvironment\RemoteAddress($this->getRequest());
    $visitorIp = $remoteAddress->getRemoteAddress();

    $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
    $secret = 'Put Google Captcha Secret Key Here';
    $response = null;
    $path = 'https://www.google.com/recaptcha/api/siteverify?';
    $secretKey = $secret;
    $response = $post["g-recaptcha-response"];
    $remoteIp = $visitorIp;

    $response = file_get_contents($path."secret=$secretKey&response=$response&remoteip=$remoteIp");
    $answers = json_decode($response, true);
    if (trim($answers['success']) != true) {
        echo 'Invalid captcha please enter the valid captcha';exit;
    } else {
    echo 'Captcha is valid';exit;
    }
}

Magento 2 add Buy Now button on product view page


This module add "Buy Now" button on product view page, When user click  this button to process directly checkout. Here is  link to download it.

Installation Instruction

- Unzip Magebug_BuyNow.zip file
- Move app folder into your project root directory
- Run command: php bin/magento setup:upgrade
- Run command: php bin/magento cache:flush

Magento 2 How to Display Country & State/Province Dropdown in Custom Frontend Form



First create block file and put below code in this file.

<?php
namespace NameSpace\ModuleName\Block;

class Form extends \Magento\Directory\Block\Data
{
    protected $_customerSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Directory\Helper\Data $directoryHelper,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Magento\Framework\App\Cache\Type\Config $configCacheType,
        \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory,
        \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
        \Magento\Customer\Model\SessionFactory $customerSession,
        array $data = []
    ) {
        $this->_customerSession = $customerSession->create();
        parent::__construct(
            $context,
            $directoryHelper,
            $jsonEncoder,
            $configCacheType,
            $regionCollectionFactory,
            $countryCollectionFactory,
            $data
        );
    }

    public function getCustomerLoggedIn()
    {
        if ($this->_customerSession->isLoggedIn()) {
            return $this->_customerSession->getCustomer();
        }
    }

    public function getFormData()
    {
        $data = $this->getData('form_data');
        if ($data === null) {
            $formData = $this->_customerSession->getCustomerFormData(true);
            $data = new \Magento\Framework\DataObject();
            if ($formData) {
                $data->addData($formData);
                $data->setCustomerData(1);
            }
            if (isset($data['region_id'])) {
                $data['region_id'] = (int)$data['region_id'];
            }
            $this->setData('form_data', $data);
        }
        return $data;
    }

    public function getConfig($path)
    {
        return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }
}

Second create phtml file in your module

<?php
$countryList = $block->getCountries();
$regionList = $block->getRegion();
?>
<div>
    <form class="form-contact"
          action=""
          id="form-contact"
          method="post"
          data-hasrequired="<?php echo __('* Required Fields') ?>"
          data-mage-init='{"validation":{}}'>
         
        <fieldset class="fieldset contact-info">
            <div class="field region required">
                <label for="region_id" class="label"><span><?php echo __('State/Province:') ?></span></label>
                <div class="control">
                    <select id="region_id" name="region_id" title="<?php echo __('State/Province') ?>" class="validate-select" style="display:none;">
                        <option value=""><?php echo __('Please select a region, state or province.') ?></option>
                    </select>
                    <input type="text" id="region" name="region" value="<?php echo $block->getRegion() ?>" class="input-text <?php echo $block->escapeHtmlAttr($this->helper('Magento\Customer\Helper\Address')->getAttributeValidationClass('region')) ?>" style="display:none;">
                </div>
            </div>

            <div class="field country required">
                <label for="country" class="label"><span><?php echo $block->escapeHtml(__('Country:')) ?></span></label>
                <div class="control">
                    <?php echo $block->getCountryHtmlSelect() ?>
                </div>
            </div>
        </fieldset>
    </form>
</div>

<script type="text/x-magento-init">
    {
        "#country": {
            "regionUpdater": {
                "optionalRegionAllowed": <?= /* @noEscape */ $block->getConfig('general/region/display_all') ? 'true' : 'false' ?>,
                "regionListId": "#region_id",
                "regionInputId": "#region",
                "postcodeId": "#zip",
                "form": "#form-validate",
                "regionJson": <?= /* @noEscape */ $this->helper(\Magento\Directory\Helper\Data::class)->getRegionJson() ?>,
                "defaultRegion": "<?= (int) $block->getRegionId() ?>",
                "countriesWithOptionalZip": <?= /* @noEscape */ $this->helper(\Magento\Directory\Helper\Data::class)->getCountriesWithOptionalZip(true) ?>
            }
        }
    }
</script>

Magento 2 Load Region By Region Id


If you need region data by region id. check the below code.


/**
* @var \Magento\Directory\Model\RegionFactory
*/
protected $_regionFactory;

public function __construct(
    \Magento\Directory\Model\RegionFactory $regionFactory $regionFactory
) {
    $this->_regionFactory = $regionFactory;
}

function getRegionDataById($regionId){
//Ex. $regionId = 12;
$region = $this->_regionFactory->create();
        $region->load($regionId);
        echo '<pre>';print_r($region->getData());exit;
}

Output
Array
(
    [region_id] => 12
    [country_id] => US
    [code] => CA
    [default_name] => California
    [name] => California
)

hope so it will help.

Magento 2 - Get product active filters using Event Obeserver


Create events.xml

Path: app/code/Module_Name_Space/Module_Name/etc/frontend/events.xml

Put this code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_generate_blocks_after">
    <observer name="customize-category-block" instance="Module_Name_Space/Module_Name\Observer\Filters" />
</event>
</config>


Now create observer file Filters.php

Path: app/code/Indianic/CategoryTab/Observer/Filters.php

Put this code

<?php
namespace Module_Name_Space\Module_Name\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\Layer\Resolver as LayerResolver;

class Categoryblock implements ObserverInterface
{
    /**
     * @var \Magento\Catalog\Model\Layer\Category
     */
    protected $catalogLayer;

    public function __construct(
        LayerResolver $layerResolver
    ) {
        $this->catalogLayer = $layerResolver->get();
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
{
    $action = $observer->getData('full_action_name');
    if ($action !== 'catalog_category_view') {
        return;
    }

        // Get selected filters
        $layer = $this->catalogLayer;
        $activeFilters = $layer->getState()->getFilters();
}
}

Also you can unset layout this observer, put below code in execute function

/** @var \Magento\Framework\View\Layout $layout */
$layout = $observer->getData('layout');
$layout->unsetElement('Element_Name_Here');

Magento 2 Add tabs with product attribute content on product page


In Magento, like in most other eCommerce platforms, tabbed navigation is utilized on product pages for displaying various product information and data. By default, and this is the same for Luma and Blank theme, there are three tabs on the product page. If you want to add an extra tab on product detail page and display product attribute value on this tab. So maybe this article help you.

Here is module link. You can download and easy to install.

Install extension by command line

Step 1: Download the extension

Step 2: Unzip the file in a temporary directory

Step 3: Upload app folder to your Magento installation root directory

Step 4: Enter the following at the command line:

- php bin/magento setup:upgrade
- sudo php bin/magento setup:di:compile
If magento deploy mode is developer
- sudo php bin/magento setup:static-content:deploy -f
If magento deploy mode is production
- sudo php bin/magento setup:static-content:deploy
- php bin/magento cache:flush

Step 6: After opening Stores­ >>Configuration >­>Advanced >­> Advanced, the module will be shown in the admin panel

This module is tested in Magento 2.2.2 version.

Magento 2 How to get the database(connection) details


If you required database detail in your custom file. This article help to how get the database details from env.php file. In your block file add below code and simply call function anywhere.


<?php
namespace Namespace\Modulename\Block;

use Magento\Framework\App\DeploymentConfig\Reader;

class Index extends \Magento\Framework\View\Element\Template
{
private $deploymentConfigReader;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        Reader $deploymentConfigReader
    ) {
    parent::__construct($context);
    $this->deploymentConfigReader = $deploymentConfigReader;
    }

    public function getDbConnection()
    {
        try {
            $deploymentConfig = $this->deploymentConfigReader->load();
            $DBdata = $deploymentConfig['db']['connection']['default'];

            echo 'host: ' . $DBdata['host'];
            echo ' username: ' . $DBdata['username'];
            echo ' password: ' . $DBdata['password'];
            echo ' dbname: ' . $DBdata['dbname'];
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

Magento 2 To get product attributes of specific attribute group id


Hello Friends,

Get specific attribute collection by attribute group id in product page. Use below code. First get your group id and attribute_set_id in eav_attribute_group table.

Then use this code.

//$_product is current product object
$productAttributes = $_product->getAttributes();
$group_id = 104; //Past Your Attribute Group Id
$attributeSetId = 16; //Past Your Attribute Set Id

foreach ($productAttributes as $attribute) {

    if ($attribute->isInGroup($attributeSetId, $group_id)) {

        if ($attribute->getFrontend()->getValue($_product)) {
            echo 'Attribute Label: '.$attribute->getFrontendLabel().'<br>';
            $valueArray = explode(",",$attribute->getFrontend()->getValue($_product));

            foreach ($valueArray as $valuesArray) {
                echo 'Attribute Value: '.$valuesArray;
                echo '<br>';
            }

        }

    }

}

Magento direct sql query


Hello Friend's,

Here some usefully mysql query.

========================================================================

Number Orders - Sales - Avg Per Order

*********************************************************************************

AVG Order Value Per Day

SELECT DATE(`created_at`) AS 'Date', AVG(`grand_total`) AS 'AVG Order Value Per Day' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY DATE(`created_at`) ORDER BY DATE(`created_at`) DESC

--------------------------------------------------------------------------------------

AVG Order Value Per Week

SELECT WEEK(`created_at`) AS 'Week',YEAR(`created_at`) AS 'Year', AVG(`grand_total`) AS 'AVG Order Value Per Week' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY WEEK(`created_at`),YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC, WEEK(`created_at`) DESC

--------------------------------------------------------------------------------------

AVG Order Value Per Month

SELECT MONTHNAME(`created_at`) AS 'Month',YEAR(`created_at`) AS 'Year', AVG(`grand_total`) AS 'AVG Order Value Per Month' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY YEAR(`created_at`), MONTH(`created_at`) 
ORDER BY YEAR(`created_at`) DESC, MONTH(`created_at`) DESC

--------------------------------------------------------------------------------------

AVG Order Value Per year

SELECT YEAR(`created_at`) AS 'Year', AVG(`grand_total`) AS 'AVG Order Value Per year' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Sale Per Day

SELECT DATE(`created_at`) AS 'Date',SUM(`grand_total`) AS 'Total Sale Per Day' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY DATE(`created_at`) ORDER BY DATE(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Sale Per Week

SELECT WEEK(`created_at`) AS 'Week',YEAR(`created_at`) AS 'Year', SUM(`grand_total`) AS 'Total Sale Per Week' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY WEEK(`created_at`),YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC, WEEK(`created_at`) DESC

--------------------------------------------------------------------------------------

Total sales per month

SELECT MONTHNAME(`created_at`) AS 'Month',YEAR(`created_at`) AS 'Year', SUM(`grand_total`) AS 'Total Sale Per Month' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY YEAR(`created_at`), MONTH(`created_at`) 
ORDER BY YEAR(`created_at`) DESC, MONTH(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Sale Per year

SELECT YEAR(`created_at`) AS 'Year', SUM(`grand_total`) AS 'Total Sale Per year' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' GROUP BY YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC

--------------------------------------------------------------------------------------

Specific Month of year  sale

EX. 
" MONTH(`created_at`) = '01' " = Number of month(05)
" YEAR(`created_at`) = '2016' " = Number of year(2013)

SELECT MONTHNAME(`created_at`) AS 'Month',YEAR(`created_at`) AS 'Year', SUM(`grand_total`) AS 'Total sale',`status` FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' AND MONTH(`created_at`) = '01' AND YEAR(`created_at`) = '2016'

--------------------------------------------------------------------------------------

Specific Month wise yearly sale

EX. 
" YEAR(`created_at`) = '2015' " = Number of year(2013)

SELECT MONTHNAME(`created_at`) AS 'Month', SUM(`grand_total`) AS 'Total Sale Per Month' FROM `sales_flat_order` WHERE `store_id` = 2 AND `status` = 'complete' AND YEAR(`created_at`) = '2015' GROUP BY MONTH(`created_at`) ORDER BY MONTH(`created_at`) ASC

--------------------------------------------------------------------------------------

Total Order Per Day

SELECT DATE(`created_at`) AS 'Date', COUNT(*) AS 'Total Order Per Day' FROM `sales_flat_order` WHERE `store_id` = 2 GROUP BY DATE(`created_at`) ORDER BY DATE(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Order Per Week

SELECT WEEK(`created_at`) AS 'Week',YEAR(`created_at`) AS 'Year', COUNT(*) AS 'Total Order Per Week' FROM `sales_flat_order` WHERE `store_id` = 2  GROUP BY WEEK(`created_at`),YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC, WEEK(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Order Per Month

SELECT MONTHNAME(`created_at`) AS 'Month',YEAR(`created_at`) AS 'Year', COUNT(*) AS 'Total Order Per Month' FROM `sales_flat_order` WHERE `store_id` = 2 GROUP BY YEAR(`created_at`), MONTH(`created_at`) ORDER BY YEAR(`created_at`) DESC,MONTH(`created_at`) DESC

--------------------------------------------------------------------------------------

Total Order Per Year

SELECT YEAR(`created_at`) AS 'Year', COUNT(*) AS 'Total Order Per Year' FROM `sales_flat_order` WHERE `store_id` = 2 GROUP BY YEAR(`created_at`) ORDER BY YEAR(`created_at`) DESC

*******************************************

Sales by New Customers (How many new and sales)

Consider created customers in current month customers as new customer

SELECT `sales_flat_order`.`customer_email`,`sales_flat_order`.`customer_id`,`customer_entity`.`created_at` AS 'Customer Created Date',COUNT(*) AS 'Total Order By Customer' FROM `sales_flat_order` JOIN `customer_entity` ON `customer_entity`.`entity_id` = `sales_flat_order`.`customer_id` WHERE MONTH(`customer_entity`.`created_at`) = MONTH(NOW()) AND YEAR(`customer_entity`.`created_at`) = YEAR(NOW()) AND YEAR(`sales_flat_order`.`created_at`) = YEAR(NOW()) AND `sales_flat_order`.`store_id` = '2' GROUP BY `sales_flat_order`.`customer_email`

*********************************************************************************

Sales by Existing Customers

Consider not created customers in current month as existing customer

SELECT `sales_flat_order`.`customer_email`,`sales_flat_order`.`customer_id`,`customer_entity`.`created_at` AS 'Customer Created Date',`sales_flat_order`.`created_at` AS 'Order Created Date',COUNT(*) AS 'Total Order By Customer' FROM `sales_flat_order` JOIN `customer_entity` ON `customer_entity`.`entity_id` = `sales_flat_order`.`customer_id` WHERE MONTH(`customer_entity`.`created_at`) != MONTH(NOW()) AND YEAR(`customer_entity`.`created_at`) != YEAR(NOW()) AND MONTH(`sales_flat_order`.`created_at`) = MONTH(NOW()) AND YEAR(`sales_flat_order`.`created_at`) = YEAR(NOW()) AND `sales_flat_order`.`store_id` = '2' GROUP BY `sales_flat_order`.`customer_email`

*********************************************************************************

Sales by Customers By Date

SELECT `customer_firstname`,`customer_lastname`,`customer_email`,`customer_id`, COUNT(*) AS 'Total Order Per Customer', DATE(`created_at`) AS 'Date' FROM `sales_flat_order` where `store_id` = 2 GROUP BY DATE(`created_at`), `customer_email` ORDER BY DATE(`created_at`) DESC

*********************************************************************************

Sales By State

SELECT `sales_flat_order_address`.`region`,count(*) FROM `sales_flat_order` JOIN `sales_flat_order_address` ON `sales_flat_order`.`entity_id` = `sales_flat_order_address`.`parent_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order_address`.`address_type` = 'shipping' GROUP BY `sales_flat_order_address`.`region`

*********************************************************************************

Sales By Product

--------------------------------------------------------------------------------------

Total Sale for all product

SELECT `sales_flat_order_item`.`sku` AS 'Product SKU', ROUND(SUM(`sales_flat_order_item`.`qty_ordered`)) AS 'Total Product Sale' FROM `sales_flat_order` JOIN `sales_flat_order_item` ON `sales_flat_order`.`entity_id` = `sales_flat_order_item`.`order_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order`.`status` = 'complete' GROUP BY `sales_flat_order_item`.`sku`

--------------------------------------------------------------------------------------

Total Sale for specific Product

SELECT `sales_flat_order_item`.`sku` AS 'Product SKU', ROUND(SUM(`sales_flat_order_item`.`qty_ordered`)) AS 'Total Product Sale' FROM `sales_flat_order` JOIN `sales_flat_order_item` ON `sales_flat_order`.`entity_id` = `sales_flat_order_item`.`order_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order_item`.`sku` = 'JRGEL-60' AND `sales_flat_order`.`status` = 'complete'

--------------------------------------------------------------------------------------

Total Sale for specific Product with specific Day

SELECT DATE(`sales_flat_order`.`created_at`) AS 'Date', `sales_flat_order_item`.`sku` AS 'Product SKU', ROUND(SUM(`sales_flat_order_item`.`qty_ordered`)) AS 'Total Product Sale' FROM `sales_flat_order` JOIN `sales_flat_order_item` ON `sales_flat_order`.`entity_id` = `sales_flat_order_item`.`order_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order_item`.`sku` = 'JRGEL-60' AND `sales_flat_order`.`status` = 'complete' AND DATE(`sales_flat_order`.`created_at`) = '2015-12-15'

--------------------------------------------------------------------------------------

Total Sale for specific Product with specific month period

SELECT YEAR(`sales_flat_order`.`created_at`) AS 'Year', MONTHNAME(`sales_flat_order`.`created_at`) AS 'Month', `sales_flat_order_item`.`sku` AS 'Product SKU', ROUND(SUM(`sales_flat_order_item`.`qty_ordered`)) AS 'Total Product Sale' FROM `sales_flat_order` JOIN `sales_flat_order_item` ON `sales_flat_order`.`entity_id` = `sales_flat_order_item`.`order_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order_item`.`sku` = 'JRGEL-60' AND `sales_flat_order`.`status` = 'complete' AND MONTH(`sales_flat_order`.`created_at`) = '10' AND YEAR(`sales_flat_order`.`created_at`) = '2014'

--------------------------------------------------------------------------------------

Total Sale for specific Product with specific year period

SELECT YEAR(`sales_flat_order`.`created_at`) AS 'Year', `sales_flat_order_item`.`sku` AS 'Product SKU', ROUND(SUM(`sales_flat_order_item`.`qty_ordered`)) AS 'Total Product Sale' FROM `sales_flat_order` JOIN `sales_flat_order_item` ON `sales_flat_order`.`entity_id` = `sales_flat_order_item`.`order_id` WHERE `sales_flat_order`.`store_id` = 2 AND `sales_flat_order_item`.`sku` = 'JRGEL-60' AND `sales_flat_order`.`status` = 'complete' AND YEAR(`sales_flat_order`.`created_at`) = '2015'

*********************************************************************************

Sales by type of Customer


SELECT `customer_group`.`customer_group_code` AS 'Customer Role', COUNT(`sales_flat_order`.`customer_id`) AS 'Total Customer' FROM `sales_flat_order` JOIN `customer_group` ON `customer_group`.`customer_group_id` = `sales_flat_order`.`customer_group_id` where `sales_flat_order`.`store_id` = 2 GROUP BY `customer_group`.`customer_group_code`

--------------------------------------------------------------------------------------

Sales by specific type of Customer
EX. - 'Wholesale'

SELECT `sales_flat_order`.`entity_id`, `sales_flat_order`.`customer_id`,`sales_flat_order`.`customer_email`,`customer_group`.`customer_group_code` FROM `sales_flat_order`
JOIN `customer_group` ON `customer_group`.`customer_group_id` = `sales_flat_order`.`customer_group_id`
where `sales_flat_order`.`store_id` = 2 AND `customer_group`.`customer_group_code` = 'Wholesale'

*********************************************************************************

Sales by customer on specific period (Report that show how many times during year)

SELECT YEAR(`created_at`) AS 'Year',`customer_firstname`,`customer_lastname`,`customer_email` AS 'Customer Email',`customer_id`,COUNT(*) AS 'Total Order By Customer' FROM `sales_flat_order` WHERE `store_id` = 2 AND YEAR(`created_at`) = '2015' GROUP BY `customer_email` ORDER BY COUNT(`customer_email`) DESC

*********************************************************************************

Birthdays per month (List Customers)

SELECT `customer_entity`.`email`,`customer_entity_varchar`.`value` FROM `customer_entity` JOIN `customer_entity_varchar` ON `customer_entity`.`entity_id` = `customer_entity_varchar`.`entity_id` WHERE `customer_entity_varchar`.`attribute_id` = 11 AND MONTH(`customer_entity_varchar`.`value`) = MONTH(NOW())

*********************************************************************************

Number of orders per customers

SELECT `customer_email` AS 'Customer Email',COUNT(`customer_email`) AS 'Total Order By Customer' FROM `sales_flat_order` WHERE `store_id` = 2  GROUP BY `customer_email` ORDER BY COUNT(`customer_email`) DESC


*********************************************************************************

Show all customer attribute data from Magento database

SELECT ce.*, ea.attribute_code, 
    CASE ea.backend_type 
       WHEN 'varchar' THEN ce_varchar.value
       WHEN 'int' THEN ce_int.value
       WHEN 'text' THEN ce_text.value
       WHEN 'decimal' THEN ce_decimal.value
       WHEN 'datetime' THEN ce_datetime.value
       ELSE NULL
    END AS value
  FROM customer_entity AS ce 
  LEFT JOIN eav_attribute AS ea ON ce.entity_type_id = ea.entity_type_id
  LEFT JOIN customer_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'
  LEFT JOIN customer_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'
  LEFT JOIN customer_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'
  LEFT JOIN customer_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'
  LEFT JOIN customer_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'


*********************************************************************************

Update status form "fulfillment" to "complete" in sales order table

SELECT * FROM `sales_flat_order` where `store_id` = 2 AND `state` = 'complete' AND `status` = 'fulfillment'

UPDATE `sales_flat_order` SET `status` = 'complete' where `store_id` = 2 AND `state` = 'complete' AND `status` = 'fulfillment'

----------------------------------------------------------------------------------------

Update status form "fulfillment" to "complete" in sales order grid table

SELECT sg.* FROM `sales_flat_order_grid` as sg JOIN `sales_flat_order` as s ON s.`entity_id` = sg.`entity_id` WHERE s.`store_id` = 2 AND s.`state` = 'complete' AND s.`status` = 'fulfillment'

UPDATE `sales_flat_order_grid` as sg JOIN `sales_flat_order` as s ON s.`entity_id` = sg.`entity_id` SET sg.`status` = 'complete' WHERE s.`store_id` = 2 AND s.`state` = 'complete' AND s.`status` = 'fulfillment'

----------------------------------------------------------------------------------------

Delete status "fulfillment" form sales order status history table

SELECT sh.* FROM `sales_flat_order_status_history` as sh JOIN `sales_flat_order` as s ON s.`entity_id` = sh.`parent_id` WHERE s.`store_id` = 2 AND s.`state` = 'complete' AND s.`status` = 'fulfillment' AND sh.`status` = 'fulfillment' AND sh.`entity_name` = 'order'

DELETE sh.* FROM `sales_flat_order_status_history` as sh JOIN `sales_flat_order` as s ON s.`entity_id` = sh.`parent_id` WHERE s.`store_id` = 2 AND s.`state` = 'complete' AND s.`status` = 'fulfillment' AND sh.`status` = 'fulfillment' AND sh.`entity_name` = 'order'


*********************************************************************************

Update order table date (day light saving)

UPDATE `sales_flat_order` 
SET `created_at`= ADDDATE(`created_at`, INTERVAL 60 MINUTE) 
WHERE `store_id`= 3 AND (created_at BETWEEN '2011-11-06 02:00:00' AND '2012-03-11 02:00:00'
OR created_at BETWEEN '2011-11-06 02:00:00' AND '2012-03-11 02:00:00'
OR created_at BETWEEN '2012-11-04 02:00:00' AND '2013-03-10 02:00:00'
OR created_at BETWEEN '2013-11-03 02:00:00' AND '2014-03-09 02:00:00'
OR created_at BETWEEN '2014-11-02 02:00:00' AND '2015-03-08 02:00:00'
OR created_at BETWEEN '2015-11-01 02:00:00' AND '2016-03-13 02:00:00');

----------------------------------------------------------------------------------------

Update order grid table date (day light saving)

UPDATE `sales_flat_order_grid` 
SET `created_at`= ADDDATE(`created_at`, INTERVAL 60 MINUTE) 
WHERE `store_id`= 3 AND (created_at BETWEEN '2011-11-06 02:00:00' AND '2012-03-11 02:00:00'
OR created_at BETWEEN '2012-11-04 02:00:00' AND '2013-03-10 02:00:00'
OR created_at BETWEEN '2013-11-03 02:00:00' AND '2014-03-09 02:00:00'
OR created_at BETWEEN '2014-11-02 02:00:00' AND '2015-03-08 02:00:00'
OR created_at BETWEEN '2015-11-01 02:00:00' AND '2016-03-13 02:00:00');


*********************************************************************************

Get all refund

SELECT MONTHNAME(`created_at`) AS 'Month',YEAR(`created_at`) AS 'Year', SUM(`total_refunded`) AS 'Total Refund Per Month' FROM `sales_flat_order` WHERE `store_id` = 2 AND `total_refunded` != '' GROUP BY YEAR(`created_at`), MONTH(`created_at`) 
ORDER BY YEAR(`created_at`) DESC, MONTH(`created_at`) DESC


Magento Techniques to Show configurable product options in custom product listing with price change


Displaying product options like colors, sizes, price… in the custom product list gives an incentive to the customer to select and purchase a product. It is likely not possible to achieve these options by installing default Magento alone. In this article, we will recommend some effective methods to show options for the configurable and product options in custom product list. Check them out!

1. Create Productoptions module with Magebug namespace (app/local/Magebug/Productoptions)
2.Create a file named app/etc/modules/Magebug_Productoptions.xml to activate the module:
Here is code :

<config>
  <modules>
    <Magebug_Productoptions>
      <active>true</active>
      <codePool>local</codePool>
    </Magebug_Productoptions>
  </modules>

</config>

3. Create a file named app/local/Magebug/Productoptions/ect/config.xml with the following content

<?xml version="1.0"?>
<config>
    <modules>
        <magebug_productoptions>
            <version>1.0.0</version>
        </magebug_productoptions>
    </modules>
    <frontend>
        <routers>
            <productoptions>
                <use>standard</use>
                <args>
                    <module>Magebug_Productoptions</module>
                    <frontName>productoptions</frontName>
                </args>
            </productoptions>
        </routers>
        <layout>
            <updates>
                <productoptions>
                    <file>productoptions.xml</file>
                </productoptions>
            </updates>
        </layout>
    </frontend>
    <global>
        <blocks>
            <productoptions>
                <class>Magebug_Productoptions_Block</class>
            </productoptions>
        </blocks>
    </global>
</config>

4. Create a file named app/local/Magebug/Productoptions/Block/Productoptions.php to overwrite the block of Mage_Catalog_Block_Product_List with the following content:

<?php
class Magebug_Productoptions_Block_Productoptions extends Mage_Catalog_Block_Product_List {

    public function getPriceJsonConfig($product) {
        $config = array();
        if (!$product->getTypeInstance(true)->hasOptions($product)) {
            return Mage::helper('core')->jsonEncode($config);
        }

        $_request = Mage::getSingleton('tax/calculation')->getDefaultRateRequest();
        $_request->setProductClassId($product->getTaxClassId());
        $defaultTax = Mage::getSingleton('tax/calculation')->getRate($_request);

        $_request = Mage::getSingleton('tax/calculation')->getRateRequest();
        $_request->setProductClassId($product->getTaxClassId());
        $currentTax = Mage::getSingleton('tax/calculation')->getRate($_request);

        $_regularPrice = $product->getPrice();
        $_finalPrice = $product->getFinalPrice();
        if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
            $_priceInclTax = Mage::helper('tax')->getPrice($product, $_finalPrice, true, null, null, null, null, null, false);
            $_priceExclTax = Mage::helper('tax')->getPrice($product, $_finalPrice, false, null, null, null, null, null, false);
        } else {
            $_priceInclTax = Mage::helper('tax')->getPrice($product, $_finalPrice, true);
            $_priceExclTax = Mage::helper('tax')->getPrice($product, $_finalPrice);
        }
        $_tierPrices = array();
        $_tierPricesInclTax = array();
        foreach ($product->getTierPrice() as $tierPrice) {
            $_tierPrices[] = Mage::helper('core')->currency(
                    Mage::helper('tax')->getPrice($product, (float) $tierPrice['website_price'], false) - $_priceExclTax
                    , false, false);
            $_tierPricesInclTax[] = Mage::helper('core')->currency(
                    Mage::helper('tax')->getPrice($product, (float) $tierPrice['website_price'], true) - $_priceInclTax
                    , false, false);
        }
        $config = array(
            'productId' => $product->getId(),
            'priceFormat' => Mage::app()->getLocale()->getJsPriceFormat(),
            'includeTax' => Mage::helper('tax')->priceIncludesTax() ? 'true' : 'false',
            'showIncludeTax' => Mage::helper('tax')->displayPriceIncludingTax(),
            'showBothPrices' => Mage::helper('tax')->displayBothPrices(),
            'productPrice' => Mage::helper('core')->currency($_finalPrice, false, false),
            'productOldPrice' => Mage::helper('core')->currency($_regularPrice, false, false),
            'priceInclTax' => Mage::helper('core')->currency($_priceInclTax, false, false),
            'priceExclTax' => Mage::helper('core')->currency($_priceExclTax, false, false),
            /**
             * @var skipCalculate
             * @deprecated after 1.5.1.0
             */
            'skipCalculate' => ($_priceExclTax != $_priceInclTax ? 0 : 1),
            'defaultTax' => $defaultTax,
            'currentTax' => $currentTax,
            'idSuffix' => '_clone',
            'oldPlusDisposition' => 0,
            'plusDisposition' => 0,
            'plusDispositionTax' => 0,
            'oldMinusDisposition' => 0,
            'minusDisposition' => 0,
            'tierPrices' => $_tierPrices,
            'tierPricesInclTax' => $_tierPricesInclTax,
        );

        $responseObject = new Varien_Object();
        Mage::dispatchEvent('catalog_product_view_config', array('response_object' => $responseObject));
        if (is_array($responseObject->getAdditionalOptions())) {
            foreach ($responseObject->getAdditionalOptions() as $option => $value) {
                $config[$option] = $value;
            }
        }

        return Mage::helper('core')->jsonEncode($config);
    }

    public function getViewTypeConfigurableBlock($product) {
        $block = new Mage_Catalog_Block_Product_View_Type_Configurable();
        $block->setData('product', $product);
        return $block;
    }

    public function getProductId() {
        $productid = $this->getData('product_id');
        return explode(',', $productid);
    }
}

5. Create 2 javascript files named js/productoptions/product.js and js/productoptions/configurable.js

(Download attached
)


6. Create layout xml file and add the javascript file
Path :: app/design/frontend/default/default/layout/productoptions.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <productoptions_index_index>
        <reference name="head">
            <action method="addJs"><script>productoptions/product.js</script></action>
            <action method="addJs"><script>productoptions/configurable.js</script></action>
        </reference>
        <reference name="content">
            <block type="productoptions/productoptions" name="productoptions" template="productoptions/productoptions.phtml"/>
        </reference>
    </productoptions_index_index>
</layout>

7. Create phtml file and put below code
Path :: app/design/frontend/base/default/template/productoptions/productoptions.phtml

<?php
//Load product collection by product id
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('status',1);
if(!empty($collection)){
?>
<div class="category-product-main">
<ul>
<?php
foreach ($collection as $_product):
?>
<li>
<h3><a href="<?php echo $_product->getProductUrl();?>"><?php echo $_product->getName();?></a></h3>
<span>
<a href="<?php echo $_product->getProductUrl()?>" title="<?php echo $_product->getName()?>">
<img src="<?php echo Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150, 150); ?>" alt="<?php echo $_product->getName()?>" />
</a>
</span>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>" enctype="multipart/form-data">

<?php echo $this->getPriceHtml($_product, true) ?>

<?php
if($_product->isSaleable() && $_product->getTypeId() == 'configurable') {
$product = Mage::getModel('catalog/product')->load($_product->getId());
$block = $this->getViewTypeConfigurableBlock($product);
$_attributes = Mage::helper('core')->decorateArray($block->getAllowAttributes());
?>
<?php if (count($_attributes)): ?>
<dl>
<?php foreach($_attributes as $_attribute): ?>
<dt><label><?php echo $_attribute->getLabel() ?></label></dt>
<dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
<div class="input-box">
<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select-<?php echo $_product->getId() ?>">
<option><?php echo $this->__('Choose an Option...') ?></option>
 </select>
 </div>
</dd>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var spConfig_<?php echo $_product->getId() ?> = new Product.Config(<?php echo $block->getJsonConfig() ?>, <?php echo $_product->getId() ?>, new Product.OptionsPrice(<?php echo $this->getPriceJsonConfig($product) ?>));
</script>
<?php endif;?>
<?php } ?>

<?php if($_product->isSaleable()): ?>
<div class="buy-add-to-cart">
<div class="qty-wrapper">
<label for="qty"><?php echo $this->__('Qty:') ?></label>
<input type="text" class="input-text qty" title="<?php echo $this->__('Qty') ?>" value="<?php echo ($this->getMinimalQty($_product)?$this->getMinimalQty($_product):1) ?>" maxlength="12" name="qty">
</div>
<div class="add-to-cart-buttons">
<button onclick="this.form.submit()" class="button btn-cart" title="<?php echo $this->__('Buy') ?>" type="button"><span><?php echo $this->__('Buy') ?></span></button>
</div>
</div>
<?php endif; ?>
</form>
</li>
<?php endforeach;?>
</ul>
</div>
<?php }?>

Now Flush Magento Cache and refresh page.


We hope my suggestion is useful enough for you to solve the product options issue. We highly appreciate your comment and continuous contribution to this techniques library.
You can download full source here Magebug_Productoptions