Get the first li or ul element value using jQuery

jQuery('.ul').first().text()

Advertisements

Redirect http to https through htaccess

Sometimes, you might need to redirect all the HTTP version of the pages to HTTPS. This can be achieved by placing this code in your website .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Get the total table count in MySQL

While using MySQL database, sometimes we may need to know the table tables count in a particular table using Structured Query Language (SQL). Here is the SQL query you can use for that:

SELECT count(*) as 'Tables', table_schema as 'Database'
FROM information_schema.TABLES
WHERE table_schema= "database_name"
GROUP BY table_schema

In the above query, change the database_name to the actual database name you would like to know the total tables count.

Prevent Page reloading to display error message when adding product to cart

Sometimes, you may don’t like how Magento works. For instance, if you are trying to add the grouped product to your cart, it loads the page just to display the error message “The fewest you may purchase is 2”. To avoid this you need to override catalog-add-to-cart.js file from module-catalog to your theme directory.

Go to the ajaxsubmit function and success and catch the if condition: if (res.backUrl). There are these two lines:
window.location = res.backUrl;
return;

Just remove them and add customerData.reload(‘messages’); so the if condition looks like:

if (res.backUrl) {
customerData.reload(‘messages’);
}

At the top of the file, you need to add two more files and pass it inside the function. So the changes will look like:

define([
‘jquery’,
‘mage/translate’,
‘jquery/ui’,
‘Magento_Customer/js/customer-data’,
‘jquery/jquery-storageapi’
], function($, $t, _, customerData) {

and yes you are done. Now, flush the cache, remove pub/static/frontend content and redeploy and recompile(if you are in production mode) to see the changes. Now the error message will appear without the page load.

Happy coding,
-Gideon

How to have the new arrival sorting work for current date products, past products, future products and empty date set

Override block file from vendor/module-catalog/Block/Product/ProductList/Toolbar.php into your custom module and for new arrival, case add the following lines of code:


case 'new_arrival':

$now = new \DateTime();
$currentdate =clone $collection;
$pastdate =clone $collection;
$futuredate =clone $collection;
$emtpydate = clone $collection;

$currentDate = $currentdate->addAttributeToFilter('news_from_date', ['eq' => $now->format('Y-m-d')]);
$pastDate = $pastdate->addAttributeToFilter('news_from_date', ['lt' => $now->format('Y-m-d')])->setOrder('news_from_date', 'desc');
$futureDate = $futuredate->addAttributeToFilter('news_from_date', ['gt' => $now->format('Y-m-d')])->setOrder('news_from_date', 'asc');;
$emptyDate = $emtpydate->addAttributeToFilter('news_from_date', array('null' => true));

$productIds = array_merge($currentDate->getColumnValues('entity_id'), $pastDate->getColumnValues('entity_id'), $futureDate->getColumnValues('entity_id'), $emptyDate->getColumnValues('entity_id'));

$this->_collection->addAttributeToFilter('entity_id', array('in' =>$productIds));
$this->_collection->getSelect()->order(
new \Zend_Db_Expr('FIELD(e.entity_id, ' . implode(',', $productIds).')') // to keep the sorting by array
);

break;

Overriding core Js file in Magento 2

To override Magento default core js file, you need to copy that file. For instance, if we want to override lib/web/mage/menu.js file, we need to copy that file and paste is in your theme folder. So the file location would be like this app/design/frontend/[vendor name]/[theme name]/web/js/mage.js

Now, you need to add the location in require js config file under your theme folder. The file location is app/design/frontend/[vendor name]/[theme name]/requirejs-config.js.

Please add a new line inside map config like this:

var config = {
 "map": {
   "*": {
     "menu": "/js/menu",
   }
 }
};

Please do static content deployment after this for changes to take effect.

Select first swatches automatically in Magento 2

You have to override the swatch-renderder.js file into your theme from module-swatches and add a small script the_init() function of $.widget(‘mage.SwatchRenderer’).

This should be the location of the overriden file
app/design/frontend/Vendor/themename/Magento_Swatches/web/js/swatch-renderer.js

So the new function should look like this:


_init: function () {
if (_.isEmpty(this.options.jsonConfig.images)) {
this.options.useAjax = true;
// creates debounced variant of _LoadProductMedia()
// to use it in events handlers instead of _LoadProductMedia()
this._debouncedLoadProductMedia = _.debounce(this._LoadProductMedia.bind(this), 500);
}

if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
// store unsorted attributes
this.options.jsonConfig.mappedAttributes = _.clone(this.options.jsonConfig.attributes);
this._sortAttributes();
this._RenderControls();

//custom script to select swatches automatically
if($('body').hasClass('catalog-product-view')){
if (this.options.jsonConfig.attributes.length > 0) {
var selectswatch = this.element.find('.' + this.options.classes.attributeClass + ' .' + this.options.classes.attributeOptionsWrapper);
$.each(selectswatch, function (index, item) {
var swatchOption = $(item).find('div.swatch-option').first();
if (swatchOption.length && !$(item).find('div.swatch-option').hasClass('selected')) {
swatchOption.trigger('click');
}
});
}
}

this._setPreSelectedGallery();
$(this.element).trigger('swatch.initialized');
} else {
console.log('SwatchRenderer: No input data received');
}
this.options.tierPriceTemplate = $(this.options.tierPriceTemplateSelector).html();
},

Magento 2 get product attribute value

Here is the code to get a product attribute value using attribute code:

First we need to load the product using product ID like this:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get(‘Magento\Catalog\Model\Product’)->load($product_id);

then

we can use the following code to get the value of attribute with code (custom_attribute_code):

$value=$_product->getCustomAttributeCode();

Magento 2 Popup Modal

 </script type="text/javascript"> 
require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: 'Promotion Details',
                buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };

            var popup = modal(options, $('#popup-modal'));
   $('#promo-popup').click(function(){
                  $('#popup-modal').modal('openModal');
});
            
        }
    );
