Show Webform confirm message in my custom panel page I'm new to Drupal. I have created a web form in my page using Webform module. I added my contact web form in a custom panel page. I use the Clientside Validation module to validate the web forms.

If the form validation is okay, I want to show the confirmation message at the top of the web form in my panel page instead of the default message location used in the page.tpl.php. I use the single page web site.

Can anyone help me to solve my problem?

I guess the problem is that the Clientside Validation module shows the message in the default location defined in the template.

You can check Clientside Validation Usage. Then you can see Error Message placement and Default location. I hope you can tweak your default message location from this:

  Here you can select the default location to display your error
  messages. You can choose between the following options:

  jQuery selector: This option will place a div containing all the    error messages inside the div that matches the jQuery selector
  entered in the "jQuery selector" field below this option.
  Top of form: This option will place a div containing all the error messages    above the form the error messages are for.
  Before label: This option will place the error before the label of the matching element
  Afterlabel: This option will place the error after the label of the    matching element
  Before input: This option will place the error    before the matching element
  After input: This option will place the error after the matching element
  Top of first form: This option will    place a div containing all the error messages above the first form.    This means that when there
  are multiple forms on a page, the errors    of the second form will be
  added to the error div of the first form    and will be displayed
  above the first form
  Custom function: (Advanced) Selecting this option requires you to enter a javascript    function name in the textfield "Custom function
  name" below this    option. This function name will be given to the
  errorPlacement option    of jQuery.validate()

You could use jQuery selector or Custom function.


Difference between $form_id and $form['#id']? What's the difference between $form_id and $form['#id'] in hook_form_alter() ? Why they have not the same values?

Next should make sense:

<form action="somepath" id="search-theme-form"> <!-- id = $form['#id'] -->
  <input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form"/> <!-- value = $form_id -->
</form>

Terms:

#form['#id'] = store html form attribute id:

  Used to populate form elements' id property. In rare cases,
  you can set this value yourself on a form element, to override the
  default setting.

$form_id - point to Drupal form function name, in html it's form hidden element:

  The unique string identifying the desired form. If a function with
  that name exists, it is called to build the form array.


how to Remove "Add new Content" from the Main page I have a front page in which blocks and some contents (ie story) were displayed.
These stories were marked as "Promoted to front page"; later, I unchecked them.
These stories are now gone, yet the blocks were present.

Now I have the following content on my front page:

"No front page content has been created yet.

Add new content"

How do I remove this content or text?

Just add this code to the page.tpl.php or page--front.tpl.php on Drupal 7.

find

<?php print render($page['content']); ?>

and replace with below code.

<?php  if(drupal_is_front_page())
                {
                    unset($page['content']['system_main']['default_message']);
            }
        print render($page['content']);
    ?>

And i believe you surely get all blocks or contents you posted on page.

and to remove page title on page like

Welcome to "website name"

find this code on page.tpl.php or page--front.tpl.php

<?php if ($title): ?>
<?php  print $title; ?>

<?php endif; ?>

and you can remove this code or else just make a comment over.


hook_block_view For an Array of Paragraphs Is there a way to use the theme() function to process an array of paragraphs, in a fashion to how theme('item_list', $theme_args) works?

If there is not a way using the theme function, what then is the "preferred" way to create a render array for an array of paragraphs?

There isn't a 'preferred' way, or built in function, to render an array of paragraphs. You could do it like this:

$build = array(
  'p1' => array(
    '#markup' => 'Something',
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'p2' => array(
    '#markup' => 'Something else',
    '#prefix' => '
',
    '#suffix' => '
',
  ),
);

Or this:

$build = array(
  'p1' => array(
    '#markup' => '
Something
',
  ),
  'p2' => array(
    '#markup' => '
Something else
',
  ),
);

Or you could build a theme function which takes an array of paragraphs and builds up an HTML string. Or you could use some variation of implode(), or a simple loop, and so on.

It really depends on how you want to approach it, there are several equally valid ways to solve that problem.


How do i get views field labels in the template file I am creating a view, and displaying view by using custom template files. As per theme suggestions I named the template file for fields as views-view-fields--blog-display--page.tpl. In this file I want to display labels for the view fields which i have given while adding fields. I tried using

<?php print $fields['label']->content; ?>

But not able to get the label.
What am I doing wrong?

As far as I see in the documentation for views-view-fields.tpl.php (I did not test it myself), the syntax seems to be something like the following:

<?php print $fields['myfield']->label; ?>

(you can also use $fields['myfield']->label_html)


How to set and inherit variables within different twig templates? I'd like to set a variable in my node.html.twig template:

{% set title = label %}
{{ content }}

The content consists of one field visible only, which has it's own template:

file-link.html.twig

How can I access the title variable of the node template in the file template? I am not sure if importing or extending is the right way since that might cause infinite recursion?

Edit

The file template looks like this (from the bootstrap theme):

{% spaceless %}
  {%
    set classes = [
      icon_only ? 'icon-only',
      not icon_only ? 'icon-' ~ icon_position|clean_class
    ]
  %}

    {% if icon_only %}
      {{ icon }}

        {{ link }}
        {{ file_size }}

    {% else %}
      {% if icon_position == 'after' %}
        {{ link }}{{ file_size }}{{ icon }}
      {% else %}
        {{ icon }}{{ link }}{{ file_size }}
      {% endif %}
    {% endif %}

{% endspaceless %}

Within that template I'd like to print the title of the respective node:

{{ link }}
{{ title }} {# << #}
{{ file_size }}

EDIT

You could write a theme hook in your "mytheme.theme", modifiy the "variables" array and add title to the specific field AND then move the template file (in the original post) to your own theme template directory, make the changes using your new variable (called maybe title) which was provided from theme hook.

OLD:

First of all, "node.html.twig" is TOO general to claim that it's content in the future will consist only one field (file-link).

At least rename it to "node--my-content-type.html.twig".
In the file-link.html.twig you won't able to reach the "title" variable (label) of the node.

You have the following work around:
{{ content|without('field_file_link') }}
{% include directory ~ '/templates/my-custom-twig.html.twig' with {'title': title}  %}

Which means:
 1. exclude your field from content.
 2. create your own twig template
 3. Pass any variable from the caller template you would like to pass.

Twig syntax / semantics is still changing, maybe my twig codes of lines can lead to error, but at least it will give you a hint / clue how to achieve this.


How to remove taxes if outside EU I have a custom checkout page. I have already included the Swedish taxes of different amounts in my product price. Now the customer wants me to remove the taxes if the buyer is outside the EU. I tried commerce tax remove but couldn't make it happen.
I was thinking if I use the base price instead of the commerce_order_total['und'][0]['amount'] for order order total and to use base price for products on line items?

Will this be correct?

Thank you.

You have three options:

1) Apply the patch from https://drupal.org/node/1240216. It will give you a rules action that will remove the tax.

2) Always enter product prices without tax, then the VAT rules can just be made conditional based on the customer address.

3) Use commerce_vat (and commerce_eu_vat).

The first one is probably your easiest way out at this point.


Add css class to the container of the action button from a Form I have a contact form in a Block, using the contact_block module, now I want to add some bootstrap classes to the div container of the actions buttons (send message).

At the end of the form it I got this wrapper:

<button class="btn btn-primary btn-xl text-uppercase button button--primary js-form-submit form-submit btn-primary btn" data-drupal-selector="edit-submit" type="submit" id="edit-submit" name="op" value="Send message">Send message</button>

I want to affect the div id="edit-actions".

According to twig debug, I should do a hook of the container, but I don't know how to specify that I want to affect that div.

Inside the themes/bootstrap/templates/system/container.html.twig is the structure of the containers, so I can add some classes there, but I don't know how to specify which container I want to affect. I had tried to change the name to container--contact_message_feedback_form.html.twig, but it doesnt work.

{%
  set classes = [
    not attributes.hasClass('toolbar-menu-administration') ? 'form-group',
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}

{{ children }}

Extra info:
Drupal 8.4

Subtheme bootstrap

I have already a hook_form_alter() to remove the preview button.

function twig_block_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, 'contact_message_feedback_form') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary btn-xl text-uppercase';
    // Adding prefix and suffix to the form.
    $form['elements']['edit-actions']['#prefix'] = '
';
    $form['elements']['edit-actions']['#suffix'] = '
';

  }
}

Thanks to kint for devel options:

There you go:

/**
 * Implements hook_form_alter().
 */
function twig_block_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, 'contact_message_feedback_form') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary btn-xl text-uppercase';
    // kint($form['actions']['submit']);
    $form['actions']['submit']['#prefix'] = '
';
    $form['actions']['submit']['#suffix'] = '
';
  }
}


theme function not available, not called? I am extending a module, I want to create a new theme function for the output but it somehow is not recognized. I know of theme registry and rebuild it (manually and via devel module)

The issue is tracked down to

function cmis_browser_content_properties() {
    $output = theme('cmis_browser_content_properties', array('cmis_object' => $object));
    debug($output, 'output');
    return $output;
}

