2

I am using Magento 2 I want to display phtml some page only that i need to select backend. How to display selected page only?

class Selectpage implements \Magento\Framework\Option\ArrayInterface{

    /**
     * @var array
     */
    protected $options;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @param CollectionFactory $collectionFactory
     */
    public function __construct(
        CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * To option array
     *
     * @return array
     */
    public function toOptionArray()
    {
        if (!$this->options) {
            $this->options = $this->collectionFactory->create()->toOptionIdArray();
        }
        $extra_pages_list = array(
            array(
                'value' => 'catalog_category_view',
                'label' => 'Category Page',
            ),
            array(
                'value' => 'catalog_product_view',
                'label' => 'Product Page',
            ),
            array(
                'value' => 'checkout_cart_index',
                'label' => 'Shoopping Cart',
            ),
            array(
                'value' => 'checkout_index_index',
                'label' => 'Checkout',
            )
            );
        $allPages = array_merge($this->options,$extra_pages_list);
        return $allPages;
    }

my.phtml

 <?php 
$field = $this->getConfigValue('popup/general/page');
    $pages = explode(',',$field);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\Action\Context')->getRequest();
//echo $request->getFullActionName();exit;
$t1 = "default"; /* don't change this */
if ($request->getFullActionName() == 'catalog_category_view') {
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'catalog_product_view'){
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'checkout_cart_index'){
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'checkout_index_index'){
  $t1 = $request->getFullActionName();
}
elseif($this->getPageDetails()){
  $t1 = $this->getPageDetails();
}

?>


<?php 
  //$oN = '';
  //if(in_array($t1,$this->getOverlayPages())){
    //$oN = "one";
   // echo "ok";
    //echo $t1;
    //var_dump($this->getOverlayPages());
  /*}
  elseif($t1 && in_array($t1,$this->getOverlayPages('two'))){
    $oN = "two";
  }
  elseif($t1 && in_array($t1,$this->getOverlayPages('three'))){
    $oN = "three";
  }*/
?>


<?php if(in_array($t1,$this->getOverlayPages())):?>
<div style="display:none;" id="OverlayContent">
   <div class="overlay-contents">
      <h2 class="overlay-title"><?php echo $this->getTitle(); ?></h2>
      <?php echo $this->getStaticblockcontent();?>
   </div>
</div>

<script>
   jQuery(document).ready(function() {      
      jQuery(document).bind("mouseleave", function(e){
        if (e.pageY - jQuery(window).scrollTop() <= 1){  
        if(!readCookie('<?php echo $this->getCookieName();?>')){ //check cookie             
            if(!jQuery('.fancybox-wrap').length){                   
                jQuery.fancybox({
                    'width': '<?php echo $this->getWidth();?>',
                    'height': '<?php echo $this->getHeight();?>',
                    'transitionIn': 'fade',
                    'transitionOut': 'fade',
                    'showCloseButton': true,    
                    'fitToView'   : false,
                    'autoSize'    : false,
                    'fixed': false,
                    'href': "#OverlayContent",
                    'autoCenter': false,
                    'helpers'     : { 
                           'overlay' : {'closeClick': false}
                           }, 
                    'afterClose' : function(){
                        <?php if($this->getCookieExpireTime()){ ?>
                            createCookie('<?php echo $this->getCookieName();?>', 1, '<?php echo $this->getCookieExpireTime();?>');
                        <?php } ?>
                    }                        
                }); 
                }//cookie check                 
            }
        }   
     });  
        <?php if(!$this->getCookieExpireTime()){ ?>
            eraseCookie('<?php echo $this->getCookieName();?>');
        <?php } ?>
    });  



/**To create cookie**/
function createCookie(name, value, time) {
var time = parseInt(time);
    if (time) {
        var date = new Date();
        date.setTime(date.getTime() + (time * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
/**To read cookie**/
function readCookie(name) {
    var nameEQ = escape(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}
/**To erase cookie**/
function eraseCookie(name) {
    createCookie(name, "", -1);
}


</script>

<?php endif;?>

How to display ** Content ** in selected page's only ?

enter image description here

  • It's working for all page except cms page how to achive this – Magento 2 Oct 25 '16 at 18:09
3
+25

you can set condition in your block,
Here my block php file contains :

protected $_request;

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request,
    ...
) {
    ...
    $this->_request = $request;
    ...
}


public function isHomepage()
{

    if ($this->_request->getFullActionName() == 'cms_index_index') {
        return true;
    }
    return false;
}

And call that function in your .phtml file like this :

$isHome = $block->isHomepage();
if ($isHome)
{
       your page code...
}
1

For get page action you need to used something like this :

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request
) {
    ...
    $this->request = $request;
}

Then you can get the action name :

$action = $this->request->getFullActionName();

In your spacific case, you need to replace this line :

$request = $objectManager->get('Magento\Framework\App\Action\Context')->getRequest();

into this

$request = $objectManager->get('Magento\Framework\App\Request\Http')->getRouteName(); 
  • can you please tell me where i need to add – Magento 2 Oct 26 '16 at 6:40
  • I updated answer, please check. – Dhiren Vasoya Oct 26 '16 at 6:42
  • @Kothari IF above code help you, then mark as solution so other get help. – Dhiren Vasoya Oct 26 '16 at 6:46
  • How to check in if condition – Magento 2 Oct 26 '16 at 6:56
  • I want to show below div only selected page in backend – Magento 2 Oct 26 '16 at 6:57
0

A more elegant way in case you're dealing with a core block and don't want to rewrite it would be to use an event on the controller_action_predispatch event to set the t1 variable dynamically:

in etc/frontend/events.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="custom_module_observer" instance="Vendor\Module\Observer\MyObserver" />
    </event>
</config>

Then in Observer/MyObserver.php:

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class MyObserver implements ObserverInterface
{
    /**
     * @var \Magento\Framework\View\LayoutInterface
     */
    protected $_layout;

    /**
     * @param \Magento\Framework\View\LayoutInterface $layout
     */
    public function __construct(
        \Magento\Framework\View\LayoutInterface $layout
    ) {
        $this->_layout = $layout;
    }

    public function execute(EventObserver $observer)
    {
        $action = $observer->getEvent()->getRequest()->getFullActionName();
        $block = $this->_layout->getBlock('name_of_your_block');
        if ($block) {
            switch($action) {
                case "catalog_category_view":
                case "catalog_product_view":
                case "checkout_cart_index":
                case "checkout_index_index":
                    $block->setMyVariable($action);
                    break;
                default:
                    $block->setMyVariable("default");
                    break;
            }
            if ($pageDetails = $block->getPageDetails()) {
                 $block->setMyVariable($pageDetails);
            }
        }
    }
}

NB: don't forget to replace name_of_your_block with the name of your block in the layout.

Also double check that bit, as I don't know what getPageDetails does:

if ($pageDetails = $block->getPageDetails()) {
     $block->setMyVariable($pageDetails);
}

Finally, in your template you can replace:

$t1 = "default"; /* don't change this */
if ($request->getFullActionName() == 'catalog_category_view') {
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'catalog_product_view'){
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'checkout_cart_index'){
  $t1 = $request->getFullActionName();
}
elseif($request->getFullActionName() == 'checkout_index_index'){
  $t1 = $request->getFullActionName();
}
elseif($this->getPageDetails()){
  $t1 = $this->getPageDetails();
}

With:

$t1 = $block->getMyVariable();
  • What i need to add here (name_of_your_block ) it will work for my problem – Magento 2 Oct 28 '16 at 13:06
  • @Kothari you need to replace name_of_your_block with the name you defined for your block in your layout – Raphael at Digital Pianism Oct 28 '16 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.