Author: Time4Thilwayi

I completed my MS Bioinformatics from University of Manchester, but I still can't forget the memories of my time when my all friends, every evening used to laugh chat and talk together. Although I am miles away from my land but the spirit of dewasian is still in me. That life without stress, the work without load which always keep holding a sense of relax on my face. I wish we could again regain that life just by staying together by sharing our thoughts on current time, jokes, incidents and much more

Understanding $block->getChildHtml()

As I am learning magento, I had this issue from quite a while. Sometimes I was able to use $block->getChildHtml and sometimes not. So I asked help from my colleague Lee and he helped me to understand the whole concept of $block->getChildHtml();
Supposably I want to display this block in one of my view which block of class ‘Title’

echo $block->getChildHtml('sudeep_block');

So in layout file I have to define this as follows

<!-- page title -->
<block class="Vendor\Product\Block\Html\Title" name="page.main.title"
       template="Magento_Catalog::product/view/title.phtml">
    <block class="Vendor\Product\Block\Html\Title" name="product.info.sudeep.block" as="sudeep_block"
           template="Magento_Catalog::product/view/sudeep_block.phtml"/>

</block>


If I don’t put this within <block class=”Vendor\Product\Block\Html\Title”  it will not appear correctly. This is because, we are calling child HTML of this block
Thats the reply from my colleague Lee
“the problem with putting things in the product.info.main container is that its just a container and things are ordered within that container based on the before and after elements that are added in the xml – it just prints all the blocks out that are set.
I’ve moved it into the title block – this sets it as a child, so you can either call ->getChildHtml() – that will pull all child elements in that block
or ->getChildHtml(‘name-of-block’) – and that will call the specific block that you want
if its available obviously!”
Advertisements

Magento 2 add static block in Layout XML

Here is a quick way on how to add static cms block in the layout

Display CMS Static Block In Phtml File:

Here the code to show CMS Static Block in any template (phtml) file in Magento 2,



->createBlock('Magento\Cms\Block\Block')
->setBlockId('block_identifier')
->toHtml();
?>

Display CMS Static Block In CMS Content:

Here the code to show CMS Static Block in any other CMS static block/page in Magento 2,


{{block class="Magento\\Cms\\Block\\Block" block_id="block_identifier"}}

Display CMS Static Block In XML:
Here the code to show CMS Static Block in any layout (XML) file in Magento 2,

 

<referenceContainer name="content"> 
<block class="Magento\Cms\Block\Block" name="block_identifier"> 
<arguments> 
<argument name="block_id" xsi:type="string">block_identifier</argument> 
</arguments> 
</block> 
</referenceContainer>

 

 

Thanks to info at http://www.blogtreat.com/magento-2-how-to-call-cms-static-block-in-phtml-file/

Magento 2 admin catalog product edit form – categories order

I have recently been doing some developments in Magento 2 and have found out some inconsistency in the product edit form in the admin section.

The desired sort order of the category should be the default position one. However in the product edit admin catalog product edit form, the sort order is not defined therefore, it appears in the way it is returned from the database. This is not very user-friendly especially if you have about 4000 categories to deal with.

Magento 2 admin product edit form category sort order - backend Magento 2 natural - original  category sort order - frontend
admin catalog product edit form – categories order categories order on frontend

Thus to obtain same layout, we have made changed in following pre. You can also create pre pool and add the pre there, but this is a quick fix

My Magento version is community 2.2.6

Open

vendor/magento/module-catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php

Go to line 375 and add the following code

$collection->addAttributeToSort('position');

Make sure to add this line before

foreach ($collection as $category) {.

So the final code should look like as follows



$collection->addAttributeToSort('position');

        foreach ($collection as $category) {
            foreach ([$category->getId(), $category->getParentId()] as $categoryId) {
                if (!isset($categoryById[$categoryId])) {
                    $categoryById[$categoryId] = ['value' => $categoryId];
                }
            }

            $categoryById[$category->getId()]['is_active'] = $category->getIsActive();
            $categoryById[$category->getId()]['label'] = $category->getName();
            $categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];
        }

        $this->getCacheManager()->save(
            $this->serializer->serialize($categoryById[CategoryModel::TREE_ROOT_ID]['optgroup']),
            self::CATEGORY_TREE_ID . '_' . $filter,
            [
                \Magento\Catalog\Model\Category::CACHE_TAG,
                \Magento\Framework\App\Cache\Type\Block::CACHE_TAG
            ]
        );

        return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];

Thus my final version looks as following

Magento 2 quick check list before going live

Hello all