function theme_cmis_browser_content_properties($variables) {
  // do sth
  $output = 'sth';
  return $output;
}

When I create a new function by copying the existing to

function theme_cmis_browser_content_propertiesnewtest($variables)

and call it in above module code. There is no output anymore, debug says: ''

$output = theme('cmis_browser_content_propertiesnewtest', array('cmis_object' => $object));

Please enlighten me!

just fyi the cmis module is a connector to alfresco document repository via CMIS http://drupal.org/project/cmis

just seeing similar questions suggested. Will see if one fits, but send this anyaway.

From the looks of it you've forgotten to register your theme function with the system using hook_theme()

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'cmis_browser_content_propertiesnewtest' => array(
      'variables' => array('cmis_object' => NULL)
    )
  );
}

After you clear the caches your theme function should be registered with the system and start working as expected.


Creating Views based on html source Is it possible to create a view from third-party source that includes html, js and css?

Example: http://www.addyosmani.com/resources/shinetime/

I want to create a view of the example shown in the link and display it as a block on my site.
Is there an automated process for doing this or I would have to do it manually? If manually then how? Thank you

If all you want to do is display that in/on your website, include it in an iframe, eg, create a block that just has:

<iframe src="http://www.addyosmani.com/resources/shinetime/"></iframe>

in it.

Now, if you are wanting to create a View, eg http://drupal.org/project/views, then you need to give some more specifics of what you are wanting to do.


No 'pagination' on Article comments Ok, I'm on D7 and using the default Bartik theme. I set comments for content type Article to be 10 per page, threaded. I published a test Article and started commenting to test the paging, and when I surpass the set limit of 10 per page, the article only displays the first 10 comments and I don't see a "more" or a "next page" or anything linking to the second page of comments.

I did not touch any PHP or CSS.

This was cross-posted to the Drupal Sub-reddit.  Just posting here for any future googlers:

If you have more than one pager on a page (think a views block of recent content) you have to give it a unique Pager ID which you can do in the advanced settings for the pager in views.


How to catch twig errors and display custom 500 error page? I have a patch to add some custom handling of 500 errors that run through the code in errors.inc, so that it returns a themed page in those cases.

This works well in certain conditions, but I have an error that occurred with a misnamed twig template, so I got

Twig_Error_Loader: Template "@mytheme/search-result/search-result--event.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "@mytheme/search-result/search-result--event.twig" in the Drupal theme registry.) in "themes/custom/mytheme/templates/node/node--admissions-event--search-result.html.twig" at line 1. in Twig_Loader_Chain->getCacheKey() (line 129 of /var/www/mytheme-qa/site/vendor/twig/twig/lib/Twig/Loader/Chain.php).

After some digging I see that this error is generated here:
/core/lib/Drupal/Core/Template/Loader/ThemeRegistryLoader.php

if ($throw) {
  throw new \Twig_Error_Loader(sprintf('Unable to find template "%s" in the Drupal theme registry.', $name));
}

The problem is this type of error isn't handled by Drupal.  It's a Twig engine error.  So an exception subscriber doesn't catch this.

Any suggestions on how to return a themed 500 page in fatal error cases like this at the theme layer?

Just checked, there is no special handling of Twig exceptions in core, so they end up in FinalExceptionSubscriber. You can add a custom exception subscriber catching Twig_Error_Loader or Twig_Error_Syntax and return a themed response (though you might need to theme this yourself when the theme layer is broken because of the Twig error).

error.inc has nothing to do with this as long as there is no fatal error not catchable by Symfony (but this would be a failure of the Twig layer, which normally protects you from low level errors)


