0

I am trying to implement custom flash toy for website. To do this I have created custom module.

In custom module, I have created a block class. Block class contain the function to generate the Random digits.

Here is my block's Class Name:  WM_Jackson/Block/Index/Index

Random Id generator code in block:

/**
 * generate random number for player
 *
 * @return int
 */

public function playeridGenerator()
{   
     $ran = rand(10, 999999);
    return $ran;
}

This rando Id generator code works fine when I call my block in cms page using below code:

{{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" }}

But when I add multiple blocks on the same page, it generates the duplicate ids for all the blocks.

for example if I add block code 3 times, It shows flash player 3 times but it shows same id for 3players. Hence when user try to interact with Flash show, only first player works.

  {{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" }}
  {{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" }}
  {{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" }}

Above code renders output 3 times but block function playeridGenerator() is generating same number 3 times.

How can I generate Random numbers when calling blocks multiple times? Is there any native library in magento for this?

Any help would be appreciated.

0

I think it is happen for Full page.

I suggest that Use Private content concept or Call An Ajax post request to get content of this three block content. As Post request and private content request are non-cache request at magento 2.

Also, You can put block name

{{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" **name="jackson.flash.one"** }}
  {{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" **name="jackson.flash.two"** }}
  {{block class="WM\Jackson\Block\Index\Index" template="WM_Jackson::flash_elem.phtml" **name="jackson.flash.two"** }}
 

For generate randon string or number use

\Magento\Framework\Math\Random $mathRandom

See https://www.rakeshjesadiya.com/how-to-generate-random-string-or-number-in-magento-2/

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.