Get the current path in Views What's the best way to get access to the current path in Views?

My use case is I want to use the current page path in a text area (i.e. I want to have a text field like More).

At the moment I'm handling it by using hook_views_re_view to rewrite a "Global: Custom Text" field value with drupal_get_path_alias().

Ideally I'd like something more portable, i.e. the ability to add a "Global: Current Path" field to my view.

What combination of hooks/handlers/plugins do I need to use?

Thanks a lot. I did go down the Views PHP route initially, but it struck me as a bit un-Drupally, and even Views PHP says to use handlers where possible.

In the end I used hook_views_data and did:

function mymodule_views_views_data() {
  $data['views']['current_path'] = array(
    'title' => t('Current Path'),
    'help' => t('Provide current path.'),
    'field' => array(
      'handler' => 'concept2_views_handler_field_current_path',
    ),
  );
  return $data;
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function mymodule_views_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'mymodule') . '/handlers',
    ),
    'handlers' => array(
      // The name of my handler
      'mymodule_views_handler_field_current_path' => array(
        // The name of the handler we are extending.
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

With a handler file like:

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
class mymodule_views_handler_field_current_path extends views_handler_field {
  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE, 'bool' => TRUE);
    $options['hide_alter_empty'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    unset($form['help']);
  }

  function render($values) {
    // Return the text, so the code never thinks the value is empty.
    return drupal_get_path_alias();
  }
}

Have you checked out Views PHP? It has some bugs when accessing the $row variable but it works great for injecting PHP into a Views field.

You could use request_path() in a Views PHP field:

Whatever text you want plus a <a href="<?php print request_path(); ?>">link to the current page.


Panopoly with no views I've just installed Panopoly 1.14 and I can't add views to my panels.

I create the view block normally without any problem; I can see the view, inside the block section, but when I try to create or edit the panel, I can't see views at all in the left side of the add-content screen where it should be.

I checked the permissions and I have all the administrative ones. What am I missing?

Go to admin/structure/panels/settings and check Make all views available as panes.


Close Lightbox on Custom Form Submit I am using form Api to create a custom form. My form is below.

function myform_form() {
  $form = array();
  $form['name'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#required'      => FALSE,
    '#weight'        => 2,
  );
   $form['telephone'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#weight' => 3,
    );
     $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
     );
  return $form;
}

function myform_submit($form, &$form_state) {
  drupal_set_message(t('Your form has been submitted successfully.'));
  $form_state['redirect'] = 'thankyou';
}

I used to show this form in lightbox as this :

 Form

Form is correctly showing in lighbox. But when i submit the form it opens the thankyou page in popup.

I used

 Form

It closes the popup event if form validation returns false. I don't want to close the popup if there is any validation error. I added this to myform_submit function :

parent.Lightbox.end();

But drupal_add_js is not working in myform_submit function.

Updated :

I send a parameter to thank you page and added this on the page load.

<?php if($_GET['redirect']) { ?>

<?php } ?>

Its redirecting but it shows content in popup for few seconds and redirect after that. I don't want to display popup for a second also after submitting the form.

Solved this by creating a Menu showing processing message and redirect it using :

      window.parent.location = "thankyoupage";

Hope this will help you,

For forms validation on modal dialog you can user Chaos tool suite module.

Steps

Download and enable Chaos tools and Chaos Tools (CTools) AJAX Example
Go to the URL your_site/ctools_ajax_sample
You can refer ctools dialog form examples using sites/all/modules/contrib/ctools/ctools_ajax_sample

Where contrib is the folder where I keep all my contributed modules.


drupal_add_js - working with inline but not file I have the following code which works:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}
?>

but the following doesn't:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js(drupal_get_path('module','conflict') . '/js/test.js');
  }
}
?>

The code in sites/all/modules/mymodulename/js/test.js is:

If(Drupal.jsEnabled) {
  $(document).ready(function() {
    alert("Hello!");
  });
}

And when I look in the page source when I'm in "job_node_form", I can see the js file loaded.

Edit:

I've found that:

$(document).ready(function()

is causing the issue. I've tried both $ and jQuery.

Is the inline code timed differently to the code in a js file? I'm wondering if the code in the js file runs before all DOM objects are loaded?

With Drupal instead of using $(document).ready, you can/should use Drupal.behaviors. Here is a boilerplate JavaScript wrapper you can use:

(function($, Drupal) {

  // Custom functions and variables can go here

  Drupal.behaviors.moduleName = {
    attach:function() {
      // Put your document's onload code here
    }
  };
}(jQuery, Drupal));

By the way, now that it's all done, to go back to the original topic, I wouldn't/don't use drupal_add_js() at all. Instead, you can do this:

<?php
if($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}
?>

This attaches the file directly to the form, allowing it to be overridden further down the line through the context of the form it belongs to.

function mymodule_submit_add_js($file) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . "/js/name.js");
}


How to alter auto-complete exposed filter programmatically? I created a views to show parent and child term together using autocomplete expose filter .. but its show only one child. I have same child for two different parent.but its show only one child.
how to change this programmatically using view query alter. I need such type:

Parent . Parent-1
           locality-1
           locality-2
         parent-2
           locality-2
           locality-4

I need such type of result on autocomplete expose filter.

Here is a possible answer to this problem.
First of all, a litte visual.

To get this working you need the following:

Configure your View to display the exposed taxonomy filter as a dropdown. autcomplete will not work because you cannot have multiple entries with the same key in the generated JSON array.
Optional: Install and configure the Chosen module [https://www.drupal.org/project/chosen] to get your dropdown to render nicely and offer autocomplete options.

You will also need this JS library for Chosen to work => [https://github.com/harvesthq/chosen]

Optional: You can finally use some custom code for formatting the presentation of your list, here is a sample minimal module that adds the special arrow that you see in the screenshot.

define('YOUR_CUSTOM_TAXONOMY_AUTOCOMPLETE_PATH', 'mycustompath/1');
define('YOUR_EXPOSED_FILTER_MACHINE_NAME', 'field_tags_tid');

/**
 * Implements hook_form_alter()
 */
function se_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'views_exposed_form' ){
    if(isset($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]) &&
    $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#type'] == 'select'){
      $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options'] = _custom_update_options_for_taxonomy($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options']);
    }
  }
}

/**
 * Function that update select options for taxonomy filter
 *
 */
function _custom_update_options_for_taxonomy($options = array()) {
  $current_parent = '';
  foreach( $options as $i=>$option ) {
    if( is_int($i) && isset($option->option) && is_array($option->option) ) {
      $option_arr = $option->option;
      $tids = array_keys($option_arr);
      $tid = reset($tids);
      // is this a child of the previous parent
      if( strpos($option_arr[$tid], '-') === 0 && $current_parent != '') {
        $option_arr[$tid] = preg_replace('/^-/', ' ⤷ ', $option_arr[$tid]);
        $option->option = $option_arr;
      }
      // this is a parent node
      else {
        $current_parent = $option_arr[$tid];
      }
    }
  }
  return $options;
}

Hope this help some!


Why does hook_menu_link not work? theme_menu_link allegedly "Returns HTML for a menu link and submenu."

In attempting to use this 'hook' I added code to my template.php as such:

function themename_menu_link(array $vars) {
  dpm($vars);
}

It didn't work.  Nothing appears.

I confirmed that the template.php code is executing and cleared caches several times.

Every other hook_ or theme_ function I've tested runs without issue, however this one does not.

I've also tested the alternative method, themename_menu_link__your_menu_name with no success.  The code seems to be ignored.

Try print_r instead of dpm --

function theme_menu_link(array $variables) {
  return print_r($variables['element']);
}

or use hook_menu_link_alter --

hook_menu_link_alter($variables){
  var_dump($variables);
}


Installing on IIS 7/Windows Server 2008 R2/MSSQL 2008 I am having difficulty connecting to my MSSQL database (locally installed) while proceeding through the Drupal Install. I do not get any errors during the Verify Requirements portion, but not matter what info I put into the Database configuration page, it cannot connect. It does not throw an error like "phpmssql library missing"

This is what I have installed so far.

Windows 2008 Server R2
Internet Information Server IIS 7.5
SQL Server 10.0
Microsoft Drivers for PHP for SQL Server 3.2
php-5.6.21-nts-Win32-VC11-x86
php_pdo_sql_srv_56_nts.dll
php_wincache-1.3.7.9-5.6-nts-vc11-x86
sqlsrv-8.x-1.x-dev
wincachedrupal-7.x-1.10

Should I be putting something besides "localhost" and "1433" in the "Advanced Options" panel?

Thanks in advance for any help!

phpmssql library missing

You are using the 8.x-2.x branch of the driver, that relies on a paid external library phpmssl:

http://www.drupalonwindows.com/en/content/phpmssql

You can use the "free" 8.x-1.x branch - that has no dependencies - for evaluation purposes. I say evaluation because it's a non supported half-broken branch I used to work on during the first D8 port attempt of the driver.

You can find full discussiones of this issue here:

http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

Disclaimer: I'm the maintainer for the SQL Server driver, PHP Mssql and Wincache.


Simple Oauth oauth/debug?_format=json Internal Server error When i try to test the ooauth/debug?_format=json endpoint through Postman i get the internal server error and error code 403 forbidden.
Even though i use a valid Authorization header with Bearer and the access token for a certain user. The endpoint works fine for anonymous user.
So i guess it's a permission error or the token expires even though i've set a big expiration date for testing purposes.
Has anyone encountered the same issue as me? If yes did you manage to solve it? I follow the tutorial step by step from the official simple_oauth module page in drupal. Thanks in advance for reading this.

