Custom js added in custom module in magento - magento-2.0

I have created a module. In this a custom js file is added with requirejs-config.js, But to load the js file, I need to write the following lines on phtml,
<script type="text/javascript">
require(['jquery','customjs']});</script>
If I don't add the above line js is not adding .Can some body please tell is this the right approach or I am doing some thing wrong.
Require js code added at (Namespace\Modulename\view\frontend)
define([
'jquery',
'underscore',
'mage/template',
], function (
$,
_,
template
) {
//custom code
});

Yes this is the right approach. because you have created custom.js right . so that custom.js you need to call in your requirejs-config.js
But now when you want to use this actuall js functions and properties you need to pass below code
<script type="text/javascript">
require(['jquery','customjs']});</script>
What it mean actually , to load your customjs it requires jquery so first load the jquery then load your customjs and then you can pass the parameters.
require([ 'jquery', 'customjs'], function(){
alert("test");
});
so alert box will prompt when you add this in your template
Jfyi - in your requirejs-config.js you need to write like below code you dont'need to write extension of js file like.js as require js automatically render that . and lastly put the js file in web/js folder in your module
var config = {
"map": {
"*": {
"customjs": "Vendor_Modulename/js/custom"
}
}
};

Related

How to stop Webpack wrapping my JS in an IIFE so I can call my functions in .cshtml views

I've recently added WebPack 5 to my build process in my .NET Core MVC 7 application.
My goal is to be able to call my javascript functions from the javascript files WebPack generates inside my views.
I have a simple Index.cshtml file that includes a partial view and the generated javascript from webpack:
Index.cshtml
<div>
#await Html.PartialAsync("SettingsTab")
</div>
#section Scripts
{
<script defer src="~/dist/settings.entry.js"></script>
}
The SettingsTab constains a button that is trying to trigger a method from the settings.entry.js file:
SettingsTab.cshtml
<div>
<button type="button" onclick="saveProfileSettings()">Save Profile</button>
</div>
The settings.js file before webpack bundles it into the dist folder looks like this:
settings.js
import ('../css/settings.css')
function saveProfileSettings() {
// do stuff
}
When I wasn't using webpack I could directly call this function like I am trying to above.
However now when I reference the bundled js file it cannot call it.
Looking at the end of the settings.entry.js file it looks like webpack has bundled my code into an IIFE:
End of settings.entry.js
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// omitted contents of settings.js
})();
/******/ })()
;
I would like to instruct WebPack not to wrap my code like this so I can directly call the functions elsewhere.
Now I did find out that I can use library in my webpack.config.js like so:
output: {
filename: "[name].entry.js",
path: path.resolve('wwwroot', 'dist'),
publicPath: "/dist/",
library: ['WebPack', '[name]']
},
With this I can successfully reference my functions using WebPack.settings.saveProfileSettings() but I do not want to do this. I want to be able to reference my functions directly as saveProfileSettings().
How can I change how WebPack packs my code so I can do this?

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
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>
");

ZURB Foundation 6 Panini #ifpage not working

