Magento 2 Basic Detail

Get Store Country and Name

Add this to your constructor:

public function __construct(
\Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
){
$this->countryInformation = $countryInformation;
$this->scopeConfig = $scopeConfig;
}

Then in your code:

$country = $this->countryInformation->getCountryInfo($countryid);
$countryname = $country->getFullNameLocale();

Magento 2 Print SQL Query

# Print SQL query of repository list
$this->creditmemoRepository->getList($searchCriteria)->getSelect()->assemble()

Magento 2 create custom customer attribute

In this article, we’ll see what’re customer attributes and how we add them programmatically in Magento 2.

To create customer custom attribute you need to one custom module. once the module is created you need to create

Step 1: Create setup file InstallData.php

Firstly, we will create the InstallData.php file:File: Magesam/Gstnumber/Setup/InstallData.php

<?php
namespace Magesam\Gstnumber\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;
use Magento\Customer\Api\CustomerMetadataInterface;
class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;
    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig       = $eavConfig;
    }
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup $this->eavSetupFactory
                     ->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'gst_number',
            [
                'type'         => 'varchar',
                'label'        => 'GST Number',
                'input'        => 'text',
                'required'     => false,
                'visible'      => true,
                'user_defined' => true,
                'position'     => 999,
                'system'       => 0,
            ]
        );
        $attribute $this->eavConfig
                     ->getAttribute(Customer::ENTITY, 'gst_number');
       $attribute->setData(
           'used_in_forms',
          ['adminhtml_customer''customer_account_edit',
           'customer_account_create']);
        $attribute->save();
         $eavSetup->
addAttributeToSet(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,null, 'gst_number');
    }
}

Step 4: Show Customer Attribute in Register form 

For showing this customer attribute on the registration page, we need to do the following things :

We will add our phtml files to ‘form.additional.info’ reference name using Magesam/Gstnumber/view/frontend/layout/customer_account_create.xml

<pagexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="form.additional.info">
<block class="Magento\Framework\View\Element\Template" name="gst_number" template="Magesame_Gstnumber::extra_field.phtml"/>
        </referenceContainer>
    </body>
</page>
Now, in the extra_field.phtml file, we will write the code to show the additional textbox:
<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */echo __('* Required Fields') ?>">
    <legend class="legend"><span><?php /* @escapeNotVerified */echo __('Additional Information') ?></span></legend><br>
<div class="field gst_number required">
  <label class="label" for="email"><span><?= $block->escapeHtml(__('GST Number')) ?></span>
</label>
<div class="control">
            <input type="text" name="gst_number" id="gst_number" title="<?php /* @escapeNotVerified */echo __('My Attribute') ?>" class="input-text" data-validate="{required:true}" autocomplete="off">
        </div>
    </div>
</fieldset>

Magento 1 Stop add cart product process

Mage::app()->getResponse()->setRedirect($store_product->getProductUrl());
Mage::getSingleton('checkout/session')->addError(Mage::helper('checkout')->__('Sorry, the price of this product has been updated. Please, add to cart after reviewing the updated price.'));
$observer->getControllerAction()->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);  

How to create mysql table in magetno 2 with all datatype

$installer = $setup;
$installer->startSetup();
$table = $installer->getConnection()->newTable(
$installer->getTable('deal')
)->addColumn(
'deal_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
array('identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true),
'Deal ID'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Product Id'
) ->addColumn(
'deal_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Deal Price'
)->addColumn(
'deal_qty',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'11',
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Deal Qty'
)->addColumn(
'date_from',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'Date From'
)->addColumn(
'date_to',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'Date To'
)->addColumn(
'time_from',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
array(),
'Time From'
)->addColumn(
'time_to',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
array(),
'Time To'
)->addColumn(
'qty_sold',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'11',
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Qty Sold'
)->addColumn(
'nr_views',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'11',
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Nr Views'
) ->addColumn(
'disable',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Disable'
)->addColumn(
'type',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'11',
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Type'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Status'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();

Magento 2 : How to add image in system configuration and get on frontend

Step 1 :
Add code in system.xml file.

<field id="loading_icon" translate="label comment" sortOrder="11" type="image" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Loading Bar</label>
<backend_model>Magento\Config\Model\Config\Backend\Image</backend_model>
<upload_dir config="system/filesystem/media" scope_info="1">emizen/ajaxscroll</upload_dir>
<base_url type="media" scope_info="1">emizen/ajaxscroll</base_url>
</field>

Step 2:
Create block file:

namespace Rb\Mcpn\Block;

use Magento\Store\Model\Store;

class Mcoupon extends \Magento\Framework\View\Element\Template {

public function __construct(\Magento\Backend\Block\Widget\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []) {
$this->_scopeConfig = $scopeConfig;
$this->_storeManager = $storeManager;

parent::__construct($context, $data);
}

public function getCustomConfigData(){
$basurl=$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$storeid=$this->_storeManager->getStore()->getId();
$imagedata= $this->_scopeConfig->getValue(
'sleekaccordian/rbmcpngp/loading_icon',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,$storeid
);
return $basurl.'emizen/ajaxscroll/'.$imagedata;
}

}

Step 3 :
Get on phtml :

$imageurl=$data=$this->getCustomConfigData();

Magento Sending email with custom module

 In my new post i would like to discuss how send email with 
magento default template in custom module.Pretty often we 
need to have ability that allows us to notify customers or 
admins about some events, so it'w very important part of
 module developments. Let'sstart. 

     Step 1 :  First of all we need to put bellow code in our module's config.xml

     <template>
    <email>
        <demo_email_template translate="label" module="demo">
            <label>Magesam Email</label>
            <file>custom_email_template.html</file>

        </demo_email_template>
    </email>
    </template>

    Step 2 : Now we need to create one model  in your custome module
 which extends <b>Mage_Core_Model_Email_Template</b>

    class Atwix_Module_Model_Email extends Mage_Core_Model_Email_Template
    {

        /**
         * Send email to recipient
         *
         * @param string $templateId template identifier (see config.xml to know it)
         * @param array $sender sender name with email ex. array('name' => 'John D.', 'email' => 'email@ex.com')
         * @param string $email recipient email address
         * @param string $name recipient name
         * @param string $subject email subject
         * @param array $params data array that will be passed into template
         */
        public function sendEmail($templateId, $sender, $email, $name, $subject, $params = array())
        {
            $this->setDesignConfig(array('area' => 'frontend', 'store' => $this->getDesignConfig()->getStore()))
                ->setTemplateSubject($subject)
                ->sendTransactional(
                    $templateId,
                    $sender,
                    $email,
                    $name,
                    $params
            );
        }
    }

    Step 3 : Don’t miss one more important thing — creating 
email template. So it will be our next step, as template 
should be placed into app/locale/{locale_Code}/
template/email/, where {locale_Code} is current/default 
locale of your store, and in this case template has name
 app/locale/en_US/template/email/atwix_email_template.html.
 Notice for yourself, $params argument in the sendEmail
 function is located in the model. Using this variable 
we can pass data into template.How does it work? If 
you want to send some value into template, for example 
first name and last name, you should init $params 
variable see below: 

    $params = array(
    'firstname' => 'John',
    'lastname'  => 'D.'
    );

    and after this just call it in the template using specific way:

    Hello {{var firstname}} {{var lastname}}

    Step 4 : And final, show you function calling that you can use everywhere: 

    Mage::getModel('demo/email')->sendEmail(
    'custom_email_template',
    array('name' => 'John', 'email' => 'from@test.com'),
    'to@test.com',
    'Test',
    'Test Email',
    array('value' => 'Demo')
    );