In Views how to configure a contextual filter to exclude the node being viewed? I have the following setup: a content type (event) can have a "mother" event, which is configured as entity reference (Basically it's the same event on another date).

I have a view for a single event which is embedded in a panel pane and another view for the other similar events (with the same "mother") in another panel pane on that page.

This works pretty good, except when i try to filter out the event that is shown on the first pane from the second pane, so that this one isn't shown twice.

The view for the "related events" has a contextual filter of the nid and relationship to the "motherevent" which is set to "required".

Now you would say, check the exclude field for the contextual-filter. Yes, this works, but with a side effect: all other events not related to the "mother" are shown as well.

I feel like I have arbitrary tried all possible combinations of "set relationship" / required and so on, but with no effort. I even tried a second contextual filter of the nid with different settings... I don't get it.

Can someone please explain how this could be achieved? Thanks a lot!

The problem I believe is the relationship. I assume the entity reference on each event points to the parent event, including that on the parent (recursive).

Get rid of the relationship. Set up two contextual filters, one on Content:Nid and the other on Content:field_parent.

On the configuration for the contextual filter on NID, set the default value to Content ID from URL, open up the 'More' settings, and select 'Exclude'.

For the contextual filter on field_parent, set the default value to PHP Code and use something like the following:

$node = menu_get_object();
return $node->field_parent['und'][0]['target_id'];

This will get the ID of the parent from the current node, and will require all nodes displayed to have the same parent. The exclusion of the current node from the list will work, and you will have a list of all other children related to the same parent.


Custom entities created time is always the same I have a custom content entity type. When I create an instance, the first one got the right created time stamp. But starting with the second one, they all have the same created time stamp: as the first one have!

Why is this happening?

Base field definition:

$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'))
  ->setReadOnly(TRUE)
  ->setDisplayConfigurable('view', TRUE);

Setter / getter methods:

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

I had my php code cached before adding the setCreatedTimemethod to my custom entity. After clearing the cache everything was fine!

So in general: add the setCreatedTime method to your custom entity to make your created timestamp work.


Error when trying to load taxonomy term name from tid I am trying to replace a view name with the name of a taxonomy term that is determined from a url argument.

When I explicitly set $tid, the following works flawlessly:

function hook_views_pre_render(ViewExecutable $view) {
  $tid = 2;
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  $name = $term->label();
  $view->setTitle($name);
}

However, if $tid is determined from my argument, as in:

function hook_views_pre_render(ViewExecutable $view) {
  $tid = $view->args[0];
  // or alternatively $tid = intval($view->args[0]);
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  $name = $term->label();
  $view->setTitle($name);
}

...then I get the following error:

The website encountered an unexpected error. Please try again later.
Error: Call to a member function label() on null in hook_views_pre_render()

...on the line containing $name = $term->label().

I am at a loss as to why this is happening. When I inspect kint($term) in either situation, all of the data for the loaded term appears to be available. I've also verified that:

if   $tid1 = 2;
and  $tid2 = intval($view->args[0]);
then $tid1 === $tid2

Because there is the case when no argument is passed and $tid is null. So better keep a check you have data in variable $tid and further perform the task. Even the view name condition is not mentioned so it may apply to all views.

  function hook_views_pre_render(ViewExecutable $view) {
      $tid = $view->args[0];
      // or alternatively $tid = intval($view->args[0]);
    if(isset($tid) && !empty($tid)){
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->label();
      $view->setTitle($name);
    }
    }


Content hidden when author is anonymous I have encountered a problem in my site. When the author of the node is anonymous, his/her content doesn't appear on the front page for anonymous users. but it does when the author is the admin.

Has anyone ever met the same issue and/or has a solution?

please check the permission in "admin/people/permissions" under the node section check View published content has been enabled for anonymous user


Javascript will not load for anonymous users I have a controller with a route that has some javascript attached to it as a library.  When logged in as any user (admin or standard) the JS loads just fine.  When anonymous, the library file is loaded, but Drupal JS is not.
How the library is defined:
my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery

In the console the error says:

ReferenceError: Drupal is not defined
< anonymous >                      http://example.com/themes/custom/my_theme/js/my_javascript.js:7:3
< anonymous >                      http://example.com/themes/custom/my_theme/js/my_javascript.js:6:2

The lines in the JS the error is referring to are:
(function ($) {
  Drupal.behaviors.myScripts = {

This is the case for all browsers.  JS works fine when logged in as any user, but when anonymous, Drupal's JS does not load.

The code in the question appears to be similar to what was done in Drupal 7. In Drupal 8, the dependencies for your javascript need to be explicitly defined and it is a good idea to pass them through the closure as well. You can read more about the Javascript API in Drupal 8 on the new documentation pages.

my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal

(function ($, Drupal) {
  Drupal.behaviors.myScripts = {};
)(jQuery, Drupal);


How can I refresh a view block as soon as new content is added? I want to refresh a views block whenever new content is added.
I am using views auto refresh module

  Quick HOWTO: Using a ping script

  Using a ping script is essential for production environments, to avoid
  a full Drupal bootstrap at each refresh.

  Create a new page view Copy the file ping.php.example to your Drupal
  root folder and rename it as ping.php Edit ping.php such that
  DRUPAL_ROOT points to your Drupal root, and adjust the query: $result
  = $db->query("SELECT count(nid) FROM node WHERE created > $timestamp");

  to reflect your view's generated SQL query. Make sure to keep the
  created condition in the query. Add a new header of type Global:
  Autorefresh with: Set the interval time to 5000ms Check Use a ping url
  In Path to the ping script, enter ping.php Save the view and open its
  page In a second browser tab, add a new content that fits the view's
  criteria See the new content in the view!

Is there any other way we can refresh a views when content is created

You can achieve that using the Views node.js module

  This module implements dynamical update of views by nodejs after executing rules action.
  This module implements rules action which we can add to any rule for updating some views (views which need update, one can select in action).

  During updating of views all arguments that are already passed to view will be taken into account.

  It is also correctly working with views which use ajax.
  Introducing video.


Linking one view to another Here is my scenario - I have populated my content in a panel which consists of 3 views. Each view has a set of documents.
At the bottom of the page (panel page), I want to add a link which when clicked will take me to another view page populated with all documents from the caller node.  I'm very new to drupal and not able to figure out how to do it.

Please put in your suggestions on how I can do this.
Thank you

What controls the documents shown in the initial caller views? Is it a list of IDs, certain Taxonomy, some custom field, etc?

This is important as it will control how the view page lists the documents you want from the caller view.

If the initial view was displaying documents based on any option that was not ID, then you could easily create a link in the footer and include a parameter. The link should go to the URL of the View Page and include the arguments needed to filter the results shown on the page. It would look something like this:

http://www.example.com/documents/all?argumentname_here=[thiswouldbeatoken]

The token would be the value of the category, taxonomy, etc. that you used in the initial view.

The view page would need to be setup to not use AJAX, so it can use the URL arguments, and should have an exposed filter matching the filter of the caller view (you could then hide this with CSS so it can't be changed later, but let's leave it alone for now).

If you need help figuring out what the URL should look like, try filtering the View Page and clicking Apply and looking at the structure in the URL then mimic this in your initial caller view.

Hope this helps!


Exposed filter with "inverted" checkbox: Checked = view all, Unchecked = filtered I have a view that shows commerce products, with an exposed filter to show only items with stock >= 0. So, if the checkbox is checked, it will hide out-of-stock items.

I would like to reverse this so that if the checkbox is checked, all items are shown, and if it is not checked, only the filtered items (stock >= 0) are shown.

The label could then be changed to "Reveal items that are currently not available".

Any idea how to do this?
I could probably do this with some hook_form_alter() and stuff, but I am more interested in something to configure with the Views UI.

(Not that I shy away from custom modules in general, but I like to avoid stuff that is hardcoded to one specific view name and display id and field name..)

I have not tested this but you might be able to do it by using 2 filters. Add a non exposed filter that filters by stock > 0. Make sure it is below your current filter. Views filters in order from top to bottom. So if the page loads and that check mark is un-checked you will only see products with a stock greater than 0. If they then check the box it will re-load and filter by your stock >= 0. That might work. As I said I have not tested this.


How do I display the "recently created node" block using Views? I am trying to show the recently added content data in a block, using the Views module, but I can't see any record even if I recently added some nodes.

You need to check the views output settings. Notice there is a preview option. You wrongly select either fields either the filter doesn't match. You need to filter by Content Date Field and order it desc.


Is it possible to get the field value of user reference autocomplete from username? I am able to find the username. From the username I need to fill the user reference field.

Is there a way to get the user reference field value from username?

Example:

I have username: abc
I need Reference field value: Abc(201)

user_load_by_name('admin')

stdClass Object
(
    [uid] => 1
    [name] => admin
    [pass] => $S$DYk/jJiQjg07cciSAeU2EeP3XVMm/WhWHG19rA1iQf/FIqdOmY5p
    [mail] => test@gmail.com
    [theme] =>
    [signature] =>
    [signature_format] =>
    [created] => 1469189190
    [access] => 1511853833
    [login] => 1511853621
    [status] => 1
    [timezone] => Asia/Kolkata
    [language] =>
    [picture] =>
    [init] => test@gmail.com
    [data] =>
    [uuid] => 77ef7473-31cd-432e-ace6-26f1b075abb5
    [roles] => Array
        (
            [2] => authenticated user
            [3] => administrator
        )

    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => sioc:UserAccount
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => foaf:name
                        )

                )

            [homepage] => Array
                (
                    [predicates] => Array
                        (
                            [0] => foaf:page
                        )

                    [type] => rel
                )

        )

)

You can do this with user_load_by_name($name).

Once you load the user object you should be able to access the reference field normally.


How do I call pathauto alias using php I have pathauto installed on my D7 setup along with all my taxonomy terms configured.

How do I then call the alias using PHP for custom code?

EDIT: just to clear things up - I want to output the alias URL that has been created and assigned to each specific node. For example:

Terms
- Country
- City

For node #1 an alias is created as {site}/[country]/[city]

I would like to output the alias that has been created for the node so I can visit for example {site]/england/london instead of {site}/node/1

If you mean the alias for the taxonomy term you can use url() (if you just want the URL), or l() if you want a link:

$url = url('taxonomy/term/' . $term->tid);

$link = l('Link text', 'taxonomy/term/' . $term->tid);

Both of those will give you the current path alias for the term page


Entity reference vs. taxonomy Let's say I have a team, which has members. I have a content type for team and a content type for individual team members. Let's say there are also other relationships, for instance teams can belong to departments, and there are projects that can be assigned to individuals or teams.

As I understand it there are two ways I can define the relationships between these entities - either Entity references, or using Taxonomy terms. When I should use one type over the other? Is it best to choose just one method, or mix them?

It seems to me that Taxonomy is the most flexible, because it is easy to build trees using taxonomy types, or for instance if within a team I then decided I wanted to build a hierarchy in the team the functionality is already there (just drag the taxonomy terms into the hierarchy) whereas if I've used Entity reference I can't think of a simple way to do that (other than adding taxonomy, which then results in redundancy).

It feels as if there is something I'm not understanding here, but I'm not sure what it is!

Any help would be appreciated.

You are talking about two different concepts here. The first question is related to whenever one wants to organize content into different categories or if one wants to build a relationship between existing content types. The other question is, if, when using a taxonomy, will it be better to use a taxonomy reference field or an entity reference field.

Regarding the first concept

It depends on your use case. Taxonomies are great for building hierarchies, as you mentioned, but ideally, you shouldn’t use taxonomies to contain actual content. The reason for that is easy — while you can add fields to taxonomy terms, all hierarchical levels in a taxonomy use the same fields. Taking your example with members belonging to different teams, this might lead to problems. If you want to store more information about a team or member than just the name, If, for example, you want to store information about a member’s first name, last name, and biography, and add this fields to the taxonomy, they would be available on team terms as well. And if you add a team description field for the teams, those will show up for team members.

Taxonomies are best used when organizing similar items hierarchically. Like tags, for example:

vegetable

carrot
potato

fruit

apple
banana

Entity references are excellent for establishing relationships between content types. Examples include when you have a node type ‘team’ and a node type’ team member,’ each with their own fields. Or a node type ‘song’ which is referencing an ‘album’ which itself references a ‘musician.’ In this regard, entity references are more flexible than taxonomies, as it allows for more complex relationships. When you use views, you can also utilize these relationships. Taking your example, you could create a view of all team members, and using the entity reference for a relationship, and one could display any field on the team content type along with fields from the member node.

Mixing node referenced and taxonomy fields are legit too. In your example with the teams, both team and member could be a node, referencing each other with an entity reference. At the same time, the department could be a taxonomy with all available departments.

Regarding the second concept

When D.O. released D7, it shipped with a taxonomy reference field to use when referencing taxonomies. Since then, we’ve seen the release of the Entity API module and, consequently, the entity reference module, and since terms and taxonomies are entities, one can reference them like any other entity. At this point, the two are working very similarly, and in many cases, it doesn’t matter which one you use. However, there are still some contributed modules providing field formatters and widgets, which only work for one or the other. So, it mostly depends if you need such a formatter if you should use taxonomy reference or entity reference.

As D.O is replacing the taxonomy reference field with the entity reference field in D8, I prefer to go with the entity reference field to link to taxonomies rather than the field supplied by the taxonomy module.


New Relic shows the token hook being called a lot I've just installed NewRelic on a Drupal 7 website, and I'm now going through the most obvious issues that jump out at me.

Looking at the Drupal specific menu items, I notice the "Token" module accounts for about 1 min active time in 30 minutes clock time.

The list of hooks shows the "tokens" hook accounting for 203 seconds, which is about 80% of the total time. Each call takes less than 0.02ms, but the hook gets called over 18 million times in 30 minutes clock time. The closest one is node_view with 500 thousand calls. That seems more reasonable.

I can't, right off the bat, find a way to dig into the call tree for the Drupal hooks.

My questions:

Does the amount of calls to the tokens hook seem normal?
Is there a way in New Relic to find out where most hook invokes originate?

I wrote a tiny module to log all calls to the tokens hook, so that I'd have some sort of idea where the tokens were coming from:

<?php

function token_logger_tokens($type, $tokens, array $data = array(), array $options = array()) {
  watchdog('token_logger', print_r($tokens, TRUE), array());
  // Activate to fill up your database fast!
  // watchdog('token_logger', print_r(debug_backtrace(FALSE, 20), TRUE), array());
}

Turns out this was mostly the file_entity module running image alt en title tags through tokens, so that they could be overridden with another pattern if so desired:

// file_entity.file.inc:279

$alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
$title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
// a little further down the line in a loop
$output = token_replace($alt, array('file' => $file), $replace_options);
// a little further still
$output = token_replace($title, array('file' => $file), $replace_options);

That adds up to 2 calls to the token hook per file loaded. If you have a busy website with a fair amount of images, it adds up quickly. About 800 calls each time the homepage is loaded, specifically.

I think I'll patch the file_entity module to cut out tokens for the default option, and verify it makes a difference speed-wise.


Auto node redirct depending on a cck field's content When a visitor goes node/123, I need them to be redirected to the url that is specified in that node's cck field.  I know there are plenty of modules that do redirects, but I need this specific type of automation.  What would be the best way to go abut this?

There is multiple way of doing this. Probably the best one is create a custom module and

Using hook_menu_alter(), alter the page callback for node/%node. In your page callback, check the type of the node to invoke node_page_view on the node or redirect to the referenced node.

MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    //if fixed_x is a node nid
    $reference = $node->field_x;
    drupal_goto('node/'. $referenced_node->nid);
    //if fixed_x is a path
    drupal_goto($node->field_x);
    //etc
  }
  else {
    return node_page_view($node);
  }
}


