formsdependenciessilverstripesettersilverstripe-4

How to require javascript after construction but before template render in a SilveStripe form field


I currently have a custom form field with a bunch of optional parameters in the constructor. I want to change this and have the field use setter functions but I can't find any way to include my templated JavaScript except during construction

class CustomField extends FormField {

    protected $myField;

    public function __construct($name, $title = null, $myField = null)
    {
        parent::__construct($name, $title);
        $this->setMyField($myField);
        Requirements::javascriptTemplate('path/to/script.js', ['Field' => $this->myField]);
    }

    /**
     * I can update the value of myField but the value is already baked into the JavaScript and wont be updated
     */
    public function setMyField($value) {
        $this->myField = $value;
        return $this;
    }

Solution

  • I found a solution but it does feel a little hacky. I added a RequireJs() function to the form field as such:

    <?php
    
    function RequireJs() {
        Requirements::javascriptTemplate('path/to/script.js', ['Field' => $this->myField]);
    }
    

    The added $RequireJs to the top of my template file so it would be called when the template is being rendered.