Drupal add javascript (core) just like the css function - drupal

My question is straight forward, for anyone who has coded with Drupal before, so that does not include me clearly :)
My question is how can I add a function like the one below to load all my JS files?
i am using the latest Drupal 7 edition
/**
* If the user is silly and enables netcast as the theme, manually add some stylesheets.
*/
function _netcast_preprocess_html(&$variables, $hook) {
// Add netcast's stylesheets manually instead of via its .info file. We do not
// want the stylesheets to be inherited from netcast since it becomes impossible
// to re-order the stylesheets in the sub-theme.
$directory = drupal_get_path('theme', 'netcast') . '/netcast-internals/css/';
drupal_add_css($directory . 'bootstrap.min.css', array('group' => CSS_THEME, 'every_page' => TRUE));
drupal_add_css($directory . 'style.css', array('group' => CSS_THEME, 'every_page' => TRUE));
}

You have analogue function to drupal_add_css:
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
But also, if you want JS (and CSS) on all pages you can add then from theme info file.

Yes, you can also add your JS files from your YOUR_THEME.info file that is located on /sites/all/themes/your_sub_theme_folder/, for Add a file it will be something like this:
; ========================================
; Scripts
; ========================================
scripts[] = js/your_file.js

Related

Drupal: Password textfield in everypage, how can I remove?

After migration, every page add password textfield at the end of every page.
What is this? How can I remove or troubleshoot?
Drupal 7.27 with apache 2.4 and php 7.0 (same problem with php 5.6.35).
Look there is a script loaded on these pages (just above the <form> itself) that creates the input tags and set the windows focus in it :
<script type="text/javascript">
var d = document;
d.write("<br><br><form method='post'><center><input type='password'...>...");
// ...
</script>
You want to remove this script.
Since there are several ways to include javascript with Drupal it may be difficult to spot the code responsible for that. Given the ugliness of the script itself, it could very well be harcoded in a theme template file (in this case, theme switching during migration would explain why your issue suddenly arose).
The chance is that ugly snippets like this is quite often hardcoded so you can make a search for a part of the js string (e.g. 'd.write("<br><br><form') in your project at the root of your site and/or in sites/all.
Lastly, find the guy that wrote this and beat him ;)
Your code is including a java script in every page which is creating input type password since it is included in every page that's why you are getting this field.
kindly check your requirement for same.
In drupal We can add JS in drupal by following method
1.)By drupal_add_js() function
drupal_add_js() is drupal api function to include js.
Example:
drupal_add_js('misc/collapse.js');
// add JS file
drupal_add_js('misc/collapse.js', 'file');
// For including inline javascript
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
//For including inline javascript and includ and includ it in footer
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array(
'type' => 'inline',
'scope' => 'footer',
'weight' => 5,
));
//For including External JS
drupal_add_js('http://example.com/example.js', 'external');
//For passing php value to JS
drupal_add_js(array(
'myModule' => array(
'key' => 'value',
),
), 'setting');
Example:
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
for more infomation visit https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x
2.)Adding by Form API
we can used '#attached' property of form api for including js
Example:
$form['#attached']['js'] = array(
drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);
3.)Adding JS in info file
We can including javascript in script file
Example:
name = My theme
description = Theme developed by me.
core = 7.x
engine = phptemplate
scripts[] = mytheme.js
4.)By preprocess function
if we want to conditionaly include JS we can include it in preprocess function
function mytheme_preprocess_page(&$vars, $hook) {
if (true) {
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
$vars['scripts'] = drupal_get_js(); // necessary in D7?
}
}

Working with forms in drupal 8

I am facing problem with "#markup" in form API.
In Drupal 7 we can use "#markup" form element which look like this:
<?php
$form['test'] = array(
'#type' => 'markup',
'#markup' => '<div><script src="http://localhost/drupal7/sites/all/libraries/test.js"></script></div>',
);
?>
//Here is my custom test.js
(function($) {
Drupal.behaviors.test = {
attach: function(context, settings) {
console.log('testttt');
document.write('*Hello, there!*');
}
};
})(jQuery);
and above code will print "Hello, there!" when form will be render.
Now in Drupal 8 I am using below code but it prints nothing.
<?php
$form['test'] = array(
'#markup' => '<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>',
);
?>
So how can implement this functionality in Drupal 8, which is already working in Drupal 7 .
Under script tag it can be local script or external script..
Please help...
Thanks
In Drupal 8, using "#markup" is not the proposed method to attach javascript files.
You can define libraries in your custom module or theme and attach the library to your form. The library can contain multiple js and (or) css files.
To define a library in your module:
Suppose your module name is "my_module", create a file "my_module.libraries.yml" in your module folder and specify the js and css files like this
form-script:
version: 1.x
css:
theme:
css/form.css: {}
js:
js/form.js: {}
js/form-ajax.js: {}
dependencies:
- core/jquery
In order to attach this library to your form:
$form['#attached']['library'][] = 'my_module/form-script';
Then clear cache. The js and css files will be loaded in the same order as you mentioned in the libraries.yml file.
You can define multiple libraries in the same "my_module.libraries.yml" file.
#markup still works in Drupal 8, but now it is filtered before output. As it is stated in Render API overview:
#markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, and are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed_tags to alter which tags are filtered.
As an alternative you may use FormattableMarkup:
'#markup' => new FormattableMarkup('<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>', []),
though it is not recommended in this case.