Using ZURB Foundation Template, building with NPM.
I have the following code in my default.html layout page:
<script src="{{root}}assets/js/app.js"></script>
{{#ifpage 'admin'}}
<script src="{{root}}assets/js/single-page/admin.js"></script>
{{/ifpage}}
{{#ifpage 'dashboard'}}
<script src="{{root}}assets/js/single-page/dashboard.js"></script>
{{/ifpage}}
In gulpfile.js I have as a member of the 'javascript' PATHS array:
'!src/assets/js/single-page/**/*'
I then, do:
gulp.task('single-page', function() {
return gulp.src('src/assets/js/single-page/**/*')
.pipe(gulp.dest('dist/assets/js/single-page'))
.on('finish', browser.reload);
});
Then...
gulp.task('build', function(done) {
sequence('clean', ['pages', 'sass', 'javascript', 'single-page', 'images', 'php', 'chart_data', 'copy'], 'styleguide', done);
});
And finally...
gulp.task('default', ['build', 'server'], function() {
gulp.watch(PATHS.assets, ['copy']);
gulp.watch(['src/pages/**/*'], ['pages']);
gulp.watch(['src/{layouts,partials,helpers,data}/**/*'], ['pages:reset']);
gulp.watch(['src/assets/scss/**/{*.scss, *.sass}'], ['sass']);
gulp.watch(['src/assets/js/**/*.js'], ['javascript']);
gulp.watch(['src/assets/js/single-page/**/*.js'], ['single-page']);
gulp.watch(['src/assets/img/**/*'], ['images']);
gulp.watch(['src/assets/php/**/*'], ['php']);
gulp.watch(['src/assets/chart_data/**/*'], ['chart_data']);
gulp.watch(['src/styleguide/**'], ['styleguide']);
});
My three pages are all PHP pages with the names index.php, admin.php, and dashboard.php. The js/single-page directory is being written to the dist folder and the two JS files are there.
The Panini conditional doesn't seem to be working so the admin-specific and dashboard-specific paths do not appear on their respective PHP pages.
Colin Marshall in his answer to How to add JavaScript just for one specific page? mentions a config.yml file and a gulpfile.babel.js file, neither of which are in my project's directory.
Any suggestions?
Thank you.
Simple fix after a bit of fiddling. Seems Panini 'page' var returned the full page name including .php. Once I checked for admin.php or dashboard.php all worked fine.
I can only imagine there's some code change I can make to return the page name without the file extension.

DataTables editable (where to put the editable_ajax.php file)

I'm trying to edit my tables content by following this example DataTables example
In my twig page I've added this script at the end:
$(document).ready(function() {
/* Init DataTables */
var oTable = $('.dataTable').dataTable();
/* Apply the jEditable handlers to the table */
oTable.$('td').editable( 'editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "auto",
"width": "auto"
} );
} );
the file editable_ajax.php is in the folder where my twig page is.
When I try to edit a cell I see with the debugging tool that the 'editable_ajax.php' file is not found, Can someone tell me where I should place it please ?
I'm sorry to say, but you seem to not have a good grasp of how templating and Symfony in general work. You're mixing very different things (PHP code, twig templates, Javascript code).
So, first read the Symfony Book. I would also suggest reading up on Javascript.
Some mistakes:
PHP files should never be in the "views" folder (aka. with twig files)
Javascript runs on the client side so you need to think about URLs when calling server-side code (aka. php code) NOT filesystem paths.
Javascript (jQuery is just a library) should not be in a twig file, but it's own *.js file and linked with a <script> html tag.

javascript contents are not getting loaded,if i create a tab/contentPane dymaically with .xhtml as input

I am creating a dynamic tab/contentPane as below in home.xhtml file and i am trying to call a function display which is present in order.xhtml,its not getting called. what ever java script is there in order.xhtml is not getting loaded.
In home.xhtml
if(dijit.byId('ordersummary')!=null){
dijit.byId('ordersummary').destroy();
}
newTab= new dijit.layout.ContentPane({
id : 'ordersummary',
title : 'Order Summary',
href : 'order.xhtml',
closable : true
});
dijit.byId('tabContainer').addChild(newTab);
dijit.byId('tabContainer').selectChild(dijit.byId("ordersummary"));
javascript in order.xhtml
<script type="text/javascript">
//<![CDATA[
function display(){
alert(" I M BEING CALLED");
}
</script>
There are two ways about this, either a make the script type dojo/method.
Or use the extended dojox/layout/ContentPane.
http://livedocs.dojotoolkit.org/dijit/layout/ContentPane#executing-javascript-inside-contentpane
While I'm not familiar with the dojo toolkit, I think you should put the JavaScript function in the main file or load the JavaScript dynamically like;
How do I include a JavaScript file in another JavaScript file?
dijit.layout.ContentPane will not support javascript,i mean it will not execute the javascript content in the input file.
dojox.layout.ContentPane is advanced one and it will support javascript.

Resources