Pass an object from controller to JavaScript

Silverstripe Version: 4.0.1

Question:

Hi,

How do I pass an object from controller to javascript. I have used the code below but it only works for variables.

        Requirements::customScript("var a = 'test'");

Without knowing what you’re actually trying to do, it’s hard to be too specific, but there are a couple of techniques available:

To take specific data from (for example) a member object, you can just use the normal PHP notation:

Requirements::customScript("var name = '" . $member->FirstName . " " . $member->Surname . "'");

The other way to do it is to use templated javascript. In this case you have a JS file with placeholders in it, and Silverstripe will substitute them in the same way it does with front-end templates:

$vars = [
    "MemberID" => Security::getCurrentUser()->ID,
];

Requirements::javascriptTemplate("<my-module-dir>/javascript/some_file.js", $vars);

https://docs.silverstripe.org/en/4/developer_guides/templates/requirements/#javascript-files

What sort of object are you talking about? Are you trying to pass a Silverstripe DataObject to the script, or are you trying to create a Javascript object?

Can you provide a little more info on what you’re trying to achieve?

Yes Silverstripe DataObject that has data from user table.

If you want to get all the data in your template to javascript, try the following:

$data = $member->record;
Requirements::customScript('var memberData = ' . Convert::array2json($data) . ';');

Is that what you’re looking for?