Unlimited Colour Schemes in wp theme for Zurb Foundation with reduxframework

I am developing a WordPress theme with Zurb Foundation 5 framework and ReduxFramework as Theme Options panel. So, there is various way that i can implement Colour Schemes for WordPress theme.
Using Different Style Sheets with different colour Schemes.
Using css class and id
+many more way........
But, I don't want to do this way. ReduxFramework can dynamically change css files and write class or id. And I want to do this way. So i can modify Foundation 5 css style sheet class and id from ReduxFramework Options panel dynamically. And After changing, it's must change Theme colour schemes.
Foundation 5 comes with 6 main colour options. I want to change those from ReduxFramework options panel.
Primary Color
Secondary Color
Alert Color
Success Color
Body Font Color
Header Font Color
Also is there any way that i can modify or change every options that comes with Foundation 5 CSS framework from Redux Framework.
Please go to this image link. {Open this image in a new tab for bigger view}
http://i.stack.imgur.com/YI0aD.png
Now question is, How can i do those things ?
I know short of PHP, JS, HTML, CSS, MYSQL etc. If you describe everything in your answer, it's will be more helpful for me.
This Question is RE-POSTED from Unlimited Colour Schemes in wp theme for Foundation 5 - WordPress Development Stack Exchange: . One reputed user suggested me to ask this question here!
The answer given by #Dovy is right in the basics. As far as i know there is no Less version of foundation. So you will need Foundation's Sass (SCSS) files and a SASS (php) compiler.
It seems Redux has a Sass compiler built in too: Redux and Sass
Install Foundation code, for instance by running bower install foundation in your WordPress folder.
Install a php Sass compiler, see: http://leafo.net/scssphp/
Now in your Redux config file add a hook on save:
add_action('redux/options/' . $opt_name . '/saved', "compile_sass" );
Also see: https://github.com/reduxframework/redux-framework/issues/533
And finally add the compile_sass function to the config file (you can use the compile action as an example, see: http://docs.reduxframework.com/core/advanced/integrating-a-compiler/):
function compile_sass($values) {
global $wp_filesystem;
$filename = dirname(__FILE__) . '/style.css';
if( empty( $wp_filesystem ) ) {
require_once( ABSPATH .'/wp-admin/includes/file.php' );
WP_Filesystem();
}
if( $wp_filesystem ) {
require "scssphp/scss.inc.php";
$scss = new scssc();
$scss->setImportPaths("bower_components/foundation/scss/");
// will search for `assets/stylesheets/mixins.scss'
$css = $scss->compile('$primary-color: '.$values['primary-color'].';
#import "foundation.scss"');
$wp_filesystem->put_contents(
$filename,
$css,
FS_CHMOD_FILE // predefined mode settings for WP files
);
}
}
Well, actually this is quite easy. Foundation uses LESS or SCSS to compile that. They use variables that they pass into those compilers. So the easiest way to do this would be to have Redux use a compiler hook on those color fields, re-output the variables file, and re-run the compiler on the LESS/SCSS. Cake. :)
I happened to get it working gathering info from the various comments but code reflecting newer versions of redux and foundation. Sharing code hoping someone finds this useful
/* sample redux fields = array(
array(
'id' => 'theme-primary-color',
'type' => 'color',
'title' => __( 'Add Primary Color', 'theme-redux' ),
'subtitle' => __( 'Add the theme primary color', 'theme-redux' ),
'default' => '#FFFFFF',
'validate' => 'color',
'compiler' => 'true',
))
*/
add_filter('redux/options/' . $opt_name . '/compiler', 'compiler_action', 10,3);
function compiler_action( $options, $css, $changed_values ) {
global $wp_filesystem, $kavabase_options;
$filename = get_template_directory() . '/assets/stylesheets/theme-style.css';
if( empty( $wp_filesystem ) ) {
require_once( ABSPATH .'/wp-admin/includes/file.php' );
WP_Filesystem();
}
if( $wp_filesystem ) {
require_once ( dirname(__FILE__ ) ."/plugins/scssphp/scss.inc.php" );
//use Leafo\ScssPhp\Compiler; at the beginning of the file
$scss = new Compiler();
$scss->setImportPaths( get_template_directory(). "/inc/foundation-sites/" );
//$scss->setFormatter( "Leafo\ScssPhp\Formatter\Compressed" );
$css = $scss->compile('#import "foundationdependencies.scss"; $theme-primary-color: '.$options['theme-primary-color'].';
#import "foundationsettings.scss";
#import "foundationutil.scss";#import "foundation.scss"');
//var_dump( $scss->getParsedFiles() );
$wp_filesystem->put_contents(
$filename,
$css,
FS_CHMOD_FILE // predefined mode settings for WP files
);
}
}

Adding custom code to <head> in Drupal

I'm trying to figure out where the <head> for all of the pages in Drupal is (I'm using Orange theme if it matters). I have to add analytics code into the <head>.
Inside which file would I find the <head>?
Use drupal_set_html_head() by placing this in your themes template.php file. If the function MYTHEMENAME_preprocess_page() already exists insert what is inside the {closure} brackets below (before the $vars['head'] if that exists in it as well) :
function MYTHEMENAME_preprocess_page(&$vars, $hook) {
// say you wanted to add Google Webmaster Tools verification to homepage.
if (drupal_is_front_page()) {
drupal_set_html_head('<meta name="google-site-verification" content="[string from https://www.google.com/webmasters/verification/verification]" />');
$vars['head'] = drupal_get_html_head();
}
}
In template.php of your theme folder :
function your_theme_preprocess_html(&$variables) {
$appleIcon57px = array(
'#tag' => 'link',
'#attributes' => array(
'rel' => 'apple-touch-icon',
'href' => '/images/ICONE-57.png',
'type' => 'image/png',
'media' => 'screen and (resolution: 163dpi)'
)
);
drupal_add_html_head($appleIcon57px, 'apple-touch-icon57');
}
If you look in your theme folder you'll see page.tpl.php, that is the template for the site. You can add the code there most likely.
How to change a page meta description and keywords in Drupal 6
One another solution is to use blocks in header these can also managed very effectively using css.
All you have to do is to go to Structure->Blocks then create new block.
Then select theme corresponding to it and position in which section you want to show that block.
Custom html like can be added. And can be handled from that id.
It allow me to handle page structure very easily.
In the theme folder (e.g. themes/orange) there is a templates folder with the file html.tpl.php
In this file you can freely add what you need to the head section and it will be added to every page.
there is a google analyitics module that will accomplish this for you with just your key.

Load view template on module activation

I have developed a blogger-like archive feature (you know, from the feature module).
I want to edit the .module file in order to automatically load the view-template (which is bundled in the feature) into the theme. Is there a way to do it?
On a general level: you should think "features = modules" and leaving theming for... themes! This does not mean that you shouldn't include a template with your feature, but that you should evaluate whether the template you have built suits a general use of your feature or it is specific for your currently used theme. If it is the latter case, you should not package your template file with the feature, but leave it with the theme instead. Just think to how the views module works, to get an idea of what I mean.
[Maybe you are already aware of this and made your considerations to this regards, in which case simply disregard what above. I thought about writing it because your sentence "I want the tpl.php to be actually available for the feature to use it (just as if it were in the active theme folder)" surprised me as general-use templates do not live in the theme folder but in the their module one, and moreover views already provide a "general use" template.]
That said, the way you normally tell drupal to use a given template, is via implementing hook_theme() in your module. In this case - though - given that you are going to override the template defined by views you should implement hook_theme_registry_alter() instead.
Somebody actually already did it. Here's the code snippet from the linked page:
function MYMODULE_theme_registry_alter(&$theme_registry) {
$my_path = drupal_get_path('module', 'MYMODULE');
$hooks = array('node'); // you can do this to any number of template theme hooks
// insert our module
foreach ($hooks as $h) {
_MYMODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $my_path);
}
}
function _MYMODULE_insert_after_first_element(&$a, $element) {
$first_element = array_shift($a);
array_unshift($a, $first_element, $element);
}
Of course you will have to alter the theme registry for your view, rather than for a node (the original example refers to a CCK type).
As on using the template in the views_ui, I am not sure weather the features module already empty the theming cache when you install a feature (in which case you should be good to go). If not, you can trigger it manually by invoking cache_clear_all() from your install file. If emptying the entire cache is too much, you should dig into the views module on how to flush the cache relatively to a single views.
Hope this helps!
Try to add this to your feature .module file
/**
* Implementation of hook_theme_registry_alter().
*/
function MYMODULE_theme_registry_alter(&$theme_registry) {
$theme_registry['theme paths']['views'] = drupal_get_path('module', 'MYMODULE');
}
On the .install file use this
/**
* Implementation of hook_enable().
*/
function MYMODULE_enable() {
drupal_rebuild_theme_registry();
}
Here is my snippet to declare views templates stored in the "template" folder of my "custom_module":
/**
* Implements hook_theme_registry_alter().
*/
function custom_module_theme_registry_alter(&$theme_registry) {
$extension = '.tpl.php';
$module_path = drupal_get_path('module', 'custom_module');
$files = file_scan_directory($module_path . '/templates', '/' . preg_quote($extension) . '$/');
foreach ($files as $file) {
$template = drupal_basename($file->filename, $extension);
$theme = str_replace('-', '_', $template);
list($base_theme, $specific) = explode('__', $theme, 2);
// Don't override base theme.
if (!empty($specific) && isset($theme_registry[$base_theme])) {
$theme_info = array(
'template' => $template,
'path' => drupal_dirname($file->uri),
'variables' => $theme_registry[$base_theme]['variables'],
'base hook' => $base_theme,
// Other available value: theme_engine.
'type' => 'module',
'theme path' => $module_path,
);
$theme_registry[$theme] = $theme_info;
}
}
}
Hope it helps someone.

Resources