Get entities that share the Entity Reference field Let's say that I have two content types:

Article

title
body
field_ref_term

Page

title
body
field_ref_term

Those two content types are sharing the same field: "field_ref_term" wich is a "Entity reference" field type, to another entity called 'Term' (or something else, it doesn't mind).

What I'm trying to do is, when displaying a particular content of type "Page", I would like to be able to display a list of content in a block who shares the same value for the "field_ref_term" field.

It's a bit like the "Content: Has taxonomy term ID" contextual filter from Views and Taxonomies, where you set the value to "Taxonomy term ID from URL" then check "Load default filter from node page, that's good for related taxonomy blocks".

Do you think this is currently possible with Entity Reference ?

Thanks

I finally found a way to do it, here are the steps:

Add a relationship: Entity Reference: Referenced Entity, select the right field to match, select "Require this relationship"
Add a relationship: Entity Reference: Referencing Entity, selection the just add relationship in step 2 and check "Require this relationship".
Add a contextual filter: Content:nid, provide default value: Content ID from URL
Add a contextual filter: Content:nid, select the relationship "Content referencing...", provide default value: Content ID from URL, then in the More fieldset, check exclude.
Add a field "Title" and select the relationship "Content Referencing..."

I will close this question, feel free to comment or propose other solutions.

Thanks.


How do I create an exposed filter for a localized taxonomy term? How do I create an exposed filter for a localized taxonomy term? My vocabulary is set to 'Localize' and I'm able to create a translation for each term in this vocabulary. In my View, however, I can't add a localized taxonomy term to the filter. This is an exposed filter and I'd like the selection items to show up in the user's language.

How do I display localized taxonomy terms in a filter?

you need to install i18nviews module
and then use one of these:

Content: Has taxonomy term (translated)
Content: Has taxonomy terms (with depth, translated)

instead of regular filters


Theme video-embed-iframe.html.twig by content type I am using Drupal 8 and trying to theme video-embed-iframe.html.twig by content type. with the current naming suggestions this is not possible.

I am using Media with video embed field containing in a field called video

This is what I did so far. in the fields template named above in the templates folder of my theme

{% if logged_in %}

{% else %}

Eine brilliante Überschrift

 Credit author of the background image

{% endif %}

I have no clue how to access the field by content type to separate the code deepening if you have a content type eg page and article
Any Ideas?

Is there a way to populate a global var like logged in containing the mashine name of the content type without needing a custom module. I other words is there a way to populate a var like

contenttype=anycotenttypehere in the mytheme.theme file by writing a function? to be able to display the video depending on with contetnt type has been used and if the user is logged in or not

That's not easily possible, not directly.

By default a media entity is going to be render cached on its own, that means the same media could be used in two different nodes with a different type and as long as they use the same view mode, it is only going to be built once. While you can get the current node easily on the detail page in preprocess and you could vary the rendered media by path, that will possibly result in a lot of variations and won't really work on views and other pages that display teasers of many nodes.

The easist way to achieve something like this would be to define two different view modes, use one from one node type and the second from the other.


Using Menu Tabs with Views 3 (Drupal 7) So I'm confused by the Menu Tabs functionality of Views 3 (Drupal 7 site).

My menu is organized like this:

  About-Us => /about-us
  --Management => /about-us/management
  ----Top-Management => /about-us/management/top-management
  ----Board-of-Directors => /about-us/management/board-of-directors

I have a View setup with two page displays and their paths are:
about-us/management/top-managers
about-us/management/board-of-directors

I configured the 'top-managers' page display to be a "Default Menu Tab"
I configured the 'board-of-directors' page to be a "Menu Tab"

For the Default Menu Tab, I had to provide a Parent Menu Item, so I selected "Normal menu item". I also tried "Already Exists" but that seemed worse.

So.. When I go to about-us/management/top-managers I get the correct page display, and there are tabs at top. When make the 2nd tab active ("Board of Directors"), the path changes correctly and I get the correct page display. But the 1st tab ("Top Management") links to the parent's path (about-us/management) instead of to itself (about-us/management/top-management).

So the 1st tab links to about-us/management and the 2nd tab links to about-us/management/board-of-directors.
I want the 1st tab to link to about-us/management/top-managers

How do I get the default menu tab to link to its own path instead of the parent's path? Or am I doing something completely wrong?

Check this:

How to add a tab to a Views page:
On the View that you want as the default tab: In the Views ‘page settings’, set the Menu Type as ‘Default Menu Tab’ then click the little setting ‘gear’ and set the ‘parent menu item’ to ‘normal menu item’.  Set the path as “/something/tab1″; for example, “/postlist/allposts”
On the View that you want as your second (or 3rd, etc) tab, set the Menu Item Type as ‘Menu tab’.  Set the path as “/something/tab2″ for example, “/postlist/newposts”
The key to making the tabs show on the View page is the path setting!  All of the pages must have the same parent-path – in the examples above this is “/postlist”.  If the parent-paths are not the same, you will never get that damn tab to show up in the View.

For more check the original post


Why would taxonomy_term_save be slow when called from hook_install_tasks? As part of making a site more easily deployable from scratch, I have generated two PHP scripts to pre-populate taxonomy vocabularies with a list of terms.  The scripts are straightforward, creating stdClass objects with the appropriate fields and callingtaxonomy_term_save on each one.  Example:

$term = (object) array (
  'name' => 'Art & Architecture',
  'description' => '',
  'format' => 'plain_text',
  'weight' => '0',
  'vocabulary_machine_name' => 'categories',
  'field_cc_numeric_code' =>
  array (
    'und' =>
    array (
      0 =>
      array (
        'value' => '102',
      ),
    ),
  ),
);
$term->vid = $vocabulary->vid;
taxonomy_term_save($term);

The variable $vocabulary already contains the appropriate taxonomy vocabulary structure at the time this is called.  One vocabulary has about 150 terms to create, the other about 2,000.

On a fresh installation of the site made using drush site-install, these scripts run almost instantly when called via drush php-script.  However, if they are incorporated into the installation profile and called by a task in the implementation of hook_install_tasks, they are much slower.  In the latter case, saving each term takes about a second, which is unacceptably slow.

There is discussion of a similar issue at https://www.drupal.org/node/1887924, but no solution offered either there or in the linked bug report.

Why would taxonomy_term_save be so much slower when performed from an installation task?  Is there anything that can be done about it?

In this case, the problem resulted from having the Pathauto module enabled during installation.  When a new taxonomy term is saved, Drupal calls pathauto_taxonomy_term_insert(), which calls pathauto_taxonomy_term_update_alias(), which in turn calls pathauto_create_alias().  This last function calls an internal function, _pathauto_path_is_callback(), to determine whether an alias can be created for a given path, and this in turn calls the core function menu_get_item(), which contains the following lines:

if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  menu_rebuild();
}

menu_rebuild contains the following lines:

if (defined('MAINTENANCE_MODE')) {
  variable_set('menu_rebuild_needed', TRUE);
}
else {
  variable_del('menu_rebuild_needed');
}

The cumulative effect seems to be that the menu_rebuild_needed variable is continually reset to TRUE, meaning that a complete menu rebuild is triggered each time a new taxonomy term is saved, slowing things down immensely (from ~100 terms saved per second to ~1 per second).

This seems like a bug, though it's not clear which component, if any, is at fault.  For now, I am working around the problem by disabling pathauto, creating the terms, and then re-enabling pathauto:

module_disable(array('pathauto'));
…
module_enable(array('pathauto'));


