1

I am passing some params to JS in my custom module using the addScriptOptions provided by Joomla:

$document->addScriptOptions("mod_mymodule", $params));

This works fine, as long as there is only 1 instance of the same module on 1 page. But how to make it work for multiple modules on the same page?

I would think to pass 1 object like so:

$document->addScriptOptions("mod_mymodule", (object)array($params => $module->id)));

In my JavaScript file I can log the object:

console.log(Joomla.getOptions('mod_mymodule'));

// Output:
  {
  105: {...}
  }

So the problem is that only the first module is passed in the object. I need every module to be passed in the object before it is passed to my JS file, so I can loop over the object to create desired script for each module.

Addition: I think I'm getting closer, but still not working:

$currentOptions = $document->getScriptOptions('mod_mymodule');
if ($currentOptions) :
    $currentOptions->{$module->id}->{$params};
else :
    $document->addScriptOptions("mod_mymodule", (object)array($module->id => $params));
endif ;

I think the logic is there, or not? Syntax error? I'm not sure..

Any insights? Thanks!

2 Answers 2

3

A simple code review:

You don't need the condition block because getScriptOptions() always returns an array.

getScriptOptions() documentation

If you want to declare the variable $configs...

$configs = $document->getScriptOptions('mod_mymodule');
$configs[$module->id] = $params;
$document->addScriptOptions("mod_mymodule", $configs);

If you don't want to declare the variable...

$document->addScriptOptions(
    "mod_mymodule",
    array_replace(
        $document->getScriptOptions('mod_mymodule'),
        [$module->id => $params]
    )
);

Both snippets execute the same behaviour, here's what is happening...

  • If the returned array from getScriptOptions() already contains a key which matches the $module->id value, then the element will be overwritten.
  • If the key does not yet exist in the array, then the element will merely be added to the array.
1
  • Hah. Even better. Thanks for pointing that out! :)
    – TVBZ
    Commented Jun 18, 2020 at 12:28
1

Okay.. Found the solution. Here we go:

$configs = $document->getScriptOptions('mod_mymodule');

if ($configs) :
    $configs[$module->id] = $params;
else :
    $configs = array($module->id => $params);
endif ;

$document->addScriptOptions("mod_mymodule", $configs);

The logic wasn't that hard. I'm still pretty new at php and Joomla! development.

Hopefully it will be of some use to someone else. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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