I have been working on Magento2 from quiet a while and getting my hands on its development & deployment. I know it always happens when you develop or customise something and keep on refreshing the page, but you does not get the desired results.

Therefore I have created a quick checklist to make sure all boxes are ticked before you go live. I have also included the commands so that its handy to run them in order

Production mode is enabled

php bin/magento deploy:mode:set production

Cache is first flushed and then enabled

php bin/magento cache:clean
php bin/magento cache:enable

Static contents have been deployed

 php bin/magento setup:static-content:deploy

var folder persmissions

chmod -R 777 var

pub folder persmissions

chmod -R 777 pub

Static contents have been deployed

 php bin/magento setup:static-content:deploy

Catalog has been reindexed

 php bin/magento indexer:reindex

Sql queries to use Alias in where – alternative

I have been working on SQL queries. Now the scenario is as follows.

what if you wanted to compare the alias in WHERE. By mysql rules, you cannot use Alias in WHERE. However, you can use alias to filter the results using HAVING. The difference between WHERE and HAVING clause is that you can use WHERE in UPDATE or DELETE clause, while HAVING is only used when to filter the results

I have one to many relationships in table (lets say we have items at multiple locations).

Now I have to pull a low stock report where total item quantities at multiple locations is less than threshold. Thus I have to sum the total quantities at multiple locations on fly and compare it with recommended minimum level of quantities.

I am sure there could be other problems to this approach but I have used the following code.

 

   SELECT
item.id as master_item_id,
item.name as item_name,
supplier.name as supplier_name,
item.recommended_lowest_quantity as min_level,
(SELECT SUM(quantity_out) FROM item_outbound WHERE item_outbound.item_id=item.id AND item_outbound.status_id IN  (6, 7 , 12, 20 ,21)) as total_qty,
item_outbound.quantity_out as location_qty,
item_outbound.id as outbound_id,
location.name as location_name,
status.name as status_name
FROM item
LEFT JOIN item_outbound ON item.id=item_outbound.item_id
LEFT JOIN supplier ON supplier.id=item.primary_supplier_id
LEFT JOIN location ON location.id=item_outbound.location_id
LEFT JOIN status ON status.id=item_outbound.status_id
WHERE item.active=1
AND item_outbound.status_id IN (6, 7 , 12, 20 ,21)
HAVING total_qty <min_level
ORDER BY `master_item_id` ASC

Regular expressions

Some handy regular expressions terms

If you want to remove only specific tags from the html, you can use following regular expression. I use it along with PHP storm.

For example here is my sample code

    <a href="/samplelink/5656/565">
        <i class="fa fa-trash-o fa-2x" aria-hidden="true"></i>
    </a>
    <a href="/samplelink/21112/21">
        <i class="fa fa-trash-o fa-2x" aria-hidden="true"></i>
    </a>
    <a href="/samplelink/99/997"> 
        <i class="fa fa-trash-o fa-2x" aria-hidden="true"></i>
    </a>

if you want to replace all a tags

<a href="/samplelink/99/997">

I will use the following code in regular expressions to find

<a href=".*?"\s*[/>]* 

Calling controller from a View in Yii

There are two ways to call a controller from a view.

$this->forward('/enggdiary/optimiseroutebygoogleapi',true, array('engineer_id'=>$isAdmin));?>

OR

 

if(($ca=Yii::app()->createController('enggdiary'))!==null){
 list($controller,$actionID)=$ca;
 $controller->init();
 $controller->renderPartial('optimiseroutebygoogleapi',array(
 'engineer_id'=>$model->engineer_id,
 'route_date_string'=>$route_date_string,
 'route_date_time'=>$route_date_time,
 'route_map_results'=>$route_map_results,

'planroute'=>'0',

));
 }

Redirecting all URLs to .com rather than .biz, .co.uk, .info

I was having this problem with my current site. I have several domains like

ukwhitegoods.biz

ukwhitegoods.co

ukwhitegoods.co.uk

ukwhitegoods.com

ukwhitegoods.eu

ukwhitegoods.info

ukwhitegoods.me.uk

Even the problem was Google was indexing all these pages separately and which is not good from the SEO perspective. Therefore, we

This thing is also called as CANONICAL DOMAIN

I used the following code to force all URLs to go to .co.uk

RewriteBase /
 
RewriteCond %{HTTP_HOST} !^(www\.)?ukwhitegoods\.co\.uk$ [NC] ////This means was anything other than this pattern is fired, follow the rule

///NC means case sensitive URL
RewriteRule ^(.*)$ http://www.ukwhitegoods.co.uk/$1 [R=301,L] ////Its a permanent redirect and LAST RULE

So now all my landing pages goes to ukwhitegoods.co.uk