jberculo
jberculo

Reputation: 1113

Silverstripe: How to add custom css/js from module

I am building a small module that replaces the default FileField in Silverstripe and changes it into a fancier upload (in the front end). I replace the class through the injector method in Yaml. This seems to be working all right.

However, I need to add some js and css that only has to be included when the specific field is used. I tried the forTemplate method and the constructor of the filefield class, but both do not result in the files being added to the html.

Is there a way to do this?

I am using SS 3.4

Upvotes: 1

Views: 1231

Answers (1)

Barry
Barry

Reputation: 3318

You can add requirements in the CMS by adding the following to your config.yml file, however this will add globally...

LeftAndMain:
  extra_requirements_css:
    - mymodule/css/mymodule.css
  extra_requirements_javascript:
    - mymodule/javascript/mymodule.js

Instead including the required source files just within the FormField constructor would include just when this field is shown...

Requirements::javascript("mymodule/javascript/mymodule.js");
Requirements::css('mymodule/css/mymodule.css');

You can also add code directly possibly including values from the PHP like this...

Requirements::customCSS('
    #Form_FilterForm .field {
        display:inline-block;
        width:31%
    }
');
Requirements::customScript('
    jQuery(document).ready(function(){
        //JS Code here
    });
');

Or as above but it must be included in the header...

Requirements::insertHeadTags("
    <style>
        #Form_FilterForm .field {
        display:inline-block;
        width:31%
        }
    </style>
    <script>
    jQuery(document).ready(function(){
        //JS Code here
    });
    </script>
");

Upvotes: 1

Related Questions