Render Javascript on customer_login event












4















I'm trying to render some javascript when the customer_login event fires by accessing a block on the layout from within the observer.



I've successfully registered my observer to execute with the event and that works fine.



The problem I'm running into is that when I attempt to access a specific block object from within the observer the layout does not contain any block elements.



I'm mimicking code that I've seen in the magento2 google analytics plugin that sets a value on a block object from an observer registered on the checkout_onepage_controller_success_action event.



My guess for why this isn't working is that this event fires before any of the block elements are initialized and registered with the layout.



If this is the case and my current approach is not a valid one how would I go about rendering some javascript when this event fires?



etc/frontend/events.xml:



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="login_success" instance="CompanynameRevjsObserverSetCompanynameLoginSuccessObserver" />
</event>
</config>


Observer/SetCompanynameLoginSuccessObserver.php:



<?php

namespace CompanynameRevjsObserver;

use MagentoFrameworkEventObserver as EventObserver;
use MagentoFrameworkEventObserverInterface;

class SetCompanynameLoginSuccessObserver implements ObserverInterface
{
/**
* @var MagentoFrameworkViewLayoutInterface
*/
protected $layout;

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

public function execute(EventObserver $observer)
{
$email = $observer->getEvent()->getCustomer()->getEmail();

if (!$email) {
return;
}

// this call returns false rather than a block object
$block = $this->layout->getBlock('companyname');
$block->setEmail($email);
}
}


view/frontend/layout/default.xml:



<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="after.body.start">
<block class="CompanynameRevjsBlockRv" name="companyname" as="companyname" template="rv.phtml"/>
</referenceContainer>
</body>
</page>


Block/Rv.php:



namespace CompanynameRevjsBlock;

class Rv extends MagentoFrameworkViewElementTemplate
{
public function getEmailJsFunction()
{
$email = $this->getEmail();
if ($email) {
return sprintf("someJsFunction('%s');", $email);
} else {
return '';
}
}
}


view/frontend/templates/rv.phtml:



<script>
<?php echo $block->getEmailJsFunction(); ?>
</script>









share|improve this question
















bumped to the homepage by Community 6 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • anyone got solution for this?

    – Shivam
    Jun 1 '16 at 14:05
















4















I'm trying to render some javascript when the customer_login event fires by accessing a block on the layout from within the observer.



I've successfully registered my observer to execute with the event and that works fine.



The problem I'm running into is that when I attempt to access a specific block object from within the observer the layout does not contain any block elements.



I'm mimicking code that I've seen in the magento2 google analytics plugin that sets a value on a block object from an observer registered on the checkout_onepage_controller_success_action event.



My guess for why this isn't working is that this event fires before any of the block elements are initialized and registered with the layout.



If this is the case and my current approach is not a valid one how would I go about rendering some javascript when this event fires?



etc/frontend/events.xml:



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="login_success" instance="CompanynameRevjsObserverSetCompanynameLoginSuccessObserver" />
</event>
</config>


Observer/SetCompanynameLoginSuccessObserver.php:



<?php

namespace CompanynameRevjsObserver;

use MagentoFrameworkEventObserver as EventObserver;
use MagentoFrameworkEventObserverInterface;

class SetCompanynameLoginSuccessObserver implements ObserverInterface
{
/**
* @var MagentoFrameworkViewLayoutInterface
*/
protected $layout;

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

public function execute(EventObserver $observer)
{
$email = $observer->getEvent()->getCustomer()->getEmail();

if (!$email) {
return;
}

// this call returns false rather than a block object
$block = $this->layout->getBlock('companyname');
$block->setEmail($email);
}
}


view/frontend/layout/default.xml:



<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="after.body.start">
<block class="CompanynameRevjsBlockRv" name="companyname" as="companyname" template="rv.phtml"/>
</referenceContainer>
</body>
</page>


Block/Rv.php:



namespace CompanynameRevjsBlock;

class Rv extends MagentoFrameworkViewElementTemplate
{
public function getEmailJsFunction()
{
$email = $this->getEmail();
if ($email) {
return sprintf("someJsFunction('%s');", $email);
} else {
return '';
}
}
}


view/frontend/templates/rv.phtml:



<script>
<?php echo $block->getEmailJsFunction(); ?>
</script>









share|improve this question
















bumped to the homepage by Community 6 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • anyone got solution for this?

    – Shivam
    Jun 1 '16 at 14:05














4












4








4


1






I'm trying to render some javascript when the customer_login event fires by accessing a block on the layout from within the observer.



I've successfully registered my observer to execute with the event and that works fine.



The problem I'm running into is that when I attempt to access a specific block object from within the observer the layout does not contain any block elements.



I'm mimicking code that I've seen in the magento2 google analytics plugin that sets a value on a block object from an observer registered on the checkout_onepage_controller_success_action event.



My guess for why this isn't working is that this event fires before any of the block elements are initialized and registered with the layout.



If this is the case and my current approach is not a valid one how would I go about rendering some javascript when this event fires?



etc/frontend/events.xml:



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="login_success" instance="CompanynameRevjsObserverSetCompanynameLoginSuccessObserver" />
</event>
</config>


Observer/SetCompanynameLoginSuccessObserver.php:



<?php

namespace CompanynameRevjsObserver;

use MagentoFrameworkEventObserver as EventObserver;
use MagentoFrameworkEventObserverInterface;

