Wednesday, November 25, 2015

Magento2: Search By Keyword is not working in admin grid of custom module

If your custom module is working fine with filter and other functions And you are facing issue with Search By Keyword functionality then this tips or answer will helpful to you.

Generally, this become happened due to missing of index creation for your module grid table.

You have to create a table index for faster searching mechanism for your grid table.

1. Open and edit your module's InstallSchema.php from <Vendor> /<ModuleName>/Setup/InstallSchema.php

At the end of table creation script/ table modify script add following code to create a table index.

Note: this example is for Fulltext index type.

1:  ->addIndex(  
2:                      $setup->getIdxName(  
3:                           $setup->getTable('table_name'),  
4:                           ['field1', 'field2', 'field2'],  
5:                           \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT  
6:                      ),  
7:                      ['field1', 'field2', 'field3'],  
8:                      ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT]  
9:                 )  
Note: You can apply this code to UpgradeSchema.php if you had created module finally.
2. You must check the filterSearch section is added into view/adminhtml/ui_component/xyz_listing.xml.  
Please update the relevant value with item 'provider', 'chipsProvider' & 'storageConfig'
 
Flush the cache and test your code.

Monday, November 23, 2015

Magento 2 sample module

You will get magento 2 sample module from https://github.com/tzyganu/Magento2SampleModule/

This sample module has been covered almost all the areas except 'Api' section.

It will helpful to learn to create a new module or debuging your existing module.

https://www.ashsmith.io/ this one have a good content with all technical information and easy to understand.

http://devdocs.magento.com/ is evergreen for all magento 2  backend, frontend, JavaScript & PHP developers. It is very helpful for beginners too.

Monday, November 16, 2015

Shortcut to perform commandline tasks for windows like clear cache.

you can do it using Batch program to delete it. Its to much faster than manually deletion of files.

Create a batch file in your magento root dir [you can place it another location too].

You can create batch file using .bat extension.

Right click on batch file and select edit [Open it into notepad] and Type following commands into that.
 
del /s /q "E:\wamp\www\magento2\var\cache\*.*"
del /s /q "E:\wamp\www\magento2\var\page_cache\*.*"

Set file path as per your folder location and save the file.

Create its shortcuts on desktop for fast access.

And assign shortcut key to these file shortcut. Refer following screenshot.

 Now whenever you will press Ctrl+Shift+C command from keyboard. This batch file will execute and will delete all your cache files.

How do add css and js files in custom module in magento2?

You can add CSS file as following way for your custom module.

Open you layout file e.g. modulename_index_view.xml and following code in <head> section.
 
1:  <head>      
2:    <css src="Test_New::css/my.css"/>  
3:  </head>  

to add custom module JS file you can use standard way as mentioned with below link.
How to load custom module js file in magento 2?

Optional suggestion (Optional)
You can use the standard way of Magento 2 to call css and js rather than Call CSS and JS files directly into layout file.
You can call JS using requirejs module. (You can maintain dependency of code.)

You may call css file using _module.less just put it under app\code\<Vendor>\<ModuleName>\view\frontend\web\css\source.
So It will call automatically as well as _module.less will compile by grunt tool and converted into your theme or module css

How to upgrade database schema in magento 2 ?

If you want to add more column into existing table of your module you could do following.
Step 1: Create UpgradeSchema.php under Setup folder. Get Idea from following code.

1:  namespace VendorName\ModuleName\Setup;  
2:  use Magento\Framework\Setup\UpgradeSchemaInterface;  
3:  use Magento\Framework\Setup\ModuleContextInterface;  
4:  use Magento\Framework\Setup\SchemaSetupInterface;  
5:  class UpgradeSchema implements UpgradeSchemaInterface  
6:  {  
7:    public function upgrade(SchemaSetupInterface $setup,  
8:                ModuleContextInterface $context){  
9:      $setup->startSetup();  
10:      if (version_compare($context->getVersion(), '1.0.1') < 0) {  
11:        // Get module table  
12:        $tableName = $setup->getTable('table_name');  
13:        // Check if the table already exists  
14:        if ($setup->getConnection()->isTableExists($tableName) == true) {  
15:          // Declare data  
16:          $columns = [  
17:            'imagename' => [  
18:              'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,  
19:              'nullable' => false,  
20:              'comment' => 'image name',  
21:            ],  
22:          ];  
23:          $connection = $setup->getConnection();  
24:          foreach ($columns as $name => $definition) {  
25:            $connection->addColumn($tableName, $name, $definition);  
26:          }  
27:        }  
28:      }  
29:      $setup->endSetup();  
30:    }  
31:  }  
 