Clone product display with referenced product I am using Commerce Kickstart for Drupal 7, and I need to be able to clone products.

In Commerce Kickstart you have all the products just as "reference" of node, product display. I mean, the products themselves are displayed for customers similar like any other page, with "attached" actual products. (this allows you to create more variations of one type)

I am trying to clone both of those by one operation - to clone Product display (as node), and also referenced product by this product display. But when I used basic Node Clone module, it just clones Product display as a node but not the reference. Result is, the same cloned content with "attached" reference product at the very bottom, but when I change that product, It also changes the product of previously cloned product display.

Here is what I mean: http://harmonel.sk/stuff/drupal_commerce.jpg

I am not sure what to do, I am not very good with coding, maybe I should somehow re-write the Node Clone module to also clone the referenced product? Does anyone had similar or same problem? I am trying to achieve this with Rules but with no success, but maybe that would be the best way to achieve this?

Any advice would be greatly appreciated.

Try  https://www.drupal.org/project/replicate  and https://www.drupal.org/project/replicate_commerce

The Node Clone module focus on cloning using the administration interface and is designed only for nodes replication, whereas Replicate can clone any entities (nodes, taxonomy terms, users, ...).


Creating field with multiple properties I am creating a Field plugin, where I have requirement as below

Field name : Question

Properties:

Question Text : String

Question Type : integer (0,1,2)

Question Options : Array of Strings

I defined schema like this. I am not sure if I am doing it right for Question Option

public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
        'columns' => [
            'question_text' => [
                'type' => 'varchar',
            ],
            'option_type' => [
                'description' => 'Option Type: 0 = radio, 1 = checkbox',
                'type' => 'int',
                'default' => 0,
            ],
            'question_option' => [
                'type' => 'varchar',
                'serialize' => TRUE,
            ],
        ],
    ];

    return $schema;
}

And for property definition I have following

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {

    $properties['question_text'] = DataDefinition::create('string');
    $properties['option_type'] = DataDefinition::create('integer');

    $properties['question_option'] = DataDefinition::create('string');

    return $properties;
}

Please let me know how can I do it for the question_option.

--

Thanks

If you want an array of strings maybe your should use a blob in you schema:

 'question_option' => [
          'type' => 'blob',
          'size' => 'big',
          'not null' => TRUE,
          'serialize' => TRUE
        ],

Note that by default 'size' = 'normal' which max storage value is 16KB so if it is enough for you use 'big'; 'big' can handle up to 4GB.
And for properties as follow:

$properties['question_options'] = MapDataDefinition::create()->setLabel(t('Options'))


drupal_add_js not working I have this code in my javascript:

(function ($) {
    Drupal.behaviors.myid_print_table_id_link = {
        attach: function (context, settings) {
            $.ajax({
              type: 'POST',
              url: '?q=myid_print/table_pager',
              success: function(data) {
                console.log(data);
              }
            }).done(function(o) {
              console.log(o);
            });
        }
    }
})(jQuery);

This calls a function called myid_print_table_pager declared in my hook menu:

 function myid_print_menu(){

     $items = array();
     $items['myid_print/table_pager'] = array(
         'title' => 'Table Pager',
         'page callback' => 'myid_print_table_pager',
         'type' => MENU_CALLBACK,
     );
     return $items;
  }
 }

Below is my function:

