Working with forms in drupal 8 - drupal

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.

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?
}
}

Dynamic load css with CakePHP on a Page

I am using CakePHP 2.0 and I want to load a concrete CSS style in a Page. (with no controller but using the Layout).
I know it can be done with scripts using:
$this->Html->script('photos', array('inline' => false));
And then on the Layout:
<?php echo $scripts_for_layout; ?>
But i have no idea if it exists or not something similar to $scripts_for_layout; for CSS style.
Do you know how can i do it?
If you can upgrade to 2.1 then you can use this:
// in your view
$this->Html->script('carousel', array('block' => 'scriptBottom'));
// in your layout
echo $this->fetch('scriptBottom');
http://book.cakephp.org/2.0/en/views.html#using-blocks-for-script-and-css-files
update:
In earlier versions you could do it like you do with scripts:
$this->Html->css('some.css', null, array('inline' => false));
And it will be placed to $scripts_for_layout.

Drupal 7: calling custom content type field into page tpl

I'm working on a Drupal 7 website. I need custom layout for some pages. so I created page--customContentTypeName.tpl.php file and it addresses perfectly.
The problem is, I need to display some fields in page tpl. The code below works fine in node tpl, but page tpl :/
<?php print $content['field_images']['#items']['0']['filename']; ?>" />
How can I call custom fields into page tpl?
Appreciate helps!! thanks a lot!!
** SORTED **
with custom field editing... here is the tutorial video: http://lin-clark.com/blog/intro-drupal-7-theming-fields-and-nodes-templates#comment-54
For page.tpl.php
if you access the node directly you can use $node variable
$node['field_images']['und'][0]['filename']
else use $page variable.
$page['content']['system_main']['nodes'][1]['field_images']['#items'][0]['filename'];
but remember in a page variable you might have more than one node.
The structure changed in 7, the field is keyed by language first ("und" by default which means "undefined"), then you can follow this example:
// Array of Image values
$images = $node->field_images['und'];
//If you don't know the language, the value is stored in:
$node->language
// First image
$image = $images[0];
// If you need informations about the file itself (e.g. image resolution):
image_get_info( $image["filename"] );
// If you want to access the image, use the URI instead of the filename !
$public_filename = file_create_url( $image["uri"] );
// Either output the IMG tag directly,
$html = '<img src="'.$public_filename.'"/>';
// either use the built-in theme function.
$html = theme(
"image",
array(
"path" => $public_filename,
"title" => $image["title"]
)
);
Note the usage of the uri instead of the filename for embedding the image in a page because the File API in Drupal 7 is more abstracted (to make it easier to integrate with CDN services).
there are 2 useful modules in drupal for theme developers:
Devel and Theme_developer
Devel module provides a function called dsm() .
using dsm you can recognize that how elements are stored in different objects.
like nodes or ...
for example you can use this statement : dsm($node)
the structure of any nodes in the page will show up in the message box.
you can type the statements in your codes.

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.

Drupal 7 and using custom templates with theme()

I have a list of items in the default main-menu. I am trying to override the template so I may iterate over each item and custom template/theme the entire menu.
echo theme('links', array('links' => menu_navigation_links('main-menu', 0)));
main-menu is the default menu ID drupal provides. The first param to theme is telling it to use the default "links" template - this much I understand. How do I tell it to use MY mainmenu.tpl.php that resides in mytheme directory?
I have tried creating a file named mainmenu.tpl.php and calling it with
theme('links__mainmenu.tpl.php')
So as to provide a fallback to default links in case mainmenu.tpl.php should every disappear. I am naming the files wrong or something and I cannot for the life of me figure it out. Help :)
Cheers,
Alex
A module's default theme is defined in the hook_theme method. This function allows you to declare theme files (.tpl.php) and the variables passed to them. To declare the default theme file, use the template field.
function hook_theme($existing, $type, $theme, $path) {
return array(
'mymodule_display' => array( /* displayable name */
'template' => 'mymodule_display', /* template file, leave off .tpl.php */
'variable' => array(...), /* associative array of vars used */
)
);
}
This link contains a more in depth example.
To invoke the module's default theme, use the theme() method, as shown in your original post. Something like:
<?php echo theme('mymodule_display', array(/* vars */));
The double-underscore is used for defining fallback themes, with the last one being preferred. Therefore, theme('links__mymodule_display', ...) means that Drupal will use the Links module theme only if mymodule_display cannot be resovled.
Kind of basic but does your theme implement the base theme and is your theme set to the default?

Resources