I fixed this issue by going to admin/people/permissions and selecting all of the Simple OAuth permissions for Authenticated User. I'm sure a more refined approach to selecting permissions will be possible, but initially selecting all of them has fixed this issue for me.


How does the view filter: Search: Search Terms works? Can I improve it? I have a View with and Exposed Filter: Search: Search Terms to filter the view result based in the keywords entered in this filter.

I works, but not as I expected.

Lets say I have a node with the title "The car, a good transport". Then:

if I enter the keyword: car the node is shown
if I enter the keywords: car a good the node is not shown
if I enter the keywords: good car  the node is not shown

Is this behaviour right? I need the node to be shown in all these situations

UPDATE: I see that there is already an open issue about this: http://drupal.org/node/1615438

If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word"

It's better to use operator "contains all words". Drupal search is no good, it's indexing everything but then you can't find anything..


Get argument from current URL in twig to generate a link with that argument I'm trying to get an argument from search page URL so that I can pass that argument to a link.
For example I have this URL for a search results page:
http://domain.com/site-search?search_api_fulltext=foo
And on that page I want to have a link that goes to:
http://domain.com/other-search?search_api_fulltext=foo

I've tried {{ url('<current>') }} but that only returns the domain and path, but not the arguments. I've been trying stuff like {{ app.request.requestUri }} but that returns nothing.

FWIW, I'm trying to include these links in a custom block that appears on the search results page.

well if you are making a custom block then you are probably doing something like this ....

 $build = [];
 $build['#theme'] = 'your_template',
 return $build;

and then in you hook_theme().

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
    ],
  ];
 }

you don't need to pre prossess the block at all just make sure the block is not being cached aka add this to your block plugin.

see How to prevent a block from being cached?

public function getCacheMaxAge() {
  return 0;
}

then in your block function :

 $search_query = \Drupal::request()->get('search_api_fulltext');
 $build = [];
 $build['#theme'] = 'your_template',
 $build['#search_query'] =  $search_query,
 return $build;
....

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
     'variables' => [
       'search_query' => NULL,
     ],
    ],
  ];
 }

then in your twig template

{% if search_query %}
  do what you want here {{search_query}}
{% endif%}


sort specific field last modified date I have content type named recipe, Recipe have some fields like name, image, description. And also have a Boolean field name editors picks. I want to get last checked 3 posts of editors picks field in a view. or i want to limit this field can check only in 3 post. How can i do this. Please help me

I searched for SORT CRITERIA to sort by last modified date there is a field named "Content revision: Updated date". This field helped me to sort by modified date.

Credits: @ismini (for posting the comments that helped me).


How to run jquery function on every page load I have a Views grid that contain images in DIV containers. I want these containers to have one of two possible heights 60px or 104px, depending on the images height. So I came up with this function (contained in a $(document).ready function())  that I have added in my theme's JS file.

  $('div.givarbild img').each( function() {
    var container = $(this).closest('div.givarbild');
    var pic = new Image();
    pic.src = $(this).attr("src");
    var picHeight = pic.height;
    console.log(picHeight);
    if(picHeight < 60){
        container.height(60);
    }else if(picHeight > 60){
        container.height(104);
    }

  });

Now, my problem is that this only works once, after clearing the caches in Config -> Performance. If I simply reload the page after clearing all caches in Drupal all DIVs are 60 px high and the container.height value is zero in the js console (Firebug).

How can I force this little function to run after every page load?

EDITED:
Hmmm, I am obviously doing something wrong here :-)... but with this code:

(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                var pic = new Image();
                pic.src = $(this).attr("src");
                var picHeight = pic.height;
                console.log(picHeight);
                if(picHeight < 60){
                    container.height(60);
                }else if(picHeight > 60){
                    container.height(104);
                }
            });
        }
    }
})(jQuery);

... I get the exact same result. It works immediately after clearing all caches in Drupal 7 but not when I reload the page after that. Is there something fishy with my custom script itself?

EDITIED AGAIN: I post this change to my js code in case anyone else is having the same issue. This code does the same thing as the previous one, except that it works every time, and not just the first time after clearing all caches in D7. The only thing I changed was the method for getting the natural image height. It would be interesting to know why this latter code works though and not the first one... it actually works every time even without the added Drupal.behaviors rows.

(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                $("<img>").attr("src", $(this).attr("src")).load(function(){
                    var picHeight = this.height;
                    console.log(picHeight);
                    if(picHeight < 60){
                        container.height(60);
                    }else{
                        container.height(104);
                    }
                });
            });
        }
    }
})(jQuery);

(function ($) {
  Drupal.behaviors.custom_scripts = {
    attach: function (context) {

      //write your custom code

    }
  }
})(jQuery);

Along with this for the first time you have to clear cache, and this will work in all pages and all the times.

You could try to disable the caching of the view.
To do this go admin/structure/views and edit your view under the advanced section there is a caching option.


Is there a way to get a default e-mail recipient by default when adding a new webform node? When I add a new Webform node type, this have no e-mail recipien by default. You can read this message:

  Currently not sending e-mails, add an e-mail recipient below.

Is there a way to get a e-mail recipient value by default when creating a webform node?

You can do this with a custom module and hook_node_presave(). After you have a custom module created, you can use code like this to create a default e-mail configuration for any created Webforms.

Assuming your module were called myexample.module, the hook would look like this:

<?php
/**
 * Implements hook_node_presave().
 */
function myexample_node_presave($node) {
  // Add a default e-mail configuration for new nodes.
  if (empty($node->nid) && $node->type == 'webform') {
    $node->webform['emails'][] = array(
      'email' => 'example@example.com',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
      'html' => 0,
      'attachments' => 0,
    );
  }
}
?>

Yes, you can.

You go to your webform node, click on "webform" then "email's", you should set up one if you don't have one, and on "E-mail to address" you can write your default email.
You can even set up the subject and the body.
You can print the whole email through %email_values token value, or field by field with label using  %email[yourfield] or without label using %value[yourfield].

I'm editing my answer:

You can set a defaul email recipient you have three choices:

You create an email field with a defaul value (your email) and the user can change that value;
create an email field with your email such as default value and click on "disable" if you don't want the user changes the email but he can still see it;
create a email field with your email such as default and click on "hidden", the user won't be able to see and change that email;

I hope this time will be useful :D


Cannot install Drupal 8 on Windows 8 XAMPP PHP 5.6 Additional uncaught exception thrown while handling exception

Cannot install D8 in latest XAMPP workstation on Win8. Can install D7 though.

I did increase max_allowed_packet = 64M

You have comments disabled in your opcache configuration. Add the following line

opcache.save_comments=1 in php.ini or if opcache has its own config file

Please consult this for more details.

I had same problem.
Solution:
https://www.drupal.org/files/Installing%20Drupal%208%20on%20windows%20with%20XAMPP.pdf
(page 7)

Regards.


Dreadful Google CSE error We have several sites on a multisite structure, and almost all of them use Google CSE. However, some of these websites display the error "Refused to display 'http://www.google.com/cse?cx=...' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. This behaviour happens only for a couple of sites. I have compared Google CSE settings, and they are identical. How can I fix this issue?

UPDATE: I've compared directory sizes from both sites and they were different, so I've tried removing the module from the site that doesn't work, and copying one from a site that does work; but no dice :S

Doing a quick search on Google I found this answer to a similar question: https://stackoverflow.com/questions/7905169/when-did-google-search-start-sending-x-frame-options-sameorigin

I hope it helps.

Best regards,
David.


Views block showing empty content on front end I created a view to show a list of news items. I placed the view block in the content bottom region of the page. In the Views preview, it shows the results. However in the front end, the content is empty and shows:

I do have a view template for this block - views-view--news-list--block-1.tpl.php. In the Views page it shows this template as selected. I do not see that it is being rendered on the page though. Even when I just put a basic div with text in the views template, nothing shows in the content div.

What are the possible reasons for this? What can I do to get content to show?

Turns out it was my theme's block.tpl.php file. It was displaying content like so, $block->content.

I changed it to match the block.tpl.php file in modules/block:

<?php print $content ?>

I would check the following:

Does it work without the views template?

Does it use arguments in the view? If so, are they set correctly in the block.


Can I access node ID of the parent node of a field collection field in field-collection-item--FIELD_NAME.tpl.php I am just hoping to get the node ID of the parent node in a field-collection-item--name.tpl.php template file.

So if my parent node name is mypage in which I have child fields of field-collection-item--name.tpl.php, I just want to access the Node ID of the parent page (mypage) in field-collection-item--name.tpl.php.

Is it possible?

Apparently somewhat yes. If I do this, I get details on the parent node. The only problem is that that data is protected. The output of this line is pasted below. All I want is [vid] value (i.e. 120)

  $var = $content["field_image_title"]["#object"];
  print_r ($var);

Output of above line