function myid_print_table_pager(){
    drupal_add_js('$(document).ready(function () { alert("Hello!"); });', 'inline');
    watchdog('message', 'I've been here!');
}

I'm pretty sure that the function myid_print_table_pager is invoke because 'I've been here!' is seen in my watchdog table in my database. But why does the alert with the message Hello! has not been invoke?

I usually avoid calling drupal_add_js() and use the #attached property of the render array. The advantage of using #attached is that you don't need to implement additional hooks, the js is only added when needed, and (as I've been told) it works better with caching. Your code would look something like this:

function myid_print_menu() {
  $items = array();
  $items['myid_print/table_pager'] = array(
    'title' => 'Table Pager',
    'page callback' => 'myid_print_table_pager',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function myid_print_table_pager() {
  $build = array(
    '#markup' => 'Hello world!',
    '#attached' => array(
      'js' => array(
        array(
          'data' => '$(document).ready(function () { alert("Hello!"); });',
          'type' => 'inline',
        ),
      ),
    ),
  );
  return $build;
}

Disclaimer: untested code, please let me know if it doesn't work as expected.


Ajax form submission error when using use-ajax-submit I receive the following message when I attempt to submit a form with use-ajax-submit class attached to the submit button:

  An error occurred while attempting to process /my_form?_wrapper_format=drupal_ajax: ajax.$form.ajaxSubmit is not a function

Similar to this question, but for Drupal 8.

The following dependencies need to be added to the library attached to the form in order to use use-ajax-submit.

my_module.libraries.yml

my_module.my_library:
  dependencies:
    - core/drupal.ajax
    - core/jquery.form

The library needs to be attached to the form:

$form['#attached']['library'][] = 'my_module/my_module.my_library';


How can I limit the days returned in the date module to today's and future dates only? I have the Date module installed on Drupal 7 (version 7.x-2.5) and I am attempting to disable the selection of past dates within the date popup.

$form['ratesDateSelect'] = array(
    '#title' => 'Arrival Date',
    '#type' => 'date_popup',
    '#default_value' => '',
    '#size' => 21,
    '#maxlength' => 100,
    '#date_flexible' => 0,
    '#date_year_range' => (date('Y')) . ':+5',
    '#attributes' => array('autocomplete' =>'off','readonly' => 'readonly'),
    '#description' => '',
    '#value' => array('date' => $date),
    '#date_format' => 'D d M Y',
    '#required' => FALSE,
);

I have limited the popup to return this year and five years into the future, but I also need to restrict it so that people cannot select past days.

I have managed to do this in another project using pure javascript, using the datepicker param: minDate: 0

I worked this out shortly after posting, but it required a little bit of "hacking" of the date module.

To get this working I added a new '#settings' variable onto the date_popup type so it would look like ..

$form['ratesDateSelect'] = array(
'#title' => 'Arrival Date',
'#type' => 'date_popup',
'#default_value' => '',
'#size' => 21,
'#maxlength' => 100,
'#date_flexible' => 0,
'#date_year_range' => (date('Y')) . ':+5',
'#attributes' => array('autocomplete' =>'off','readonly' => 'readonly'),
'#description' => '',
'#value' => array('date' => $date),
'#date_format' => 'D d M Y',
'#required' => FALSE,
'#settings' => array('minDate'=>'0'),
);

on the form element and then I added this code into date_popup.module (around line 336) after the settings array.

$user_settings = $element['#settings'];
foreach($user_settings as $setting_key => $setting_val) {
    $settings[$setting_key] = $setting_val;
}

This allowed me to inject javascript settings/options so that I can restrict the dates returned from now into the future.

Ryan


How can I scrape data from the web into drupal? I want to scrap location data from google. So for example; If I search for "Restaurants in Miami". I get over 14K results. I reviewed; How to import Nodes and Node Location data using Feeds module?. But that doesn't really help me with importing a query term from google.

How would I be able to scrap each one of the locations that the
query gives as a result and import them as a node into drupal?
Are there any pre-built modules that might assist in this process?
I'm I going to need to build a custom module for this use case?

UPDATE: I've found this page; http://drupal.org/project/example_web_scraper and will studying the info to see if this is what I'm looking for.

AH HA MOMENT:

http://drupal.org/project/geolocation
http://drupal.org/project/location_feeds
http://drupal.org/project/geolocation_proximity

Not to put a damper on things (I've written more scrapers than I care to remember and it's always fun), but such an act is specifically against Google's Terms of Service:

  Do not misuse our Services, for example, do not interfere with our Services or try to access them using a method other than the interface and the instructions that we provide.

I'm sure you'll be ok if you're doing this for fun/educational purposes (don't take my word for it though, I'm not a lawyer!), but if you make something commercial out of this you could find yourself in a tricky position.


How can I access individual form elements for theming? I have overridden the default user login form in Drupal 8 using a different template in my sub theme, but it isn't of much use because when I access it in twig template, all I can do is

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

Doing this I get the elements in same order, and there is not lot of modification option. I can put them in container but that is it. I was wondering there was instead a way to call elements like username field, password field individually instead of doing a bulk call using {{children}}.

That's a case for the new Formdazzle! module.

  Drupal form theming with less pain

  Theming drupal forms can be difficult and time-consuming. This module
  provides a set of utilities that make form theming easier.

  Currently, this module provides theme suggestions for forms that are
  much more useful than those provided by Drupal core.

  Theme suggestions for all form elements (including buttons)
  Theme suggestions for all form element labels
  All theme suggestions include the form ID and the form element name; e.g. [element-type]--[form-id]--[form-element-name].html.twig

  While Drupal core only provided these two theme suggestions:

input.html.twig
input--textfield.html.twig

  Formdazzle adds the following two theme suggestions to the list:

input--textfield--webform-contact-form.html.twig
input--textfield--webform-contact-form--first-name.html.twig


Where do I find the settings for adding a vocabulary to a content type in Drupal 7? In Drupal 7, I can't find the Content types and Required setting under edit vocabulary.

How do I customise it?

Drupal6

Drupal7

Head over to the Manage fields tab of your content type. For example, for "article" that would be admin/structure/types/manage/article/fields. Then add a Term Reference field.

This question is about Drupal 7, but be aware that Term Reference appears to be deprecated and potentially be removed from Drupal 8 (in favor of the entity reference field). For more details on that, refer to the question about "Are there any benefits/caveats with using Entity Reference over Term Reference?", in which there is a comment also like "Term reference isn't going anywhere and there will be an upgrade path from 7 to 8".


How to add "Content type B" from within "Content type A" and then display both together? I have the following scenario:

Content type A
Content type B

Content type A is added by the admin role.
Content type B is added by the students role.

Once Content type A is created, then on that link, like node/20 or content-type-A/20, I am looking to have an node add form for Content type B.

then the content type B that was added from this form, should be related and displayed with the existing content from content type A.

For example,
Content type A: title: Bread is good

So now, when you go to node/20 you see Title: Bread is good
then here you should have a form for Content type B with fields say title and some radio buttons.  The student role user inputs the form and then submits.

Now the node/20 should display Title: bread is good and the fields associated with content type B that the student inputted.

And more students should be able to continue adding to this.  This is something like a one-to-many relationship.  Content type A has many Content type B associated with it.

I hope someone can help explain to me how to get this done

For the first part of your problem you can use Entity reference to create the relation between the content types:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

For the second part, one content type form inside another content type form you have this modules:

The Inline Entity Form module:

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

Entityreference Autocreate

  A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

  Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

  Node Reference Create is an enhancement to the nodereference
  autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

  It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.

  The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

Important: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.

For the third part, the visualization of one entity (or more entities) inside another entity I think that you can use the EVA: Entity Views Attachment module, is very easy to use.

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

I think that you should see this: Drupal 7 Node Reference Tutorial


Pass taxonomy terms from node to block just wanted to scope peoples thoughts on the best way to do this: I have a node which surfaces taxonomy terms. I need to pass them to a custom block (templated with block.tpl.php).

The terms can be see within the node using devel, but i'm unclear as to how best pass them into the custom block.

any thoughts would be greatly appreciated

/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */

function MYTHEME_preprocess_block(&$variables) {

  if ($variables['block_id'] == 'target_block_id') {

    //load node object
    $node = menu_get_object();

    // do something with node object

    // add variable to your block template file
    $variables['block_variable'] = 'something';
  }
}

Available block variables - Block variables


How do I set up a Drupal view with two relationships? I have "Event," "Session," and "Download" content types. Events can have many sessions, and each session can have many downloads. I have used node references to link the downloads to the sessions, and sessions to the events. Can I create a view of the downloads which will show session information and also the event information? I know I can use a relationship to link two node types in a view, but can I do it for three node types?

I'm using Drupal 7, and Views 3.

I found my answer at Multiple Node Relationships?

The answer is to go to the Relationships section and add two relationships, each for your node references. You'll find them under the 'Content' group. When adding the second relationship, select it to use the first relationship so that they chain. That will get you "base" node being the lowest level child, the first relationship is that node's parent, and the second relationship is the grandparent.
Then, add the Node: title field 3 times. Set 1 to use no relationship, 1 to use the first relationship, and 1 to use the second. Preview your view. That should get you the basis for what you want. Add sorts, filters and other fields to taste.


"init "and "mail" fields in the users table What is the difference between the "init" and "email" fields?

mail varchar(64)  User's e-mail address.
init varchar(64)  E-mail address used for initial account creation.

The difference is that mail is the actual email address used by the user, while init contains, in a plain Drupal installation, the email address used when the user account was created.
In the case the Bakery Single Sign-On System module is installed in a slave site (in Bakery parlance), the init field contains the link to the user account on the master site.

So, the init field could be described as the field that unequivocally identifies a user account, and that is (by default, when third-party modules don't change its content) set to contain the initial e-mail address. (That seems the reason why the field has been named init.)

Drupal.org uses the init field in the case users lose the access to their account, and create a new account to report that. They are asked (not publicly) which email they used when registering their previous account; a Drupal.org administrator would then verify that is exactly the email they used while registering the lost account by reading the database content. (There isn't a module that allows to do so automatically, for what I know.)


how to theme the read more link using fields mode in views, In views i have created a block view in where i want to list only the titles of 5 nodes,
using the 'field' setting in views.
Under 'pager' i have set the amount of items accordingly.
I have enabled 'the read more' link in case more nodes show up.

My problem is that when my read more link shows up it is way out of line with the listing.(right side)

With my chrome element inspector i set the aligning of the read more link to left which is acceptable.

How can i accomplish this with in my drupal set up.

Help appreciated.

You should be making any theme changes in a sub theme, rather than editing the actual theme files. This is so all of your changes are not wiped out when an update is available for corporate clean.

Please read https://www.drupal.org/node/225125 for more information on sub theming.

As for the changes to be made to your stylesheet, open your style.css in an editor such as notepad++ and add the following lines (if align left is what you need)

.more-link {
  text-align:left;
}


Template reused on repeated node I have a node repeated on the page, once for styled dropdown menu through submenuesmall view and once as node when that submenu is selected. Submenu is styled with node--view--submenuesmall.tpl.php that is OK. But same template is used for node later instead of normal node.tpl.php

If I omit that node from submenuesmall normal node.tpl.php is used.

Is that standard behaviour and how can I fix it or did I do something wrong. All modules are up to date.

Solution acording to @Vaibhav tip...

// node__view__submenuessmall is used in view
// for creating block menues with images
// when same node is used in menue and on page
// wrong theme_hook_suggestion is used on page

function cuter_preprocess_node(&$variables){
 if(array_key_exists('theme_hook_suggestions',$variables))
  {
    $lastVar = count($variables['theme_hook_suggestions'])-1;
    if($variables['theme_hook_suggestions'][$lastVar]=='node__view__submenussmall')
    {
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
      $variables['theme_hook_suggestions'][$lastVar]='foobar';
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
    }
  }
}


How to solve limitations of 32-bit PHP in drupal 8 I am unable to complete the setup of Drupal 8. When I get to the third step then the error below will be displayed stating:

  "You are running on a system where PHP is compiled or limited to using
  32-bit integers. This will limit the range of dates and timestamps to
  the years 1901-2038. Read about the limitations of 32-bit PHP."

I am using a 32-bit windows 7 system. How can I resolve this issue?

There is a "continue anyway" link at the bottom. I've had the same problem, but for the install process this is only a warning, and will not prevent you from using Drupal 8.

Also, credit to Clive for mentioning this first.


Can't set field names with Given users behat call When I run the following behat test:

Scenario: Logs in to the site
  Given users:
  | name     | pass        | mail                  | roles         | status | field_fir | field_la |
  | someuser | sompassword | someone@xenomedia.com | administrator | 1      | Some      | User     |
  Given I am on "/user"
  When I fill in "Username" with "someuser"
    And I fill in "Password" with "sompassword"
    And I press "Log in"
  Then I should see "Some User"
  Then I visit "user/logout"
  Then I should be on the homepage

I get the following error:

Given users:                                # Drupal\DrupalExtension\Context\DrupalContext::createUsers()
  | name     | pass        | mail                  | roles         | status | field_fir | field_la |
  | someuser | sompassword | someone@xenomedia.com | administrator | 1      | Some      | User     |
  Warning: explode() expects parameter 2 to be string, array given in /var/www/xmd8/vendor/drupal/drupal-extension/src/Drupal/DrupalExtension/Context/RawDrupalContext.php line 316

The weird thing is if I remove field_fir and change Then I should see "Some User" to Then I should see "User, it works.  For some strange reason it doesn't like field_fir. I verified that field_fir and field_la have exactly the same settings.

I didn't think this was the issue but I recently upgraded to PHP 7.  I downgraded to PHP 5.6 and the issue went away.  I created an issue on Drupal.org.

Turns out that I was using an older version of drupal-extension.  Upgraded to and the issue went away:

"drupal/drupal-extension": "^3.2",


How can I use a replacement pattern in a custom field? I just created a new custom field in a view, but I would like to use replacement patterns in that field. Is it possible to do this?

class CustomButtonField extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function usesGroupBy() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Do nothing -- to override the parent query.
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['target'] = ['default' => FALSE];
    $options['class'] = ['default' => FALSE];
    $options['text'] = ['default' => FALSE];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&amp;$form, FormStateInterface $form_state) {
    $form['target'] = array(
      '#title' => $this->t('The target id of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['target'],
    );

    $form['class'] = array(
      '#title' => $this->t('The class of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['class'],
    );

    $form['text'] = array(
      '#title' => $this->t('The text of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['text'],
    );

    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    return [
      '#theme'  => 'custom_button',
      '#target' => $this->options['target'],
      '#class'  => $this->options['class'],
      '#text'   => $this->options['text']
    ];
  }
}

How can I use replacement patterns in $form['text']?

Take a look to \Drupal\views\Plugin\views\field\FieldPluginBase::renderText

/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
  $tokens = $this->getRenderTokens($this->options['text']);
  return [
    '#theme'  => 'custom_button',
    '#target' => $this->options['target'],
    '#class'  => $this->options['class'],
    '#text'   => $this->viewsTokenReplace($this->options['text'], $tokens),
  ];
}


How do I create inline border style in views table for views data export word output? I am using views data export module to generate word output. I am able to get word document but views table out is coming without border. How to put border in word output ?

I have created views template and saved in theme folder. then used styles in template itself like below:

      <th style="border:1px solid #000000; border-collapse:collapse; padding:5px; min-width:80px" <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
        <?php print $label; ?>

Useful link: http://www.wdtutorials.com/drupal-7/drupal-7-how-to-create-custom-template-view#.VWsGAlJp0-Y


How do I use views to create a block that display image and title How do I use views to create a block that display image and title.
The image is using IMCE module.

I have try create a views, select “node”, under "fields" section select "content" but can't select the imce image.

What is wrong?

Use CCK to upload image.
In Views, display the image with CCK. (Filter > Content:Image)


views display restricted number of results based on nid Is it possible to create a view which would show only 3 rows. Based on curent node (nid) show result before current row and show one row after this row.

You can do this by using the Node: Nid filter.

Add the Node: Nid filter
Select Operator > equal to > Is between and then select the nid before your node as the Min and the nid after your node as the Max.


Using the PHP include in your template: Naming the file .php or .inc? I'm able to load static PHP files for my theme without any problems but do I name the file as file.php or file.inc? I found out that either way works fine so which one is better?

<?php include ".." . base_path() . path_to_theme() . "/includes_folder/file.php"; ?>
<?php include ".." . base_path() . path_to_theme() . "/includes_folder/file.inc"; ?>

Remember that the files are saved in my theme folder since I'm not making a module. It's just static content.

The Drupal 7 coding standards (#includes) seem to use ".inc" over ".php". If you browse the Drupal Core you see ".inc" is used everywhere. I suggest you stick to ".inc".


Trouble hooking blocks with theme templates So I am making blocks and viewing the page source when they're displayed, and for instance one has the id="block-views-first-row-footer-links-block"

so I make templates called the following: none will work(yes I am clearing the cache)...I am using drupal 7.12

block--views-first-row-footer-links.tpl.php

block--first-row-footer-links.tpl.php

block--footer-links.tpl.php

what am I doing wrong here?

There is a easier way to do this using Block theme. But in case you do not want to use it, you can create block template files in the following order.

block--module--delta.tpl.php

block--module.tpl.php

block--region.tpl.php

More information can be found here.


Page not found error when using plus"+" sign in the url alias I am trying to create a new simple node with url alias as test+node. when i save the node the page is not showing the node, the url changes as

http://server/packets/test%2Bnode

but it only shows the following error

Page not found
The requested page "/packets/test%2Bnode" could not be found.

Can anyone help me to fix this issue out...

Drupal url do not accept the + sign, so it will convert the url into "space" so that only i t return page not found value.
Please remove the + sign from url.


Struggling with View Slider Image Rotation I'm struggling to let the images rotate with the View Slider module.

When I add an image of content type of say -> image_slider. At the moment it only replaces the current slider image with the latest published content of type image_slider instead of rotating between the images.

Where can I set/change this?

Thanks in advance!

Edit: I added 2 images to one node and now when I think it wants to rotate between the images I get this error in the console: Uncaught TypeError: Cannot read property 'action' of undefined

The basic setup for the slider depends on two factors:

1.) A collections of nodes of a particular type, in your case image_slider.

2.) A view that manages the slideshow outputting it as either as a page, block or both.

So, initially go to create (for example) 3 nodes, each containing an image, as the content-type image_slider.

Then go ahead and access your view under admin/structure/views and ensure that:

The format (under Format) is set to Slideshow
You are "showing" (Show:) Fields (under Format)
That you have selected your image field to be called (under Fields).
That your filter criteria has the content type set to image_slider
Finally, that under "Pager" (in the second column) you have set the pager to display "All Items" - you can change this later to limit the output but for now this will ensure that all node-fields, which meet the previously mentioned conditions, will be output.

Once all of these conditions are met, save the view and it should already display the slider in action at the bottom of the page as part of the preview. If everything went smooth, you can now access either your view-page output or set the block under blocks to display your slideshow throughout your website.


cloning a live drupal website (db) to a local / working mamp version I have a drupal multi-site project, that I've inherited. I am stuck on the process of trying to clone or import the database from a live server to the local enviroment. Does anyone have any suggestions as to how I might be able to do this?

It would have to be done via the command line, as the I don't have access to phpmyadmin from the live server. I know this can be done, with a series of commands and scripts -- I'm just not sure how...

I use this command to dump my databases which are hosted on Ubuntu:

mysqldump -uusername -p --databases db_name | gzip -f > db_name.sql.gz


How to remove results returned from Views UI I am getting results as expected using Views UI. But I don't want to display a particular record from the output of Views UI. How to achieve this and will I require any hooks for this?

For example; My Views return result as 1,2,3,4. Now I don't want to show 1 in the result. I cannot change the query using hook_views_query_alter as 1 is being used in "where" clause.

An answer to this question very much turns on what record you want to exclude from the listing. But the typical route here is to use a Contextual Filter on your view.

A typical pattern is that you are displaying a View alongside a node, e.g. a view of items that are related to that node. In this case, you want to exclude the node itself. For this you create a contextual filter that provides a default value of the the current node when there is no filter value present in the URL. You then check the exclude box in the contextual filter configuration. (Detailed steps below.)

Update In comments, you give more detail about what you want to exclude. Or, put another way, what you want to include. In general terms, you want to include nodes that share ANY taxonomy terms with the current node. Specifically, if you have a Teacher content type and a Subject taxonomy, then your requirement is to show every teacher that shares ANY of the taxonomy terms (representing subjects taught) of the currently displayed teacher.

Contextual Filters can do this out of the box, although the configuration is not especially intuitive. The approach is to add a Content: Has taxonomy term ID contextual filter and then configure it so it pulls taxonomy terms out the current node. (Detailed steps below.)

Stage one: Exclude current node

Add a contextual filter Content: Nid (under ADVANCED to the right of the Views configuration page).
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Content ID from URL'. (This gets the node id.)
In the MORE section check the box 'Exclude'. (This says instead of filtering to show only the node, filter to show anything but the node. Of course, the normal non-contextual filters also apply.)

You can add more than one Contextual filter to build up more complex conditions. And, as noted above, you can write PHP for the Contextual filter.

Stage two:  Include all nodes that share ANY of the taxonomy terms of the current node

(aka, exclude any nodes that don't have any common taxonomy terms with the current node, but include everything else)

Add a contextual filter Content: Has taxonomy term id.
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Taxonomy term ID from URL'. (This is a powerful option and what it does depends on the next configuration steps.)
Uncheck the 'Load default filter from term page' box.
Check the 'Load default filter from node page, that's good for related taxonomy blocks'
You will usually want to check the 'Limit terms by vocabulary' box and then select the relevant vocabulary, e.g. 'Subjects'. You might skip this step if you know you only have term reference field on kinds of nodes you are interested in. But it does not harm to check it even in these cases.
Under Multiple-value handling select the 'Filter to items that share any term' option.
Further down the configuration find the 'Reduce duplicates' check box and check it.
Open up the MORE fieldset at the bottom of the configuration and check 'Allow multiple values'


How to grant User Points after Quiz questions are answered correctly? I have the User Points module enabled and I want to use the Rules module to create a rule which lets a user win User Points whenever the user answers correctly my questions.

I don't know what should I put as Rules Event and as a Rules Condition.

How can I specify that the user only earns User Points when the answer is correct?

If using Quiz 7.x-5.x

Assuming you're using the 7.x-5.x-rc3 version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.

To do so, have a look at the delivered rule, which looks like so:

{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a Rules Action to grant an amount of User Points that you may want to be related to [quiz-result:score] (note that this token is also shown in the Rules example above (within the Rules Action).

If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).

If using Quiz 7.x-4.x

For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

  ... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.

  Patch works for me.


How can I add JavaScript only on the front page? I created a custom Theme: filhos_do_porto using Bartik as a subtheme and I would like to add JS code only to the Front Page.

Can someone help me? (I didn’t find anything specific of D8 clear enough for someone new in Drupal)

One way, in your mytheme.theme file:

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(&$attachments) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $attachments['#attached']['library'][] = 'mytheme/library-name';
  }
}

This points to an entry in your mytheme.libraries.yml file which list out what file(s) to load.


Tokens missing in Webform Emails after upgrading Currently running Drupal 7.69 / PHP 7.3 (+ CiviCRM)
I have recently updated some Modules : Webform, Views Bulk Operations, i18n, and Content Access.
Since then, my Webform Emails do not show the pertaining tokens (but they just show the token titles) :
All those tokens are not populated :
[submission:completed_date:long],
[submission:user],
[submission:values],
[submission:url]
Any help is welcome

I could solve the problem, but an issue still remains.
I have disabled Token and Entity Tokens Modules (and requested associated Modules)
... then reactivated :
The probem comes from the Advanced User Management Module : when it is enabled, most of the tokens cannot be browsed (among which the default proposed ones in the mail content).
... So, I cannot use this Module any more.


FlexSlider fail slideshow I installed FlexSlider as suggested on the module's in Drupal7. I try to put a slideshow on my home page with no luck. I tried to create the FlexSlider Example content but it does not create a slideshow, but only lists the images.

The FlexSlider libs are version 2.4.

The website is here: http://projects.busoniu.net/

the images are uploaded in the FLEXSLIDER EXAMPLE SLIDESHOW and I didn't upload any of it in the FLEXSLIDER EXAMPLE IMAGE.

I get an error when I try to edit the content:

  Notice: Undefined property: stdClass::$name in flexslider_add() (line
  395 of
  /data/home/buso01/domains/busoniu.net/public_html/projects/sites/all/modules/flexslider/flexslider.module).
  Notice: Undefined property: stdClass::$name in flexslider_add() (line
  398 of
  /data/home/buso01/domains/busoniu.net/public_html/projects/sites/all/modules/flexslider/flexslider.module).

In console chrome I can see this error:

  Uncaught TypeError: undefined is not a
  functionflexslider.load.js?nk4e6d:41 (anonymous
  function)jquery.js?v=1.4.4:34 b.extend.eachjquery.js?v=1.4.4:27
  b.fn.b.eachjquery.once.js?v=1.2:55
  $.fn.onceflexslider.load.js?nk4e6d:34
  _flexslider_initflexslider.load.js?nk4e6d:24 Drupal.behaviors.flexslider.attachdrupal.js?nk4e6d:76 (anonymous
  function)jquery.js?v=1.4.4:33 b.extend.eachdrupal.js?nk4e6d:74
  Drupal.attachBehaviorsdrupal.js?nk4e6d:412 (anonymous
  function)jquery.js?v=1.4.4:30 b.extend.readyjquery.js?v=1.4.4:38 u

Put the Flexslider library in sites/all/libraries.

Check Status page for error with flexslider (admin/reports/status).


Searching using Solr within Views I'm learning Drupal, and having a lot of fun. I am approaching the phase were I'd like to make my content more accessible to users.

I haven't implemented it yet, but I am really liking the ApacheSolr Search Integration module. I was wondering if there was any module to search within Views. My problem is that most of my site is based on Views; I have a lot of content on external databases, which I am maintaining, and Views queries that content for the users.

If Solr doesn't have anything I need, is there any other solution?

Please see the Apache Solr Views module for combining Solr and Views together.

If you are looking for a Views-only approach, you should watch this screencast on Exposed Filters.


User profile fields translated but not showing up on user account modification and registration I translated my user fields (select list) and they show up fine on:

Exposed Filters
In .po files and and translated
User Display view mode

However, they don't show up translated for users.

Hard to explain...so let me try this way:

A user registers on the site in French, with fr prefixe.

When modifying his account, the drop downs are not shown in French, they are in English. However, even if English selections are selected, the display is indeed translated into French.

After you translated the select list options of your (user) field, make sure that you ALSO change the Format of that selection list from Default to Default Tanslated, which you can do via "Manage Display" (located at /admin/config/people/accounts/display). Similar to what is explained in this comment also ...

Note: same is true for using such fields within a content type.


Trigger submission via Javascript when exposed filters are changed on a block display in Views I have a View showing a list of nodes that has a block display, with AJAX enabled. It seems that that is required when you using exposed filters on a block display in 8.

What I want to do is autosubmit the form (where did this option go?) when a filter is changed. This is the jQuery I have tried:

    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing input[data-drupal-selector="edit-submit-blog"]').trigger('click');
    });

    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing').trigger('submit');
    });

    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing').submit();
    });