class SetCompanynameLoginSuccessObserver implements ObserverInterface
{
/**
* @var MagentoFrameworkViewLayoutInterface
*/
protected $layout;

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

public function execute(EventObserver $observer)
{
$email = $observer->getEvent()->getCustomer()->getEmail();

if (!$email) {
return;
}

// this call returns false rather than a block object
$block = $this->layout->getBlock('companyname');
$block->setEmail($email);
}
}


view/frontend/layout/default.xml:



<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="after.body.start">
<block class="CompanynameRevjsBlockRv" name="companyname" as="companyname" template="rv.phtml"/>
</referenceContainer>
</body>
</page>


Block/Rv.php:



namespace CompanynameRevjsBlock;

class Rv extends MagentoFrameworkViewElementTemplate
{
public function getEmailJsFunction()
{
$email = $this->getEmail();
if ($email) {
return sprintf("someJsFunction('%s');", $email);
} else {
return '';
}
}
}


view/frontend/templates/rv.phtml:



<script>
<?php echo $block->getEmailJsFunction(); ?>
</script>









share|improve this question
















I'm trying to render some javascript when the customer_login event fires by accessing a block on the layout from within the observer.



I've successfully registered my observer to execute with the event and that works fine.



The problem I'm running into is that when I attempt to access a specific block object from within the observer the layout does not contain any block elements.



I'm mimicking code that I've seen in the magento2 google analytics plugin that sets a value on a block object from an observer registered on the checkout_onepage_controller_success_action event.



My guess for why this isn't working is that this event fires before any of the block elements are initialized and registered with the layout.



If this is the case and my current approach is not a valid one how would I go about rendering some javascript when this event fires?



etc/frontend/events.xml:



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="login_success" instance="CompanynameRevjsObserverSetCompanynameLoginSuccessObserver" />
</event>
</config>


Observer/SetCompanynameLoginSuccessObserver.php:



<?php

namespace CompanynameRevjsObserver;

use MagentoFrameworkEventObserver as EventObserver;
use MagentoFrameworkEventObserverInterface;

class SetCompanynameLoginSuccessObserver implements ObserverInterface
{
/**
* @var MagentoFrameworkViewLayoutInterface
*/
protected $layout;

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

public function execute(EventObserver $observer)
{
$email = $observer->getEvent()->getCustomer()->getEmail();

if (!$email) {
return;
}

// this call returns false rather than a block object
$block = $this->layout->getBlock('companyname');
$block->setEmail($email);
}
}


view/frontend/layout/default.xml:



<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="after.body.start">
<block class="CompanynameRevjsBlockRv" name="companyname" as="companyname" template="rv.phtml"/>
</referenceContainer>
</body>
</page>


Block/Rv.php:



namespace CompanynameRevjsBlock;

class Rv extends MagentoFrameworkViewElementTemplate
{
public function getEmailJsFunction()
{
$email = $this->getEmail();
if ($email) {
return sprintf("someJsFunction('%s');", $email);
} else {
return '';
}
}
}


view/frontend/templates/rv.phtml:



<script>
<?php echo $block->getEmailJsFunction(); ?>
</script>






magento2 event-observer blocks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 6 '16 at 15:29









Raphael at Digital Pianism

53.6k19112270




53.6k19112270










asked Apr 6 '16 at 15:28









r3vr3v

211




211





bumped to the homepage by Community 6 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 6 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • anyone got solution for this?

    – Shivam
    Jun 1 '16 at 14:05



















  • anyone got solution for this?

    – Shivam
    Jun 1 '16 at 14:05

















anyone got solution for this?

– Shivam
Jun 1 '16 at 14:05





anyone got solution for this?

– Shivam
Jun 1 '16 at 14:05










1 Answer
1






active

oldest

votes


















0














you cannot access the blocks in the layout because there are no blocks in the layout.

The customer_login event is dispatched on a POST action that does not have output.

TO overcome this, you can, in your observe, add just something to the session and in you block just check if there is that value in the session.

If there is, use it and remove it.






share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "479"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f109791%2frender-javascript-on-customer-login-event%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    you cannot access the blocks in the layout because there are no blocks in the layout.

    The customer_login event is dispatched on a POST action that does not have output.

    TO overcome this, you can, in your observe, add just something to the session and in you block just check if there is that value in the session.

    If there is, use it and remove it.






    share|improve this answer




























      0














      you cannot access the blocks in the layout because there are no blocks in the layout.

      The customer_login event is dispatched on a POST action that does not have output.

      TO overcome this, you can, in your observe, add just something to the session and in you block just check if there is that value in the session.

      If there is, use it and remove it.






      share|improve this answer


























        0












        0








        0







        you cannot access the blocks in the layout because there are no blocks in the layout.

        The customer_login event is dispatched on a POST action that does not have output.

        TO overcome this, you can, in your observe, add just something to the session and in you block just check if there is that value in the session.

        If there is, use it and remove it.






        share|improve this answer













        you cannot access the blocks in the layout because there are no blocks in the layout.

        The customer_login event is dispatched on a POST action that does not have output.

        TO overcome this, you can, in your observe, add just something to the session and in you block just check if there is that value in the session.

        If there is, use it and remove it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jun 17 '16 at 20:33









        MariusMarius

        164k28312663




        164k28312663






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f109791%2frender-javascript-on-customer-login-event%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Polycentropodidae

            Magento 2 Error message: Invalid state change requested

            Paulmy