FieldCollectionItemEntity Object
(
    [fieldInfo:protected] =>
    [hostEntity:protected] => stdClass Object
        (
            [vid] => 120
            [uid] => 1
            [title] => My Parent Page Name
            [log] =>
            [status] => 1
            [comment] => 1
            [promote] => 0
            [sticky] => 0
            [vuuid] => f3c2f63d-5d86-4d94-98f3-8a1ba76ce1f9
            [nid] => 120
            [type] => subpage
            [language] => und
            [created] => 1408623334
            [changed] => 1408640101
            [tnid] => 0
            [translate] => 0
            [uuid] => 486dead0-4f72-45a3-988c-64512e6b91de
            [revision_timestamp] => 1408640101
            [revision_uid] => 1

Any help on how I can get this vid value in this protected array?

Thanks.

Load the field collection using entity_load by passing the entity id. It gives you object where you can get the Host entity of the loaded entity. example profile2 will have user entity as host entity, or commerce line item will have commerce order as host entity.

$entity = entity_load('field_collection_item', $your_file_collection_id);
$host_entity = $entity->hostEntity();
echo $host_entity->nid;

All I needed was the nid of the parent, so I wound up going with:

$parent_node = menu_get_object();

This gave me access to the full node info, and I could use what was needed. It's not quite as elegant as the solution above, but I wanted to keep it simple.


How do I turn on theme_debug? I want to use theme_debug to check which elements of a site use which .tpl files.

I have tried turning it on by using the drush command:

drush @mysite vset theme_debug 1

Though I do get the response theme_debug was set to 1, this does not seem to work.

Would anyone know if there is a way to get this working?

(Drush it's self seems to be working ok as I can use drush @mysite cc all)

Drush commands to control theme debugging:

Drupal 7

To turn it on: drush variable-set theme_debug 1
To turn it off: drush variable-set theme_debug 0

Drupal 8

To turn it on: drush state-set theme.debug 1
To turn it off: drush state-set theme.debug 0

Step 1: Path :\sites\default\setting.php

  Step 2: Edit Setting.php:
  remove # from

  #$conf['theme_debug'] = TRUE;

  Step 3: Save setting.php file

  Step 4: Inspect your website then you seen that theme information is show.


Image styles not generated with Drupal 7 on IIS 6 I've developed a site that uses various image styles to export images to an iPhone (linked from a XML export document). This worked perfectly fine on my own development server with Linux/Apache.

The site is now currently hosted on a shared hosting environment, which uses Windows/IIS6. (yeah, strange; it is not my decision as you can assume ;).)

The problem now is that the image_style URLs for new images (existing images work) lead to a 404 error page, which is directly served by IIS. However, clean URLs worked fine out of the box and "normal" 404 pages are displayed by Drupal.

So, an URL like http://example.org/does_not_exist shows the typical site not found error, served with Drupal but http://example.org/sites/default/files/styles/command_image/public/Chrysanthemum_0.jpg shows the IIS 404 page.

The site is using the public file system for these images and the path is correct; it does work fine for existing images, which I uploaded together with the rest of the site during the initial deployment on that server.

Do you have any idea?

Ok, I figured it out.

The problem was that there were two .htaccess files. One in the top level, that contains most of the configuration and one in sites/default/files, which is security related (avoid execution of php files and similar) and contains just this:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

Now the difference seems to be that in Apache, both files seem to be combined (the one in sites/default/files inherits everything from the top-level one). This does not happen with the ISAPI_Rewrite module that seems to handle the Apache/IIS .htaccess compatibily.

I fixed this by copying the content of the top-level directly into the file in sites/default/files, below the existing content. Additionally, I had to change the RewriteBase so that it included the index.php file in the correct directory.

The header of the changed .htaccess file now looks like this:

# From the original .htaccess file, do not remove.

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

#
# Apache/PHP/Drupal settings:
# (copied from /.htaccess)
#

Content of the top level .htaccess file here comes here...

And the part that I changed now looks like this:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /YOURFOLDERHERE

So when Drupal is installed in a sub directory, insert your folder name. If not, you can leave this part commented out.

I found this thanks to the (unecessarly long) blog post at http://www.caspianit.co.uk/imagecache-wrong-path/

Note: Simply deleting the .htaccess file in sites/default/files did work too, however, that removes the security relevant SetHandler setting. I however doubt this has any effect in IIS anyway...

My quick solution to this was to set sites/default/files to 775


Distinguishing form being built for rendering versus submission Is there a way to distinguish, inside a form function, that the form is being built to be rendered on the page, as opposed to being re-built as a result of submission?

I would like to use drupal_set_message() inside the form function, but only while it's being built for rendering.

Take a look at the $form_state elements. You'll want to look at 'submitted', 'rebuild', 'cache', 'programmed', etc... depending on your use-case.  You can get a good idea of those elements and what they mean in drupal_build_form.  I typically use $form_state['submitted'].


How to add multiple terms to a taxonomy reference field via feeds? I would like to import a node with multiple taxonomy terms referenced in one of node fields.
How can I do this with Feeds and Drupal 7 ?

Use the Feeds Tamper module to "explode" the comma-delimited list of taxonomy terms into individual references.

  Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below.
  Additional plugins can be added in separate modules or through the issue queue.

I'd like to suggest the Manage Multiple Terms module.

  Manage Multiple Terms provides a simple mechanism to add, update, delete many terms in the same time easily and quickly.


remove second admin menu This is a pretty basic problem I think but i can't seem to find the solution. I've install the adminimal menu and I would like to remove the second menu on the bottom of this image. I've disable toolbar.

navbar was enable. I disable it and the hambuger menu was gone.
Thanks for your help.

Disable Toolbar module from core section in module list,
hope it helps


Getting the value of a taxonomy term reference field I have a content type (Movie) with a taxonomy reference (Movie rating) for which can get multiple values. I would like to use the template node--movie.html.twig and get the first value inserted in the taxonomy term.

I tried using the following code, but it doesn't give any value.

{{ content.field_rating['#items'].getValue()|first.value }}

What am I doing wrong? In which way do I reference the taxonomy term value?

You get the first item out of ['#items] with a "0":

{{ content.field_rating['#items'].0 }}

To get a field from the taxonomy term, I would use the node object, because you don't know how the render array in content will change if you configure the view mode differently:

{{ node.field_rating.0.entity.term_field.value }}

I got the answer of my problem.

Actually first i wanted to show only label or title of term just in my node template. To get the title of first term is like below -

{{ content.field_rating[0]['#title'] }}

OR

{{ node.field_rating.0.entity.label }}

But I got to know that I have to show entire term (comma separated ) with link of term as well. The code below works -

{{ content.field_rating[0] }}
{% for key, value in content.field_rating %}
       {% if key > 0 %}
           {{ ' , ' }}
           {{ content.field_rating[key] }}
        {% endif %}
{% endfor %}


How to track users site use in a webform / contact form? I was wondering if anyone knows a way of adding some data to the end of the emails I receive from a contact / web form, such that I can see what pages users (authenticated and unauthenticated) have visited prior to submitting the form?

Something like:

Here is the main body of the web form.

Before submitting this form the user visited:
/node/1,
/node/12,
/contact-us,
/node/45,
etc etc...

This is more or less the feature of the Google Analytics Contact Form, Webform, Rules Email module.

  This module will instantly append Google Analytics information to the bottom of the Contact Form, WebForm, and Rules emails.

The mail would look something like:

You could definitely do this by creating your own Module, but I Google Analytics is free and is built for tracking this sort of thing.  Check out "Event Tracking" and "Goal Flow" in particular.


Is there a module for google maps in drupal 7? On a site that I am building (using drupal 7), there is a feature that I need to include that I can't seem to find; Google maps. I am looking for two things;

1: something that will allow you to put in your home address, and it will give you directions to a preset location

2: something that will allow you to imbed a map of the surrounding area of a preset destination by stating the location in a CCK

do either of these exist? if so, where can I find them?

I need it to look like this:
where instead of an image, the map is actually an embedded google map.

There is the GMap Module module, but there is just a development snapshot, for Drupal 7.

There is the Simple Google Maps module.

  This module is about the simplest way to get a Google Map, and/or a link to a Google Map, displayed with your content. It provides a field formatter for Drupal 7 text fields. With this formatter, you can enter a single-line address that Google Maps would recognize into a plain text field, such as: 100 Madison Ave, New York, NY.
  And then on your Manage Display screen (or in Views field setup), you can choose to display the field with an embedded iframe Google Map, a link to a Google Maps map, or both; with or without the original address text.


How to use predefined drupal elements in a custom block/module? This is regarding the user block but the question is general and could be related to any standard block/module: How to use in a custom block elements that have been defined in standard modules? (for example the "username" field defined in the user block)
What is the way to access these elements in my code?

If the above is not clear, in other words what I would like to do is to use the "username" , "password" , "..." and all the elements defined in the user module, as independent elements in my custom block. And then build my own Submit which will include both standard drupal and custom items.

I think hook_form_alter will not do this trick because it is 1 level higher, right? i want to go one step more into details and manipulate the form items, no the form itself.

When building your own form in your module, you can simply read your defaults from $user variable. Then, in your submit function, use user_save() function to update your user.


How to use hook_entity_presave? I have a product type called package. It is a package of another product type which is called applications; when a user wants to create or update a package , I want to calculate the price of the package by adding the price of all applications in that package . I want to use hook_entity_presave(). but it doesn't work. I have put my function here.

My question: what should I check exactly against the $entity->type? My node type? Or my product type? It doesn't work either way.

function itunesdev_entity_presave(&$entity, $type) {
  if($entity->type == 'package') {
    $product_ids = array();
    foreach($entity->field_products[LANGUAGE_NONE] as $key => $pid)
      $product_ids[] = $pid['target_id'];
    $products = entity_load('commerce_product', $product_ids);
    // reset default price
    $entity->commerce_price[LANGUAGE_NONE][0]['amount'] = 0;
    foreach($products as $pid => $product) {
      $entity->commerce_price[LANGUAGE_NONE][0]['amount'] += $product->commerce_price[LANGUAGE_NONE][0]['amount'];
    }
  }
}

Function hook_entity_presave acts on an entity before it is about to be created or updated

Code:

  function hook_entity_presave($entity, $type) {
    $entity->changed = REQUEST_TIME;
  }

source :  Drupal API


Where do I add my own javascript or jquery so that it executes after the DOM is ready in Drupal 7? The site I'm working on is here.  The theme is modified Bartik theme.

Here is the code I ended up with.  The actual script inside the function works in Chrome console.

//Scripts that are required to run after DOM is ready
jQuery(document).ready(function)() {

    // Make the parent menu item of the active sub-menu item also active.
    jQuery('#block-system-main-menu li.active-trail > a').addClass('active');
}

I read a few articles and eventually ended up making a new file here:
/sites/all/themes/brainfx/js/brainfx.js

And I call this file from the theme's template.php file inside the brainfx_preprocess_html function with this code:

drupal_add_js('sites/all/themes/brainfx/js/brainfx.js');

You'll see it shows up in the head tag on the site.  But its not working.  What do I need to do to correct this?

There is a syntax error in above code. Change the js file contents to below. It will work as you expected !

jQuery(document).ready(function () {

    // Make the parent menu item of the active sub-menu item also active.
    jQuery('#block-system-main-menu li.active-trail > a').addClass('active');
});

Checkout the api for drupal_add_js it has an options array which allows you to give the scope where you want to load it like header or footer.

So I would do it something like this

drupal_add_js(drupal_get_path('theme', 'brainfx') . 'js/brainfx.js', array('scope' => 'footer'));

You can also add it to your theme info file like
scripts[] = myscript.js


Display menu Shopping cart (# items) and total amount In the user menu, I added a menu link to the shopping cart:

Title: "Shopping cart (# items)"

Path: "cart/my"

How to add the total amount of the order, at the end of the title ?

I think it is necessary to use the file "template.php" of my theme.

/**
 * Implements hook_menu().
 */
function commerce_cart_menu() {
  $items = array();

  $items['cart'] = array(
    'title' => 'Shopping cart',
    'page callback' => 'commerce_cart_view',
    'access arguments' => array('access content'),
    'file' => 'includes/commerce_cart.pages.inc',
  );

  $items['cart/my'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'commerce_cart_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'commerce_cart_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  $items['checkout'] = array(
    'title' => 'Checkout',
    'page callback' => 'commerce_cart_checkout_router',
    'access arguments' => array('access checkout'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/commerce_cart.pages.inc',
  );

  // If the Order UI module is installed, add a local action to it that lets an
  // administrator execute a cart order refresh on the order. Modules that
  // define their own order edit menu item are also responsible for defining
  // their own local action menu items if needed.
  if (module_exists('commerce_order_ui')) {
    $items['admin/commerce/orders/%commerce_order/edit/refresh'] = array(
      'title' => 'Apply pricing rules',
      'description' => 'Executes the cart order refresh used to apply all current pricing rules on the front end.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('commerce_cart_order_refresh_form', 3),
      'access callback' => 'commerce_cart_order_refresh_form_access',
      'access arguments' => array(3),
      'type' => MENU_LOCAL_ACTION,
      'file' => 'includes/commerce_cart.admin.inc',
    );
  }

  return $items;
}

/**
 * Returns the title of the shopping cart menu item with an item count.
 */
function commerce_cart_menu_item_title() {
  global $user;

  // Default to a static title.
  $title = t('Shopping cart');

  // If the user actually has a cart order...
  if ($order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

    // If there are more than 0 product line items on the order...
    if ($quantity > 0) {
      // Use the dynamic menu item title.
      $title = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
    }
  }

  return $title;
}

You can use https://www.drupal.org/project/menu_badges to accomplish that.

  Once enabled, go to Administration > Structure > Menus, and click
  "list links" next to the menu containing the target item. Click "edit"
  next to the item and select the badge to display with the Display Menu
  Badge select box.

Or you can set the parent menu item of the Shopping cart (# items) link provided by the cart module to your menu. This menu item is provided by commerce and by default can be found in the navigation menu at admin/structure/menu/manage/navigation


How to load module include files in .test file? I'm trying to update the Drupal 7 version of the password_policy.test file that is included with the Password Policy module. When I run the tests, I'm getting "Fatal error: Call to undefined function password_policy_constraint_uppercase_validate()".

The function in question is in an include file in the constraints subdirectory, located inside the module's directory. I've tried adding to the test's setUp() function, along the lines of:

drupal_load('module', 'password_policy');
module_load_include('inc', 'password_policy', 'constraint_uppercase');

I've also tried adding the module_load_include line inside the individual test method generating the error. However, none of my attempts so far appear to be working and the error still persists.

How should I go about loading the ./constraints/constraint_uppercase.inc and other include files, so that the necessary functions are loaded prior to the tests being run?

You have a flaw in your code, module_load_include works by including files relative to the module base dir, so you should do

module_load_include('inc', 'password_policy', 'constraints /constraint_uppercase');

to include password_policy/constraints/constraint_uppercase.inc

When you do

module_load_include('inc', 'password_policy', 'constraint_uppercase');

You instead try to include password_policy/constraint_uppercase.inc which doesn't exist.

I believe you can add in the modules .info file:

files[] = constraints/includeme.inc
files[] = constraints/includeme2.inc
files[] = tests/included.test


How set div in a specific position inside .tpl.php file I use views module in my website (built in drupal-7). I have a custom theme.
I have set a views-view-fields--XX.tpl.php like follows.

    <?php /**`
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */
?>

<?php foreach ($fields as $id => $field): ?>

<?php if ($id == 'field_voti'):?>

<?php endif; ?>
    <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
    <?php endif; ?>
    <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
    <?php if ($id == 'distance'): ?>

<?php endif; ?>
<?php endforeach; ?>`
"

in order to insert some fields into a new div with a specific class.

With firebug I see the following:

..

    ..
    ..

..

..

..

All that I want to do now is to have the div with class="uniscicampischeda" before the div with class="views-field views-field-field-foto", so that with css I will give the right attributes (I want class "uniscicampischeda" with float=right attribute)
HOw can I do that? do I have to write some code into views-view-fields--XX.tpl.php file? How?
Can anybody help me?
Thanks.

Well, there are three solutions for your problem,

Forget about the div with class uniscicampischeda and try to work with the existing classes in order to align them to right.
If you want to insert the div.uniscicampischeda, try to find out which one of the PHP lines generates the
..
, then edit the .tpl file and put the DIV before that PHP line.
As the last solution and also the most complicated one, in your template.php create function hook_preprocess_views_view_fields(&$var), in this function get the Views fields value and insert them in to the $var array, then in the .tpl file use those keys of the $var array as the variable that generates the corresponding value. Using this solution you will have much more freedom to theme your view output.

If you need help about any of these solutions just let me on it.

try edit your  views-view-field--XX.tpl.php not FIELDS, also double check your iteration end starting and closing tags for the div.

Also take note that firebug will auTO-CLOSE an unclosed HTML tag so check the :view-source in order to be sure whats rendered in HTML...


How to create arguments in path with regular page node instead of module, yet pass them to a module I know how to create a URL with hook_menu() in a module, but is it possible outside a module?
Here's what I'm needing/asking:
My front-end guy wants to create a page as a node using a Content Type via the Content menu. The URL for this content type needs to be something like www.somesite.com/some-page/arg1/arg2. Can this be done without a module defining the route with hook_menu() in a module?
If so, in my module that needs to do the work, it needs to collect these args and use them to insert data into the DB.
Is it possible for him to create a path with arguments that I can get? If so, what would be the best way to get these args to my module that is going to work on the backend.
I could do this all day with hook_menu() in module, but the front-end guy seems adamant that he can create a node and get the args from it's path. I don't understand how he can do that.
Thanks in advance.
Cy

https://www.drupal.org/project/pathauto
will help you on your quest ... to do this make custom fields to collect the arguments then use tokens to replace them...
Edit:
but if your developer is using the front end to create content (nodes) its easy to create path arguments ...
my idea was to make the fields to help generate the "path" ...
then in your module you have to simply load the node then access the fields .. sure there is more ways to do this like look in to the path and explode out the "/" then use them but way easier just to get from the loaded node object.
other than that can you please up date your question to be more clear


How do I get a block configuration value in a module? I created a custom block that contains a form field.

This is my blockSubmit() method.

public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue('my_text_field', $form_state->getValue('my_text_field'));
}

Now I want to access the my_text_field value from outside the custom block class.

You can load the block configuration entity, and get the settings.

$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
  $settings = $block->get('settings');
  $my_text_field = $settings['my_text_field'];
}

$block_id is the machine name you see in the block layout when you save the block.

Edit: Store module configuration

If you want to store configuration for modules don't use a block form, but use a configuration form. Reference https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms
(see comment from @Berdir)

Dump all blocks and their settings

$blocks = \Drupal\block\Entity\Block::loadMultiple();
foreach ($blocks as $key => $block) {
  $settings = $block->get('settings');
  var_dump([$key => $settings]);
}

I understand that the code above sounds like it should work, Block::load($bid) and $bid is from the annotation of the Block class. But the start of my code is this:
/**
 * Provides a 'SearchFiltersBlock' block.
 *
 * @Block(
 *  id = "search_filters_block",
 *  admin_label = @Translation("Filters"),
 * )
 */
class SearchFiltersBlock extends BlockBase {

yet, ::load('search_filters_block') returns NULL.
I tried this: Block::loadMultiple() to see what blocks existed and i see one with the id "filters" and it has plugin value "search_filters_block".
No idea.


How to fix view with no ID I get WSOD when I try to access the views page (admin/structure/views).

I get the notice below in the error log followed by the error.

Notice: Undefined index: id in Drupal\Core\Config\Entity\Query\Query->Drupal\Core\Config\Entity\Query\@closure() (line 92 of /home/pierost0/public_html/core/lib/Drupal/Core/Config/Entity/Query/Query.php).

Drupal\Core\Entity\EntityMalformedException: The "view" entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\Entity->toUrl() (line 189 of /home/pierost0/public_html/core/lib/Drupal/Core/Entity/Entity.php).

I have disabled all views through Drush but there's seems to be one empty view. Take notice on the screenshot. An empty view is enabled.

Is that view my problem? Where are the views files, or entries in the db so I can have a look for the solution there.

If you have access to the database check the table config for all entries starting with views.view.*
One of these entries might be empty or with a corrupt uuid. If so, take a backup of your database and try to manually delete this entry and see what happens.

Update
According to coments below I suggest taking a database backup and then delete views one by one from the database until the error is gone


Using Acquia for a production site and running Wordpress concurrently I've been building a website for my library in Drupal 6 using the Acquia Installer package on my local machine, a Win7 PC. I'm also going to need to run 2-3 Wordpress blogs alongside Drupal on the same machine, both on my local machine and when everything is migrated to our Server 2008/IIS 7 machine.

Do I need to ditch Acquia Installer now while still developing in order to run WP alongside Drupal? I've thought about installing WAMP alongside Acquia just to run WP on my local machine. But that seems like it would kill my local machine, running two separate installs of Apache, MYSQL, PHP, etc. And Acquia + WAMP probably isn't the smartest way to set up an efficient production environment on my server.

Acquia Installer is just an *AMP package. It installs standard versions of Apache, MySQL, and PHP, so you can configure Apache for multiple vhosts just as you would on any other machine.

Here's a guide to setting up vhosts on drupal.org http://drupal.org/node/111238

If you are deploying to IIS, I'd suggest at least testing your site locally before you push to live. These links may be of help:

http://learn.iis.net/page.aspx/505/install-drupal-on-iis/
http://www.microsoft.com/web/downloads/platform.aspx

The second is a Microsoft IIS installer with native Drupal support. MS are supporting Drupal as part of their Windows 8 push, so there are more resources around for IIS as a platform than previously.

Thats what I would recommend, actually ditching the Aquila installer and using WAMP locally for both Drupal and Wordpress on different Apache vhosts. Then in production host it on a traditional LAMP server.

The other alternative would be to make your Drupal 7 install a "multisite" with different URLs and settings in /sites//modules etc. and host all the Blogs and the Drupal sites on Drupal, its MORE than capable and the blog modules are all in core default install so you already have everything :)


Creating an editable table which can be updated I have a site with about 150 users. I am going to implement a system whereby things that they do in the real world (it's a fitness company), such as attending sessions, introducing new customers etc will earn them points.

I would like to create a table with 3 columns:

Name | Points | Update

so something like this:

The idea being that my client (editor role) could log in and amend the points that each user has and then click update to modify each row. I guess the table would be equally useful if there were just a single 'update' button at the bottom of the table to update all entries at once.

I don't know how I might go about making a table such as this 'editable', but would really appreciate some pointers as to how you might accomplish this. I would stress that I'm okay with using contributed modules, but quite poor with creating modules and PHP in general!

For your requirement Slickgrid is the best option for you and for that you need to use views module.

At the front end, users can show/hide, resize, reorder columns &
resize the height of the grid. These settings will be stored per user
and used next time the grid is shown. Saving the view (via the usual
views UI) will reset these settings.

For every field defined in the view, you can set its column width, whether it's sortable, and formatters (how the cell data is displayed), an editor, a validator and filters (for filtering the column data).
This modules comes with the following plugins ready to use:

Editors:

Inline cell editor - for excel-like editing of text & numeric data.
Popup field form - the field form pops up in an overlay. All field types can be edited.

Features of the grid:

Grouping field - group fields with a common value together
Collapsible taxonomy fields (tree structures)
Tabs - organise columns into tabs
Resize, reorder & hide columns
Delete entities via the grid
Force fit columns (to fill the available column space)
Undo (undo previous changes - uses node revisions)
Set viewport height
Set row height
Add entities via the grid*
Clone entities*
Export data (via the views data export module)*
Multi edit/delete/clone/export (checkboxes will be displayed in the rows - select as many rows as you want to perform action against)***

or as  Pontus Nilsson said use this Editable Views module.

You need the WYSIWYG module. Once you have installed the module, you'll need to install an editor, such as CKEditor or IMCE.


How do I show/hide elements on a page using jquery? I am trying to hide check-box selectors in the custom search module when the page initially loads and then have a clickable link to show them. I have the clickable link working but the check-boxes are initially in a visible state. How can I hide the check boxes when the page/module loads? I tried placing the following code in my THEME_form_alter(&$form, &$form_state, $form_id) function

drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types")[0].hide(); });', 'inline');

and

drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types").hide(); });', 'inline');

But neither worked. Any help would be appreciated. thanks

the easiest way of adding custom javascript-snippets is to create a custom.js file in your themefolder and declare it in your theme.info file like scripts[] = custom.js. Add all your snippets there.

In your JS file you can hide the elements.
If you have multiple checkboxes create an array and hide them with a for each loop.

example

// create array with stuff you want to hide
    checkboxes = [
        '#checkbox1',
        '#checkbox2',
    ];

// Hide arrays
    for (i = 0; i < checkboxes.length; i++) {
        jQuery(checkboxes[i]).hide();
    }

For Drupal 7

drupal_add_js('(function ($) { $("#edit-custom-search-types").hide(); }(jQuery));', 'inline');

Working with JavaScript and jQuery


change quicktabs default tab according to current documentation of for change alter quicktabs should use this method
in my module

mymoule_quicktabs_alter(&$quicktabs){
    $quicktabs->default_tab=2;
   }

when i print result with dsm  it changed applied, but it not apply to visual output of quicktabs.

tell me how i can change quicktabs default tab ?
tnx

Its not done simple, by default quicktabs ordered by wieght,
Quicktabs has quickly become one of my favorite Drupal modules of all time. To think that I was actually wasting time creating tabs by using jQuery plugins, and writing custom AJAX. Creating tabbed content is one of the most popular techniques used on the web today, and with Quicktabs it has never been easier to add tabs to your Drupal site - even with AJAX!

First you'll want to install Quicktabs

Once you have Quicktabs installed, there are a couple of ways to generate tabs. You can do it through the Drupal interface, or you can do it programmatically, but first, make sure you have some content that you want to show in tabs! Quicktabs works with your existing content. You can tab between views, blocks, nodes, or a mixture of these.

For this demo, we'll use Views and set up 2 displays filtered by a certain taxonomy term. We will then create a tab that displays nodes of each taxonomy term respectively. Make sure you have some taxonomy terms to choose from for each post. Then you'll want to create a view called "my_listing", or whatever makes sense for you.

Once you have created your View, create a couple of different "page" displays. Name each display according to your taxonomy term, so if you want to tab between say "Development" and "Theming" nodes, each page display will be named respectively.

Since you're creating page views, you'll have to specify a URL for each under the Page Settings section. You can use something like "list/development" and "list/theming" respectively. This is required by page displays, but it is also good if a user for some reason does not have javascript enabled, they will still be able to see the listings, just not through AJAX.

Also, for simplicity, make "Row style" node, so we don't have to play with fields.

Under "Filters" filter on each display for that specific taxonomy term, so that each display is only displaying nodes of whichever taxonomy you choose. Save the view.

Now that you have some content to play with it's time to create some tabs. Browse to admin/build/quicktabs and click on the "New QT block tab".

By default, Quicktabs creates a block for you which you can then place anywhere in the site like a regular block, but there is also a way to output your quicktabs in code, which i'll show you further down.

In the Block Title field, give your block a meaningful title. Next is the style dropdown, where you can select between various styles of tabs. You can also select "no style" so you can theme them your own way

The next field allows you to select whether or not you want your tabs to be AJAX. In most cases you will want to use AJAX so that you only load the second view when the user requests it.

The "Hide empty tabs" will only work if you do NOT use AJAX, which is kind of unfortunate. But, an easy way to deal with this is to use the "empty text" area in your views to give the user a friendly "There is no content here" message.

The next section is where you will start creating your tabs

Let's say the view you created with the 2 page displays are for a taxonomy term "Development" and one for "Theming". Give each tab their respective title. For the Tab type, select "view". In the tab content section, select the view you created (my_listing). Then select the display you want to show. For the Development tab, show the display that filters on Development. For the Theming tab, show the display that filters on Theming. You can also pass arguments into your Quicktabs to use with Views that accept arguments which is really cool, but I won't be covering that here.

Click save. You now have a block available for you to place anywhere on your site, that will tab between nodes of each taxonomy term! Very cool! But, what if you dont' want to use a block...what if you want a bit more control to place these tabs wherever you want? It's easy.

On your tabs listing page (admin/build/quicktabs) hover over the 'edit' link and take note of your quicktabs ID in the url. (quicktabs/1/edit). If this is your first quicktab, the ID will be 1.

Now to print out your quicktabs, all you need to do is call this function and run it through theme("quicktabs"); like this:

$tabs = quicktabs_load(1); // where 1 is your quicktabs id
$mytabs = theme("quicktabs", $tabs);

return theme("my_custom_template", $mytabs);

Then in your custom template, just print out the mytabs variable and you should see your quicktabs!

The easiest is qt- =  in the new version of quick tab it takes as a query string


How to add css to specific blocks or view with CSS injector module? How to add css to specific blocks or view with CSS injector module?

I can add css to specific pages, but what about blocks, views and all sorts of other nodes?

I am try already this but i think it would be helpfull

Use php section to add css against any view or block
and try this one

<?php
if ( $block->module == 'your_block_id/name'){
          //add some code here
}
?>

Or can do it by add a class in view or block

Using the CSS Injector module, there is not a way to only add CSS to pages that include specific elements such as Views, blocks, etc.

However, that's generally OK. If you're using Drupal's built-in CSS aggregation (and/or Advanced Aggregation), you're really just looking at couple hundred bytes per page, which should be cached by the browser, making those tweaks fairly negligible in terms of page load times.


How to populate DB values in content type field, drupal 7 I have created a content type with 4 field in Drupal 7. One field is of list type, say for listing countries. I have tables in DB for saving country_id and country_name. Is there any way to connect the DB table and content type field? I want to list all these countries in the content type's country field.

You have to install Content Construction Kit (CCK) module. After installing this module you get a text field for Allowed value function in field setting of desired field. Put the function name here to get country list. Also put following function in a module.  You may have to modify query as per your requirement.  After doing all these thing you will able to get country list in that field.

function _get_country_list(){
    $country = array();
    $query = db_select('country', 'c');
    $query->fields('c', array('country_name','country_id'));
    $result = $query->execute();
    if ($result) {
        while ($row = $result->fetchObject()) {
            $country[$row->country_id] = t($row->country_name);
        }
    }
    return $country;
}

You could make use of views.api

Implement views API

function MYMODULE_views_api() {
    return array(
        'api' => '3.0-alpha1', // Youre api version
        'path' => drupal_get_path('module','MYMODULE'). '/views',
    );
}

and create a file named MYMODULE.views.inc put it in /views folder

Read available functions here views.api.php


Retina image support (@1x @2x @3x) I've been struggling for a while to figure out how to support higher pixel density screens for my images in drupal. I have 3 variations for every image on the site (@1x, @2x, @3x) but I haven't been able to find an easy way to use them. I searched around and found articles like:
https://www.advomatic.com/blog/adding-responsive-images-to-your-drupal-8-site
and https://evolvingweb.ca/blog/making-drupal-websites-retina-ready

but they usually talk about using the retina module for drupal which seems to not pass security adviory policy or are just adding different image styles and using the picture tag. Is there no way to use just srcset and using 3 different images for different dpi in drupal?

Ideally I'd like to have an image field which will just let me upload 3 images for different dpi.

I think the answer from @ipwa is close but is not quite there.

What you want is an output like this:

<img src="/fallback.jpg" srcset="/1x.jpg 1x, /2x.jpg 2x, /3x.jpg 3x" />

Here's what you need to do:

Enable both the Breakpoint and Repsonsive Image Style modules.
Add an image field for uploading 1 image to a content type. Editors should upload the highest quality image needed.
Configure three normal image styles that produce the desired resolutions for each of the 1x, 2x, and 3x pixel densities.
In your theme, or a custom module, create a breakpoint yaml file with the following contents:

my_module_or_theme.image_pixel_density_only:
  label: Pixel Density Only
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
    - 2x
    - 3x

Rebuild caches.
Add a new responsive image style.
Configure the responsive image style so that it uses the breakpoint group that you just created. This should expose a 1x, 2x, and 3x fieldset. For each of these fieldsets, select type "Select a single image style." and choose the appropriate image style.
Configure the image field formatter for image field you created in step 1 to use the responsive image style you just created.

Drupal will output the srcset just like I described above and will not output a "sizes" attribute (which you don't need). Browsers will know what the pixel density is of the device and automatically select the most appropriate image based on that.

You can do this in Drupal 8 with just core:

Skip creating specific breakpoints in your theme, they aren't needed
with this approach.
Setup your different image styles at
admin/config/media/image-styles. Usually something like, Author
Small, Author Medium and Author Large.
Create a responsive image style at
admin/config/media/responsive-image-style. Make sure the Responsive
Image module is enabled first.
Ensure "Responsive Image" is selected for the "Breakpoint group".
Choose a suitable "Fallback image style". Click "Save". The
following screen is where the secret sauce is.
Under the "1x Viewport Sizing []" fieldset, Select "Select multiple
image styles and use the sizes attribute."
Select each of Image styles you'd like to use.
Adjust the Sizes value as needed. The default here 100vw is
hard-coded for a good reason, it's a pretty sane default and works
well in most situations. Customize this is you want even finer
control.

From: https://chromatichq.com/blog/responsive-images-drupal-8-using-srcset


How do I add class "caption" into image? I using image field with insert module to upload image.
After select an image and upload, I press "insert".
The image appears in body but the script of image doesn't have class "caption".

<img src="/sites/default/files/apple.jpg" title="Some description image here" height="260" width="500">

How do I add class "caption" into image?

There is an option in the Insert section of the field to add classes. See the screenshot below.

For adding caption to image there is some module

Image Caption

  DESCRIPTION:

  This module uses JQuery to dynamically add captions to images. The
  image title attribute is used to create the caption. It basically
  wraps the image in an html container div, takes the image title text
  and appends that in a child div underneath the image. Technically, it
  works by implementing Drupal's hook_nodeapi to add one small snippet
  of captioner jquery to the head section of the page when a node of the
  configured type is viewed.

Image Field Caption

  Description: Adds an extra text area for captions on image fields.

  Similar to the alt and title text fields available with an image
  field, the caption text area can be used to enter text or html
  descriptions of an image.

JCaption

  Description: This is a simple module for Drupal 7.x that uses jQuery
  to transform the TITLE or ALT attribute of a image to a image caption.
  There is a settings page with lot's of possible configuration. The
  image caption won't show in the WYSIWYG-editor, but will be visible
  when you view the node.

  The module differs in several ways from similar modules.


How do I set the cookie lifetime? I'm having trouble setting the cookie lifetime in my D8 instance.  I'd like to set it to zero so that closing the browser logs-off the user.

I've added ini_set('session.cookie_lifetime', 0); to the site/default/settings.php file.  There was no previous cookie_lifetime reference in the file.  I added the line.  I've also cleared the Drupal cache and cleared my Chrome cache.  Sadly, it's not being respected.  Sessions still persist after browser close.

I've searched the entire codebase for ini_set('session.cookie_lifetime', 200000); but it doesn't appear to exist in my site. I don't see where Drupal is setting the cookie lifetime.  I've also tried adding the setting via a php.ini file in the root but that's being over-ruled by Drupal.

I feel like this is a simple thing, so I'd like to avoid plugins. Looking forward to hearing from everyone.  Thanks in advance.

For the session cookie options D8 uses container parameters instead of settings. Create a services.yml file in the same folder as settings.php. The default values are in default.services.yml. You can copy this file to services.yml and modify it:

/sites/default/services.yml:

parameters:
  session.storage.options:
    # Default ini options for sessions.
    #
    # Some distributions of Linux (most notably Debian) ship their PHP
    # installations with garbage collection (gc) disabled. Since Drupal depends
    # on PHP's garbage collection for clearing sessions, ensure that garbage
    # collection occurs by using the most common settings.
    # @default 1
    gc_probability: 1
    # @default 100
    gc_divisor: 100
    #
    # Set session lifetime (in seconds), i.e. the time from the user's last
    # visit to the active session may be deleted by the session garbage
    # collector. When a session is deleted, authenticated users are logged out,
    # and the contents of the user's $_SESSION variable is discarded.
    # @default 200000
    gc_maxlifetime: 200000
    #
    # Set session cookie lifetime (in seconds), i.e. the time from the session
    # is created to the cookie expires, i.e. when the browser is expected to
    # discard the cookie. The value 0 means "until the browser is closed".
    # @default 2000000
    cookie_lifetime: 2000000

You would like to modify the cookies and session values you set #default values to the same values of session or cookies otherwise it will not work in drupal 8

**Ex : #default 0
gc_maxlifetime: 0**

parameters:
  session.storage.options:
    # Default ini options for sessions.
    #
    # Some distributions of Linux (most notably Debian) ship their PHP
    # installations with garbage collection (gc) disabled. Since Drupal depends
    # on PHP's garbage collection for clearing sessions, ensure that garbage
    # collection occurs by using the most common settings.
    # @default 1
    gc_probability: 1
    # @default 100
    gc_divisor: 100
    #
    # Set session lifetime (in seconds), i.e. the time from the user's last
    # visit to the active session may be deleted by the session garbage
    # collector. When a session is deleted, authenticated users are logged out,
    # and the contents of the user's $_SESSION variable is discarded.
    # @default 200000
    gc_maxlifetime: 200000
    #
    # Set session cookie lifetime (in seconds), i.e. the time from the session
    # is created to the cookie expires, i.e. when the browser is expected to
    # discard the cookie. The value 0 means "until the browser is closed".
    # @default 2000000
    cookie_lifetime: 2000000


Run drush cron for a single module Is it possible to run drush cron over a single module, something similar to "drush cron my_module"?

You can do

drush php-eval 'my_module_cron();'

and it should run.

You can implement your own drush commands. Have look at the sandwich example code in the drush source package.


How to render element array piece by piece I have template form.html.twig Drupal commerce is using it to render cart form. I made override of that template, to be able to change it only for cart form, without affecting other forms. That part works well.

Form template looks like this:

<form class{{ attributes }}>
  {{ children }}
</form>

Where "children" is markup. But (even not documented in template it self) there is also "element" array. So I can print the it instead of children and get the same results:

<form class{{ attributes }}>
  {{ element }}
</form>

This also works well.
Now, I need to print it piece by piece. If I put loop like this:

  {% for single in element %}
    {{ single }}
  {% endfor %}

I get some form elements doubled, so obviously some elements must be excluded. But which ones?

Here is the list of all element keys inside this "element" array:

#action
#prefix
#suffix
#pre_render
#cache
#attached
#substitutions
#form_id
#type
#build_id
#token
#id
#attributes
#method
#theme_wrappers
#defaults_loaded
#tree
#parents
#validate
#submit
#theme
#processed
#required
#title_display
#description_display
#errors
#array_parents
#printed
show_view_elements
output
footer
edit_quantity
remove_button
form_build_id
form_token
form_id
actions
#sorted
#children
#render_children

How can I find out what elements  should I print and what to exclude to get the same result (valid form) as when printing top element:

{{ element }}

Update: purpose of this is to render cart page a bit differently. Now, inside the form element I have first table with purchased items, then, bellow table goes div with sub-total and total prices and then div with "Update" and "Checkout" buttons.
What I want is to display those 3 elements in 2 columns. In left one there should be only table with items and in right prices, buttons and some additional info.

BTW, I'm already displaying another form that way. It's template file looks like this:

<form{{ attributes }}>
  {{ title_prefix }}

  {{ element.pages }}
  {{ element.elements }}
  {{ element.form_build_id }}
  {{ element.form_token }}
  {{ element.form_id }}
  {{ element.footer }}
  {{ element.actions }}
  {{ element.children }}
  {{ element.progress }}

  {{ title_suffix }}

</form>

There I print progress bar bellow the other form elements.
But I have problem achieving the same with cart form.

Succeeded it "my way". Template now looks like this:

<form class{{ attributes }}>

{{ element.output }}
{{ element.footer }}
{{ element.form_build_id }}
{{ element.form_token }}
{{ element.form_id }}
{{ element.actions }}

</form>

element.output prints the table
element.footer prints the prices
element.actions prints the buttons
and other fields are printing necessary hidden fields

I know that @4k4 is right and I even tried solution he proposed before, but for some reason it didn't work for me (probably my mistake) and I didn't have more time to spend on this and this solution works well.

Posted this, because it's answer to this question and IMHO this should be "legal" way to print form, achieved only from twig without forcing on creating theme function and other stuff.

Please be gentle with minuses.


Why is a template being looked in a theme and not in my module? I have created a custom module. in that module I have create a custom twig template using hook_theme function

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
    )
  );
}

Then I created a custom block using my module here is the code of the block

public function build() {
    $config = \Drupal::config('mymodule.config');
    $role = $config->get('role');
    return array(
      '#theme' => 'mymodule_settings',
      '#role' => $role,
    );
  }

I created a templates directory in my module and inside that directory I have created mymodule-settings.html.twig file.

Cleared the cache but Drupal gives me the following error.

Twig_Error_Loader: Template "themes/subtheme/templates/mymodule-settings.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/subtheme/templates/mymodule-settings.html.twig" in the Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 45 of themes/basetheme/templates/block.html.twig).

My theme is a subtheme. Why Drupal is looking for the template in the theme and not in my module?

Try like this:

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
      'template' => 'mymodule-settings',
    )
  );
}

You are missing to define template.


Programmatically node update while saving node How can I update the value of the field in the nodes while save/update the node?
When you save/update the node value from the field was taken and save in the same field in the other nodes.
I tried to do it hook_ENTITY_TYPE_presave()

$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
  $node->set('name_field', $value);
  $node->save();
}

But this causes infinite recursion

You can use hook_entity_presave

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

    if ($entity->getEntityTypeId()=='node'){
        $value="099545";
        $entity->set('name_field', $value);
    }
}

You can use hook_ENTITY_TYPE_presave

use Drupal\node\NodeInterface;

function mymodule_node_presave(NodeInterface $node) {
  $node->set('name_field', $value');
}

Here no need to load node.


How to create a line graph of the total user points on a profile page? I'd like to have a line graph of my users' total user points in time on their profile page. Users shouldn't be able to modify the graph: it should simply graph the user points from the day the user registered until today. I'd like to use the Charts module, but I don't know how I can provide the necessary data (date and daily total points).

Perhaps it's also handy to mention that the profile pages on my website have been overridden with "user_view" (see: How to create a profile page?) into a panels page.

How can I achieve this?

Edit: I tried to find a solution, using Field Collections as @Felix Eve suggested in his answer. I've successfully added a Field Collection to my users, but I'm still stuck at these points:

Save the userpoints at the end of the day as a field collection item for all users.
Graph the userpoints in a Chart.

Solving these problems, solves this problem aswell.

I realize this is an old post, but I wanted to add a workable solution for those that find this question when searching the topic.

I've been able to use a combination of the Charts module to create a view that display the history of the user's total userpoints.

It is fairly straight-forward to create a view that displays all of the userpoints transactions of a given user, however, I found the trickiest part to be display a 'running total' of a user's points.

The following recipe should help you create a view that charts the progression of a user's points over time.

Step 1: Download, enable the Charts module

Step 2: Create a view that Shows "Userpoints", and create a block view with the Chart display format. Screenshot below:

Step 3: Add the relationship Userpoints:User

Step 4: Add the following fields:

Userpoints Transactions: Timestamp
Userpoints Transactions: Points
Global: Math Expression

Step 5: Set the expression for the math expression field to: [expression] + [points_1]. You should also adjust the label for this field.

Step 6: In the chart settings, set the label to be the timestamp field and the data to be the math expression. Also, set the chart type to line.

Step 7: Add a sort criteria to sort by the timestamp field. Set the timestamp format to be Y-m-d.

Step 8: Add a contextual filter: User:uid to filter by logged-in user's uid.

You may want to create a page view to see the chart in action:

You should be able to use Views Charts to create a view from the userpoints. Note that only a dev release is currently available for D7.


Sending a value to JavaScript I have set theme handler for a form in Drupal and this handler has a template file.
What is the easiest way to send a value from PHP to JavaScript in that include file?

The standard way to do this in Drupal is with drupal_add_js, using the "setting" type:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.

Easiest way is just to echo it out into a script tag:

<script type="text/javascript">
   var variableName = <?php echo $variable ?>;
</script>

If Drupal uses a templating language, you need to replace the <?php echo... ?> with the relevent output method...


Altering nodes title value I am trying to alter the title of my nodes to prevent URLS appearing in any title. This is the code I am using.

function mytemplate_preprocess_node(&$variables) {
  $node = $variables['node '];
  $variables['title'] = cleaner(check_plain($node->title));
}

cleaner() removes URLs from nodes. The above works perfectly on teasers, but not on full view or when the title is displayed in a list with other articles inside a block.

How can I make sure that the URL disappear whenever the concerned node's title is listed?

You need to implement both

template_preprocess_page() : this will take care of node full view mode.
temaplte_proprocess_node() : this will take care of node teaser view mode

In your theme template.php

function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your content type") {
    drupal_set_title("your_title");
  }
}

/**
 * Override or insert variables into the node template.
 */
function mythemename_preprocess_node(&$variables) {
  if($variables['type'] == "your content type") {
    $variables['title'] = "your title";
  }
}

Note:

  only changing in template_preprocess_node(), will now reflect on node teaser view as it will be overridden by page template.
  in order to change  you should use drupal_set_title() instead of $variables['title'].

Use template_preprocess_page() in the template.php to update the page title for full view, However please don't your code for hook_preprocess_node() as that code would be required for updating the page title for teaser view.

Examples:

// Example of updating the nodes title for all content types.
function MYTHEME_preprocess_page(&$vars) {
  // Check if the variable is of node type.
  if (!empty($vars['node']) {
    $updated_title = cleaner(check_plain($node->title));
    drupal_set_title($updated_title);
  }
}

To update the page title of specific page just update the if condition as below:

if (!empty($variables['node']) && $variables['node']->type == 'CONTENT_TYPE') {
  $updated_title = cleaner(check_plain($node->title));
  drupal_set_title($updated_title);
}

The above things will update the page title at the time of rendering, however the better solution is to clear the URL's from the node title before saving (insert/update) the node so that you wont need to modified at the time of rendering:

// Using the hook_node_presave() for removing the URL's from title.
function MyModule_node_presave($node) {
  $node->title = cleaner(check_plain($node->title));
}

Note: The hook_node_presave() will help you for new nodes and the nodes those you are going to update.


Enable SSL for whole Drupal 8 site I'm running a Drupal 8 site behind a nginx webserver. All http request are redirected to https. My problem is that rss links on that site are http links only.

With Drupal 7 by setting the base_url all links are shown as https links. In Drupal 8 this option is missing. How can I set the whole site to https? Is there a config option for setttings.php?

Depending on how the RSS links are rendered, I would suggest calling them over with a protocol-relative URL such as:

//domain.com/rss-feed....

This will force the information to be sent over based on the way the page was rendered.  If the page was rendered using https:// it will use https:// in place of '//'

To Enable SSL Certificate on Drupal, Write the following line of code in your .htaccess file.

RewriteEngine on

# Redirect to HTTPS

RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Drupal Time field for hour:minute:second.tenth of a second Is there a drupal field type to represent time for athletics sports events. e.g. for 100m sprint: 10.42 seconds but for 800m 1:40.89 (1 minute, 40.89 seconds)
In the format : hour:minute:second.tenth of a second

No time field will give you what you are looking for. They all work with Unix time, which is defined as 'the number of seconds since midnight, January 1, 1970'. The maximum granularity you will see is one second.

If you wish to record this information to one one-hundredth of a second, you will need to define the field and its formatting yourself.

Checkout this module HMS Field

  Displays a integer formatted as Hours, Minutes or Seconds.
  The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provides developers a way to add their own format.


Change article date format I'd like to change the date format that is used for articles in Drupal 8. It looks like it uses the Default medium date format by default. I added my own format at admin/config/regional/date-time, but I  can't find where to edit the format that articles use.

Is there a way to do this from the CMS or does this need to be done in code?

So after spending more time than I care to admit looking into this, I've come up with two solutions to this.

Solution 1

One way to do it is with the date function that darol100 mentioned in his answer. Modifying his example for my case, in my node--article.html.twig file, I changed:

{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

to

{% set createdDate = node.getCreatedTime|date('j F Y') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

The advantage to this approach is that it's easy and quick. The disadvantage is I'm not using Drupal's built-in date format system.

Solution 2

In order to use Drupal's date format system, I first created my custom format at admin/config/regional/date-time. Then I edited node--article.html.twig as follows:

{% set createdDate = node.getCreatedTime|format_date('my_custom_format') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

This assumes I named my custom format "My Custom Format", which results in the machine name my_custom_format.

While this solution requires an extra step, I feel it's the more Drupal way to do it.

I learned about it on this page about Drupal's Twig Filters.

I used the following code for node--article--full.html.twig :

    {% set day = node.createdtime|date("d") %}
      {{ day }}
    {% set month = node.createdtime|date("M") %}
        {{ month }}

{% set date = node.createdtime|date("M d, Y") %}
   {{ date }}


Breadcrumb in drupal I want to breadcrumb in drupal8
that display as url as home / list page /  node page.
I just have in breadcrumb home > node page.
I use bootstrap breadcrumb.

Drupal 8 uses the page alias to build up the breadcrumb trail. Your "node page" would need to contain the "list page" alias to make it work e.g.
List page = /mylist
Node page = /mylist/mynode

If you want to use the menu structure then you could try this https://www.drupal.org/project/menu_breadcrumb

You can do it with theme_breadcrumb function. You just need to add you condition and return.In below example I am taking service node type page and list page which is created by views page and path is service.So my breadcrumb should be like this

Home>services>Service title

function theme_breadcrumb(&$variables){
 $path = \Drupal::service('path.current')->getPath();
 $path_args = explode('/', $path);
 $home_link = \Drupal\Core\Link::createFromRoute('Home', '<front>');
 $output = '';
if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
$typeName = $node->bundle();
if ($typeName == 'service') {
$url_object = \Drupal::service('path.validator')->getUrlIfValid('service');
$route_name = $url_object->getRouteName();
$service_link = \Drupal\Core\Link::createFromRoute('Services', $route_name);
$breadcrumb = array();
$breadcrumb[] = $home_link->toString();
$breadcrumb[] = $node->getTitle();
$output .= '
' . implode('> ', $breadcrumb) . '
';
return $output;

   }
 }
}


How to use $contexts in Page Manager Im trying to make a selection rule for variants in Page manger and it includes some data comparison so it has to be in php. My field data is inside the context, so the $contexts variable can be used, but I cant get the proper way to use it. In my case it is a field value of the node, that is specified by the argument in URL "node/%nid".

Can some body please give an example code to extract the field value from context in php?

First of all, I want to point out that since this issue got closed in December, ctools got much better support for handling fields in access rules.

With that said, $contexts, have a data value, which is either an object, or an array of objects, depending on whether your plugin requires one or more contexts.

To make the code easier to read, I usually do something like this: $node = $context->data;

Brief example code:

function contact_info_pane_content_type_render($subtype, $conf, $args, $context = NULL) {
  $block = new stdClass;
  $block->content = '';
  $node = $context->data;
  $block->content .= count($node->field_email) > 0) ? $node->field_event_mail['und'][0]['email'] : '';
  $block->content .= count($node->field_phonenumber) > 0) ? $node->field_event_phonenumber['und'][0]['safe_value'] : '';

  return $block;
}

panels php https://drupal.org/sandbox/rogical/2121111

This module would solve this issue


Using '#type"=>'container' to create a div wrapper around nested elements? From my reading a render array can define a wrapper div by using the '#type'=>'container'. I am inserting a render array in the page_alter hook function in the page_bottom region. It appears that the container type does not work in this case. The code below does not wrap the two #markupelements with the div wrapper but instead outputs the div then the content at the same level.

$page['page_bottom']["notices"] = array(
  '#type' => 'container',
  '#attributes' => array(
    'id' => array('notices'),
  ),
);

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "
",
  '#prefix' => '
',
);

$page['page_bottom']["notices"]['notices-tab'] = array(
  '#markup' => '
NOTICES &nbsp;10
',
);

What I want is the following.

NOTICES....

What I get is the following.

NOTICES....

--- Added
I did try #children earlier in the day and it didn't work as well. Before I left for the day I also tried with

$page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#suffix' => "
",
    '#markup'=>"Empty String", // added to see what it would do
    '#prefix' => '
',
);

This resulted in a completely out of sync html with the #markup tag being outside the #prefix/#suffix. I don't have the results on me now to post but if you try it you will see the results for your self.

I was able to obtain what you wanted using the following code.

  $page['page_bottom']["notices"] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices'),
    ),
  );

  $page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices-placeholder'),
    ),
  );

  $page['page_bottom']["notices"]['notices-tab'] = array(
    '#markup' => '
NOTICES &nbsp;10
',
  );

The output I obtain using that code as implementation of hook_page_alter() is the following.

NOTICES &nbsp;10

I tried using your code, and setting $page['page_bottom']["notices"]['#tree'] to TRUE, or setting $page['page_bottom']["notices"]['notices-placeholder']['#type'] to 'markup', but I always obtained the same result as you.

The only explanation I have is that, using your code, theme_container() (the function defined as theme wrapper for the "container" element) doesn't get any value for $element['#children']. That would explain why the container HTML output doesn't contain any children element, as the code executed by theme_container() is the following one.

  $element = $variables['element'];

  // Special handling for form elements.
  if (isset($element['#array_parents'])) {
    // Assign an html ID.
    if (!isset($element['#attributes']['id'])) {
      $element['#attributes']['id'] = $element['#id'];
    }
    // Add the 'form-wrapper' class.
    $element['#attributes']['class'][] = 'form-wrapper';
  }

  return '
' . $element['#children'] . '
';

References

system_element_info()
drupal_render_page()

you have to render the $page : return drupal_render($page)


Turn off template suggestion for specific fields I have the problem, that the theme / template suggestion comments destroy the html when they are outputted as values.

{% set img_uri = "fields.img.value"%}

{{ dpm(img_uri)
style="backround:url({{ createMyImagePathCustomTwigFunction(img_uri) }});"

Results in:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/views/views-view-field.html.twig' -->
public://img/person/joshua-ness-117255-unsplash_0.jpg
<!-- END OUTPUT from 'core/themes/stable/templates/views/views-view-field.html.twig' -->

<!-- END OUTPUT from 'core/themes/stable/templates/views/views-view-fields.html.twig' -->

..as wrong uri.

I know that I could dive deeper into the rendered array to find other versions.

However:
To change production templates in general only for enabling a developing environment seems wrong to me.

Better would be a hook that would remove field tpl suggestions in general as I don't need them.

I know I can write handler functions... that is what I do in the moment.

But cleaner would be to turn the suggestions off for views fields. How this can be done?

As it seems, that there is no solid alternative that works for field values I have written a Twig-Filter which returns the value via this php function:

public function removeHtmlComments($string) {

  $output = preg_replace(array('/<!--(.|\s)*?-->\s*/', '/\t+/', '/\n+/', '/[\r\n]/', '/[\n\r]/'), '', $string);

  return $output;
}

Try the following.

{{ file_url(fields.img.content|striptags|trim) }}


Hide dates in the present in .tpl.php files I've got a content type (Events) and they have event dates. Some of them have multiple dates, some of them haven't. But I want to hide the dates which are in the past.

Obviously, February 15th and April 18th are already passed. How can I hide them?

When I do var_dump($content) in the tpl, all I got is this:

15 February 2012 - 14:00 to 16:30

So it looks like I can't filter in PHP since it's already converted into HTML. Any idea how I can filter this?

EDIT: screenshot of my date section

Presuming you are using the Date module. In the Manage Display settings for the content type, modify the setting for the Date output and put 'now' in the 'starting from' box.

Maybe you could use a regex on it to get the date out? Parse that date with the strtotime() function to compare it to today's date? Then just add a class to the span and hide it with css or get the entire row out of the array.

The regex could look like this:
    /(<span class="date-display-single">)([0-9]{1,2}\s[a-zA-Z]*\s[0-9]{4})\s(.*)/

The second group should be your date and you can use the first and third group to reconstruct the line + the extra css class.


Problem with mobile_theme theme switcher module I've tried using mobile_theme to switch to a selected mobile theme when a mobile visitor browses. But using online mobile emulators: mobilephoneemulator.com and transmog.net I found that half of pages get shown as Desktop version pages.

I thought of using ThemeKey but I'll need to use  browser version, operating system to serve mobile content. But it could fail for Googlebot, Bingbot etc, they also need to see my mobile pages.

Is there any alternative auto theme switcher for mobile? I'm on shared hosting and can't use Browscap etc php modules.

mobile_theme wouldn't work with Drupal cache on. It is not mentioned anywhere in the documentation. We should use m.example.com for mobile url's for Drupal. I tried many such modules except for ThemeKey but the same problem( since I was using the cache).

I finally wrote my own module. But later found : simple_mobile_redirect to be good one but have not tried yet.

For one language site, you can use Mobile JS Redirect module for Drupal 7.

  This is a simple module that adds a JS in the HTML head to perform a redirect from a desktop site URL to a mobile one or the other way around. This is useful when Varnish or any other reverse proxy cache is being used to cache
  your site and keep a mobile vs desktop redirect working.