</script>

Create Product Attribute programmatically in Magento 2

Registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Namespace_Module,
__DIR__
);

etc/module.xml

<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”>
<module name=”Namespace_Module” setup_version=”1.0.0″>
<sequence>
<module name=”Magento_Catalog”/>
</sequence>
</module>
</config>

Setup/InstallData.php

<?php

namespace Namespace\Module\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\Catalog\Model\ResourceModel\Eav\Attribute;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory
*
* @var EavSetupFactory
*/
private $eavSetupFactory;

/**
* Init
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}

/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create([‘setup’ => $setup]);

/**
* Add attributes to the eav/attribute
*/
// attributes for text type and textarea
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
‘attribue_code’,
[
‘type’ => ‘varchar’,
‘backend’ => ”,
‘frontend’ => ”,
‘label’ => Attribute Label’,
‘input’ => ‘text’,
‘class’ => ”,
‘source’ => ”,
‘global’ => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
‘visible’ => true,
‘required’ => false,
‘user_defined’ => false,
‘default’ => ”,
‘searchable’ => false,
‘filterable’ => false,
‘comparable’ => false,
‘visible_on_front’ => false,
‘used_in_product_listing’ => false,
‘unique’ => false,
‘apply_to’ => ”
]
);

// for drop down attributes
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
‘attribute_code,
[
‘type’ => ‘varchar’,
‘backend’ => ”,
‘frontend’ => ”,
‘label’ => ‘Attribute Label’,
‘input’ => ‘select’,
‘class’ => ”,
‘source’ => ‘Dg\ProductAttributes\Model\Config\Source\Options’,
‘global’ => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
‘visible’ => true,
‘required’ => false,
‘user_defined’ => false,
‘default’ => ‘Core’,
‘searchable’ => false,
‘filterable’ => false,
‘comparable’ => false,
‘visible_on_front’ => false,
‘used_in_product_listing’ => false,
‘unique’ => false,
‘apply_to’ => ”
]
);

}
}

Model/Config/Source/Options.php

<?php

namespace Namespace\Modulename\Model\Config\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;

class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
/**
* @var OptionFactory
*/
protected $optionFactory;

/**
* @param OptionFactory $optionFactory
*/
/*public function __construct(OptionFactory $optionFactory)
{
$this->optionFactory = $optionFactory;
//you can use this if you want to prepare options dynamically
}*/

/**
* Get all options
*
* @return array
*/
public function getAllOptions()
{
/* your Attribute options list*/
$this->_options=[ [‘label’=>’Select Options’, ‘value’=>”],
[‘label’=>’Option 1’, ‘value’=>’1’],
[‘label’=>’Option 2’, ‘value’=>’2’]
];
return $this->_options;
}

/**
* Get a text for option value
*
* @param string|integer $value
* @return string|bool
*/
public function getOptionText($value)
{
foreach ($this->getAllOptions() as $option) {
if ($option[‘value’] == $value) {
return $option[‘label’];
}
}
return false;
}

/**
* Retrieve flat column definition
*
* @return array
*/
public function getFlatColumns()
{
$attributeCode = $this->getAttribute()->getAttributeCode();
return [
$attributeCode => [
‘unsigned’ => false,
‘default’ => null,
‘extra’ => null,
‘type’ => Table::TYPE_INTEGER,
‘nullable’ => true,
‘comment’ => ‘Custom Attribute Options  ‘ . $attributeCode . ‘ column’,
],
];
}
}