In the first case, nothing happens. In the latter cases, the page reloads with the query string attached. Nothing in the view is filtered.

What am I missing?

Was there a while ago, still don't understand why they'd scrap-off such an essential feature. Thanks to this thread @ drupal , found a solution.

Download the module at #5


What is the difference between hook_preprocess_page and hook_preprocess_html? I see that both hook_preprocess_page() and hook_preprocess_html() are implementations of hook_preprocess_HOOK(), but I don't understand when to use which.

hook_preprocess_page is called first, but that doesn't really help me understand who is calling it.

Looking at the debug_print_backtrace() output, it's getting called by theme(), but that doesn't really get me to the answer.

Is it simply defined by the array that is passed into drupal_render()?

hook_preprocess_page is the preprocess hook invoked when the page.tpl.php template file is used, and hook_preprocess_html is the preprocess hook invoked when the html.tpl.php template file is used.

Both the preprocess hooks are invoked when a page is rendered with theme('page'), since the page element defined from system_element_info() defines html as theme wrapper.

  $types['page'] = array(
    '#show_messages' => TRUE,
    '#theme' => 'page',
    '#theme_wrappers' => array('html'),
  );

system_theme() then defines html as follows.

'html' => array(
  'render element' => 'page',
  'template' => 'html',
),

As for when to implement hook_preprocess_html(), you implement it to alter the variables used in the html.tpl.php file, which by default has the following content.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