Step 2: Change the setup_version value in module.xml

Step 3: Run php bin/magento setup:upgrade command from CLI.

How we can create unit tests to everything we have created for our custom module in Magento 2 ?

Hey!! We're working on tutorials..

How we can print array variable in log file of Magento 2 ?

In Magento 1.x, it was possible using Mage::log(print_r($arr, 1), null, 'logfile.log');

Consider following is your class file. 

class abc extends xyz
{
    protected $_logger;

    public function __construct(\Psr\Log\LoggerInterface $logger) {
        $this->_logger = $logger;
    }

 
     private function getValuesAsHtmlList(\Magento\Framework\Object $object) {
        $options = $this->getOptions($object);
//        $this->_logger->log(100,null,$options);
        $this->_logger->log(100,print_r($a,true)); //alternate method to print array as in structure form.
    }
 }

Now,open /var/debug.log file and check.

How to load custom module js file in magento 2 ?


Step 1: Add your module js file under <Vendor>/<Module_Name>/view/<area>/web/js/
e.g. <Vendor>/<Module_Name>/view/<area>/web/js/flexslider.js

Step 2: Create requirejs-config.js file under <Vendor>/<Module_Name>/view/<area>/
e.g. <Vendor>/<Module_Name>/view/<frontend>/requirejs-config.js
Add following code to  requirejs-config.js
var config = {
    map: {
        '*': {
            bannerslider: 'VendorName_ModuleName/js/flexslider'
        }
    }
};
 
Note: you may set your object name as per your choice. In my case I have set as bannerslider and do not add the .js extension to file name in VendorName_ModuleName/js/flexslider

Step 3: Call the function of your module js in .phtml file as following manner.
 
<script type="text/javascript">
    require(['jquery','bannerslider'],function($){
        $(window).load(function() {
            $('.flexslider-8').flexslider({
                animation: "fade",
                controlNav: "thumbnails",
                slideshowSpeed: 2000,
                minItems: 2,
                maxItems: 4
            });
        });

    });
</script>
Its working fine for me.
Trace : Use Net tab to see requested URL of js file loaded or not.


Note: better to use 'domReady!' plugin instead of $(window).load(), for example require(['jquery','bannerslider', 'domReady!],function($) { ...code execute only after dom load}) 

How to call a PHTML file within a CMS page Magento 2 ?

To call a phtml file in a cms page or cms static block:

{{block class="Magento\Framework\View\Element\Template" template="PackageName_ModuleName::your_template.phtml"}}
 
If you know, where the block file(php file) for your phtml file resides, then you can use it as type.
Example: Suppose you want to call new.phtml file that resides in catalog/product folder, and you know that its corresponding Block file(php file) resides in Catalog/Product folder, then you can use:

{{block class="Magento\Framework\View\Element\Template" template="PackageName_ModuleName::catalog/new.phtml"}}
 
 
 

How to add custom/new theme name to grunt CLI command to run grunt tool in Magento 2 ?

When you cloned new theme from existing parent theme in Magento 2. How you can execute less:newThemName command using grunt CLI ?
As well as how grunt watch will look any changes into newly created theme ?

Don't worry you can do it easily using following steps.

Goto \dev\tools\grunt\configs, Open themes.js and add the part as shown in the image.


Now Open less.js and add the part shown in the image.


 Now you can run grunt less:luma2 task, and it will generate the pub static files for the theme

when ever you add new theme, you will need to add its details to the to files mentioned above.

Error 404 not found at magento 2 admin login page after migrated to another system

This is a general error, usually occurs when you transfer your magento-2 installation from one location to another. The reason behind this error is that the value store_id and website_id for the admin should be 0 , but when you import the database to a new server, somehow these values are not set to 0.
So to solve this error you will need to make some changes in the database tables itself.


SET FOREIGN_KEY_CHECKS=0; 
UPDATE store SET store_id = 0 WHERE code='admin'; 
UPDATE store_group SET group_id = 0 WHERE name='Default'; 
UPDATE store_website SET website_id = 0 WHERE code='admin'; 
UPDATE customer_group SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN'; 
SET FOREIGN_KEY_CHECKS=1;

How to redirect non-www URLs to www?

In order to redirect all of the requests for example.com to www.example.com, you should set the appropriate rewrite rule. This can be done by adding the following lines at the beginning of the .htaccess file in your public_html folder:


RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

From now on, when someone accesses http://example.com he/she will be redirected to http://www.example.com.