As you can see, it contains just the HTML tags that wrap a page content, available in $page. With that, you can change the content of the  tag, the page title (the one that goes in the <title> tag in the  tag), the CSS styles and the JavaScript files added to a page, the classes and the attributes for the  tag.
With the page.tpl.php template file, you can change more of the page being rendered, including the site name, the site slogan, the page title, and the feeds associated with the page. For most of them, there is a specific Drupal function/hook you should instead use.

hook_preprocess_HOOK is the generic hook name used for all the preprocess hooks, in the same way hook_form_FORM_ID_alter() is the hook name used for a class of alteration hooks.


Create menu link for authenticated user programatically So here is what I've tried in custom module dir I've created module.links.menu.yml file here is code. I want to just for authenticated user beside Content link have my custom link to access Webform. Also, do I need routing file to?

description: "Link descr"
menu_name: main
parent: system.admin
url: 'internal:/admin/structure/webform'
  route_name: entity.webform.collection
title: "Webforms"
weight: -48
requirements:
      _role: 'authenticated'

Given that you are simply moving a link of an existing route in a drupal menu, you are probably better off using the more simple hook_menu_links_discovered_alter(). A custom link/route is probably a bit of overkill.

But, presuming you do want to go the way you are in your example, you would need to have both a my_module.routing.yml and my_module.links.menu.yml

In the menu links file you might have something like:

my_module.hello_admin_user:
  title: 'Hello Admin User'
  description: 'See a Hello Admin User Message'
  parent: system.admin_config_development
  route_name: my_module.hello_user
  weight: 100

and in the routing file you might have:

my_module.hello_user:
  path: '/hello-user'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::helloUser'
    _title_callback: 'Hello Admin User'
  requirements:
    _permission: 'access content'
    _role: 'authenticated'
  options:
    _admin_route: TRUE

You've got a bit of a mix going in your example. Note that route names and links names need to be unique across the drupal system. Using your module name as the start is a convention but not required.


How to programmatically save a value in a long text with summary field? I have a content type which has a field of type "long text with summary".

When I to try programmatically save a node with the code below, the value is not being saved.

How can I save the data into the field and set the format to "full_html"?

what does not work (assume the rest of the fields are set):

$node = new stdClass();
$node->type ='some_type';
$node->language = 'en';
node_object_prepare($node);
$node->field_custom_description_value = 'some_value';
$node->field_custom_description_format = 'full_html';

/* I also tried this */
$node->field_custom_description[$node->language][0]['value']-> 'some_value';
$node->field_custom_description[$node->language][0][format]-> 'full_html';

You forget the # in the #format, use this:

$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

Read this: How to set the default format per content type at Drupal 7?


What is the difference betweeen hook_validate and case 'validate' in hook_nodeapi I am bit confused about hook_validate() and case 'validate' in hook_nodeapi(). Both do  validate a node.

Could anyone clear me the difference with a simple example that even a beginner can understand?

hook_validate is used inside a module that creates a node type of its own, and is used along with the form used to create the node to validate that all the information required has been entered.

For example, let's say you created a node type with a specific field in it of "area" and you wanted to make sure it was of the format city-state.  You would do it in here.

hook_nodeapi with op=validate is used to validate any nodes that are being edited but not created by the module in question.

For example, let's say you wanted to make sure a description field in a node with that field had more than 1000 characters.  You would do it with nodeapi/validate.

Carefully read hook_validate and hook_nodeapi for more information or clarification.