Pathauto deactivate when I use node_save($node) I'm trying to save a node code wise (like I've done a dozen times before), but for some reason, my custom URL given with the Pathauto module, disappears... The Generate automatic URL alias checkbox is checked and Drupal ignores my custom URL...

I've tried to give a custom URL with the URL-alias like:

$path = 'events/blablabla';
$node->path = array('alias' => $path);
node_save($node);

But that didn't work out either. So I'm wondering what do I do wrong. As far as I can see, there seems to be a bug in the module, but I have no clue how to solve this.

You'll need to set:

$node->path = array('alias' => $path, 'pathauto' => FALSE);


How To Alter Web Form Elements Permanently? Webform elements can be altered using the function MYMODULE_form_alter. However the changes are not permanent. For example, if you're changing the title of an element from '#title' => t('Old Title') to '#title' => t('New Title') ,the change will not affect source - the (View) Source page will still show '#title' => t('Old Title')
So my question is: Is it possible to alter the source (YAML) from code because that will make changes permanent.I have tried to locate weformX.yml for webformX inorder to alter it in code but I can not find.

You can alter the yaml source of a webform by loading the config entity and modify elements:

use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform->get('elements'));
  $elements['name']['#title'] = 'Please fill in your name';
  $webform->set('elements', Yaml::encode($elements));
  $webform->save();


Show a link in a menu even if user has no access I created a node/add/content-type menu link in my main menu, but it only shows to those who have access to it.

How could I show this to everyone, including anonymous users, and use http://drupal.org/project/r4032login for those who have no access?

Add to the menu a page with no access restrictions that contains the login form. (But still called "Add Content Type" or whatever it's currently called).

Using Rules, add redirects to node/add/content-type

automatically redirects logged-in users
automatically redirects anonymous once logged in from the above page


style.css doesn't refresh while Bootstrap sub-theming I followed the Drupal Bootstrap sub-theming documentation: basically copied the CDN starterkit and renamed all the files and it seems to work.
I then added a line to the empty css/style.css.

At first it didn't work except when I went to /admin/appearance/settings/ and clicked the advanced tab and set the theme to 'Bootstrap (Default)'.

I then made more modifications to the style.css, this time it didn't refresh on the pages. Checking the rendered pages I found the css file is coming as a mangled named css file.

What is involved in generated this mangled file and how to refresh after modifying css/style.css?

Can I choose a different theme from the Bootstrap settings page and still use my css modified styles?

The mangled file comes from aggregating CSS files. You will need to clear/flush the cache in order to see changes.

You can turn CSS caching off by going to /admin/config/development/performance and unchecking aggregate CSS files. Now you don't need to clear the cache to see CSS changes.

PS: Remember to turn this back on when your website is ready for production/going live.


Why is migration lookup failing during synchronisation of Group entities? On the basis of an RSS feed, I am required to create Group entities and Users out of the feed's items.

Each item contains sufficient data:

<item>
  <id>123</id>
  <title>An example</title>
  <description>Some &lt;strong&gt;HTML&lt;/strong&gt; description.</description>
  <author>John Doe</author>
  <email>john.doe@example.com</email>
  <pub_date>09/19/2017 - 08:30</pub_date>
</item>

I am using Core's migration module along with migrate_plus and migrate_tools and wrote two migration yml files, one for creating Group entities out of the items and one to generate users out of the author & email fields.

Taken separately, both work fine, that is I am getting Group entities and User entities as expected. The only issue which I can't get my head wrapped around is to set the respective User to be the Group's owner.

Here's the processing part of the Group yml file:

process:
  uid:
    plugin: migration_lookup
    migration: migrate_plus.migration.users
    no_stub: true
    source: email
  label: title
  field_description: description
  created:
    plugin: format_date
    from_format: 'm/d/Y - H:i'
    to_format: 'U'
    source: pub_date
  status:
    plugin: default_value
    default_value: 1
  type:
    plugin: default_value
    default_value: my_group_type

migration_dependencies:
  required:
    - migrate_plus.migration.users

All fields except for uid are set correctly. If I change the user id process part to something static like

  uid:
    plugin: default_value
    default_value: 1

it works as well and the Group's owner is set to the Super User account. So, I reckon there's something wrong with the migration_lookup processing part. I have read numerous tutorials on how to use that and it looks fine to me. I also read that migration_lookup fails silently if there is an error which makes it hard to debug.

Looking at the migration map table in the database it looks fine too:

mysql> select * from migrate_map_users limit 1;
+-----------------+----------------------+---------+-------------------+-----------------+---------------+------+
| source_ids_hash | sourceid1            | destid1 | source_row_status | rollback_action | last_imported | hash |
+-----------------+----------------------+---------+-------------------+-----------------+---------------+------+
| 009d...234ef457 | john.doe@example.com |     118 |                 0 |               0 |             0 |      |
+-----------------+----------------------+---------+-------------------+-----------------+---------------+------+
1 row in set (0.00 sec)

Due to the migration dependency through

migration_dependencies:
  required:
    - migrate_plus.migration.users

the User migration should also run first, but it still doesn't work. Even after both migrations have run through, I tried an update migration run, but the Group's owner is never set (stays at being 0/Anonymous).

Is there soemthing wrong with my yml file? Are there other means to connect user and groups?

s/migrate_plus.migration.users/users/

The "migrate_plus.migration." is not part of the migration plugin ID - it is only part of the filename for the config entity.


Include a part template on specific node page I would like to include some custom html code only on a specific node.
I created "parts" directory and put a custom twig template in it. (mytheme/templates/parts/custom_html.html.twig)

I then copied over the page.html.twig to my templates directory, and included the custom template with:

{% include directory ~ '/templates/parts/custom_html.html.twig' %}

I want to show this only on a certain node, say "node/2". I don't wan't to create a custom template just for this page, like "page--node--2.html.twig".

Is there a way of using a condition to just show this template on the specific node?

Kind of like this?

{% if 'node/2' %}
    {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

If you want override page.html.twig for special node 2. You can try this code

{% if node.id == '2' %}
   {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

if other template you need process in your function theme first:

YOUR_THEME_process_FUNCTION_THEME(&$vars) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $vars['node'] = $node;
  }
}


What is the best way to add a comment policy to the comment form? Surely this is a common use-case... I would have thought? Underneath "Add new comment" heading I would like to add a block of text like "Comments are pre-moderated and may be edited before publication". I have an internationalised site so the text must be translatable.

You can do this easily with a form_alter hook.

<?php
function MODULENAME_form_comment_node_NODE_TYPE_form_alter(&$form, $form_state, $form_id) {
    //drupal_set_message('<pre>'.print_r($form, 1).'</pre>');
    $form['privacy-note'] = array(
          '#markup' => t('Comments are pre-moderated and may be edited before publication');

        );
}

Yes it sounds a little silly to make a module for this. But making a little module for every little work is also not a smart option.
If you have never created a module before, See this: http://drupal.org/node/1074360
Don't forget to change MODULENAME and NODE_TYPE with actual values. if you have any questions, I'd be happy to answer them here :)


How do I theme a taxonomy term page? I am working on Drupal 8, trying to get a page template for each vocabulary. I have tried using hook_theme_suggestions_HOOK_alter() to achieve this, but I was not able to do it.

I tried using Devel with kint(), but no debugging information is shown on my screen.

How can I add a template suggestion for a vocabulary?

You can suggest a new template file with the following code.

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

Then create the file: page--taxonomy--VOCABULARYNAME.html.twig and customise it as you wish.


How do I fetch translated strings? I have a progressively decoupled Reactjs application running on top of Drupal. Its a multilingual application.

I need to fetch the translated strings from the Drupal itself and handle the translations editor and everything in Drupal itself, rather than maintaining a separate translation system for react.

How is it possible? A simple Drupal.t() doesn't work. I checked.

Any examples I can refer?

Drupal.t() works in this case. Have to to compile the javascript and clear the Drupal cache in order for strings to appear.

For props way:

On get_sample_props():

function getsampleprops() {
  return ['sampleval' => t('Hello World!!!')];
}

On the controller,

$build = [
  '#theme' => 'sample_react',
  '#props' => json_encode($this->get_sample_props()),
];

On the template, I did:

On the React side, I used

$val = this.props.labels.sampleval;

Volia, its done. Its bit inconvenient, but work gets done.


Menu randomly does not display Currently I maintain 10 different Drupal 7 web sites. They were designed and built by 3 different developers. These sites are running on 3 different platform types. Some are on a dedicated server, some on a VPS server and some on Pantheon. The dedicated and VPS servers are running Apache 2 and Pantheon uses Nginx. They are on various versions of the Drupal core, between 7.43 - 7.56.

All of these sites are experiencing the same issue, at some point the main navigation menu which displays on all the site pages just stops displaying. When this happens there are no errors in the Apache or Drupal logs.

On the dedicated server and the VPS servers clearing the Drupal cache (sometimes more than once) will bring the menus back. On the Pantheon servers, clearing the Drupal cache (even multiple times) does not work. The only way to do it is to clear the cache for the site in the Pantheon dashboard for that particular site.

The only common things between these sites are:

There is nothing "special" about these menus. They were all designed using the standard Drupal utility in the Structure menu
They are all sub-themed using the Drupal Bootstrap 3 as the base theme, currently at 7x-3.13

Google hasn't helped so I'm wondering if anyone has seen this error and if so, where I can start looking to correct the issue.

Last time I encountered such thing, it was on Drupal 8. The culprit was caching. In a gist, if the page was viewed by a user who doesn't have access to that menu and that result gets cached, the page will be served from cache (without that menu) until the cache is cleared. Might want to disable page caching, then block caching, in admin to verify this. If you have any other caching mechanisms, try disabling those too. A good indicator that this may be the case is the fact that you need to clear an external cache for one of your setups.

Another culprit would be template-side logic (template.php or directly on the templates themselves). Since you're using D7, it's relatively easy to sneak in PHP into templates. You might want to review your templates for this.

Lastly... there's JS and CSS. You might want to do a View Source to see if the markup is actually there, but just removed by JS or hidden by CSS. Due to Drupal's steep learning curve, it's very tempting to just do everything in JS and CSS. Also, if the menu is dynamically generated or enhanced by a script, a broken script might have interfered with that generation/enhancement.


How to restrict ckeditor to display full html alone? I am using ck editor and want to hide the filtered html and plain text.

And user should use only the full html format. They should not get the option to select filtered html and plain text.

Anyone guide me how to do this in ck editor?

You can install the Better Formats module to achieve this.

Better formats is a module to add more flexibility to Drupal's core input format system.

  Features

  8.x & 7.x (needs more testing for a stable release)

  Set allowed text formats per field.
  Set default order of text formats per field.
  Hide format tips per role.
  Hide more format tips link per role.
  Hide format selection per role per entity.
  Currently only works on Field API fields on fieldable entities implementing core - style text processing. The good thing is that is
  most things in core and contrib.

This will let you limit what format is available per field implementing formatted text, like a body field.

Despite what the warning says, I have used this extensively on many sites to do exactly what you asked about.


Adding users to entity reference field by custom field I have added some custom fields to my D8 site's user profiles. Would it be possible to add users to a entity reference field on a node using one of these? For example phone number, as that is one of the fields. Or am I stuck referring to only the users username?

You can use any field to lookup a user in a entity reference field. You just need 2 things: an entity reference View & a configured entity reference field.

Through the Views UI, you can add a User view with an Entity Reference Display. Add any fields to the View that you'll want to search on. Once your do, the Settings link next to Format:Entity Reference list will popup a modal that will let select your Search Fields.
After you've created your view, add your node's entity reference field. Set the Reference method to Views: Filter by an entity reference view. Where View used to select the entities is set to the view you created in step #1. Once the new field config is saved, you'll be able to search for any users based of the text values in the fields selected in Search Fields.


Base tpl file for "add content" page? I'm building my first drupal site, and I'm aware there's a huge amount about theming that I don't understand. Right now I'm learning to create custom layouts for specific pages by copying and modifying the template file for that page type (e.g., node.tpl.php -> node-—my-content-type.tpl.php). Now I'm trying to modify the "add content" page for a specific content type. Is there a template file that I can copy and modify, and if so, where can I find it? Or does this page type need to be handled differently?

This is in Drupal 7.

What I've tried:

Modifying node.tpl.php doesn't affect the add content page, nor does creating and modifying node--add.tpl.php nor node--add--my-content-type.tpl.php.
Modifying page.tpl.php does affect the add content page (and all other pages). However...
Copying it to page--node--add--my-content-type.tpl.php (as suggested in this question) causes the add content page for my-content-type to not display at all, so apparently there is some other template info that's needed.

Try

theme_node_add_list

Parameters

$variables: An associative array containing:

content: An array of content types.

function theme_node_add_list($variables) {
  $content = $variables['content'];
  $output = '';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
' . l($item['title'], $item['href'], $item['localized_options']) . '
';
      $output .= '
' . filter_xss_admin($item['description']) . '
';
    }
    $output .= '
';
  }
  else {
    $output = '
' . t('You have not created any content types yet. Go to the content type creation page to add a new content type.', array('@create-content' => url('admin/structure/types/add'))) . '
';
  }
  return $output;
}

See here


How to print taxonomy term name with views PHP? I have a views that include node title, a text field and a taxonomy term reference field.

I need to print the taxonomy term name via Global: PHP field (Views PHP) but I couldn't.

How to print taxonomy term name with Views PHP?

I can print the node title with that code:

Value Code:

return $row->title;

Output Code:

<?php print $value; ?>

or without Value Code:

Output Code:

<?php print $row->title; ?>

And I could print the taxonomy term ID with that code:

Output Code:

<?php print $data->field_field_my_taxonomy_term[0]['raw']['tid']; ?>

But using name or value instead of tid doesn't return anything.

I also tried to print the term name with these ones but unfortunately none of them worked:

$data->field_my_taxonomy_term[0]['raw']['value'];

(Above code prints nothing.)

<?php $data->field_my_taxonomy_term[0]['raw']['taxonomy_term']->name; ?>

(Above code prints nothing.)

So, I'm confused now and not know how to print taxonomy term name with Views PHP?

Note: I looked at these but still couldn't solve the problem:

Views Php how to select actual term name not term ID
https://www.drupal.org/node/1707002
https://www.drupal.org/node/1516348

Storing PHP code directly on database is not a correct method, it causes many issues. Better you can add the relations on your views - "Content: Taxonomy terms on node". and then add the taxonomy term name field as a "hidden field"

Print the value via "Global: Custom text" field if required any custom wrapper around of it.


Search field for views How do I implement a search filter/field for my view? Lets say I have a view with a list of names/titles and there's a lot of them, so users could use search to filter through?

While creating a filter in a view you can expose the actual field to the use.
In case of a title field you would create a filter for the field Content: Title and enable the checkbox Expose this filter for visitors, to allow them change it.

Screenhot

After saving your view the filter would appear above your view. Depending on your search requirements you can also change the search-operator to several options. In case of a "Live search" on a big list of entries i would prefer to set the view to use Ajax in the Advanced settings of the view.


How to hide taxonomy terms from node display and still have them indexed by Drupal search? I use content type with a term reference field.
I would like users to search by taxonomy terms in that field so I keep the field visible in the main node display.
However due to other reasons I would like to hide these terms from the view but keep the content searchable by these terms.

For example I would like to have synonyms searchable I will keep in my term reference field but I don't want users to see all possible variant of the word.

How to hide taxonomy terms from the node display and still have them indexed by Drupal search?

I would recommend the Search API. You end up with much more control over the search results, and you have the extra flexibility of using it with views.

You can configure it to also include taxonomy term descriptions in the index which would be an excellent place to store your synonyms/alternate search terms. You could even create a new vocabulary that is never displayed on the node (just set it to hidden in the display tab for the content type), and is limited to only search terms.


Taxonomy URL Inside View I've created a View that displays all of my 'Product Category' taxonomies. I'd also like to get the path alias for each taxonomy listed. Usually to do this, I'll add a hidden 'Path' field, so I have access to it in my Twig template.

There doesn't seem to be that 'Path' field though, the closest I can find is 'Link to Taxonomy term' field. This isn't what I'm after though as this field seems to be preformatted, when all I want is an absolute URL. I've tried playing around with the rewrite rules of this field, but none of the changes seem to take affect.

Is there a way for me to convert the Term ID I have access to into my system path or path alias of my taxonomy pages? Is there a different way? Thanks in advance.

Add the field Taxonomy term: Term ID to your list. On the settings of this field you have options for Rewrite results check the box Output this field as a custom link on the path option you can write it taxonomy/term/{{ tid }} and below to can check the box Use absolute path if you want too.

This will automatically convert the link into alias if it exists.


What are best practices for creating node relationships? In Drupal 7, what are the best ways of creating relations between nodes?

Say I have a number of articles about famous writers. I want to build an alphabetical list of them using Views. As writers often have pseudonyms, I want these pseudonyms to appear in the list too but creating a node for a pseudonym that is identical to its respective Writer node in all aspects except title sounds like not quite good idea.

I thought a bit and came up with 2 node types, Writer and Writer_Pseudonym:

Writer

Title
Body
All other fields

Writer_Pseudonym

Title
Target Node Id

Now I want to build a view in which nodes of type Writer_Pseudonym will display body text of their target nodes:

  Title: Doe, John (Writer)

  Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".

  Title: Evil John (Writer_Pseudonym)

  Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".

Is it possible to do it with Views? And if not, are there any other ways to establish relations between nodes while being able to use fields of target nodes?

Your best bet for this kind relationship is going to be Taxonomy. You can create a free tagging vocabulary (exactly like the vocab that is initialized with the Article content type in a standard profile D7 install) and as these "Authors" come up with a need for a "Pseudonym" you just tag that node with it's term.

Views supports most every use case (if not all) you can imagine working with Taxonomy.

Because Taxonomy is core it's further developed and easier to use than alternative relationships (references, hierarchy, etc).

For the above example, you'd could configure the view to display all (full, teaser) or part (fields) of the "Author" content type based on being tagged with the relative "Pseudonym". Views are a little daunting at first but if you keep playing with them, you'll soon realize their immense capability.

Just comment if you need clarification on any of the above...


How to solve tput problem when installing drush on Windows? I am trying to get Drush running on my local development site. Drush & Cygwin are installed and the cygwin command prompt responds to Drush commands such as "Drush topic" but precedes the command output with:

  "which: no tput in + a long list of directory paths"

and then gives the topic list.  When I respond with 16 (Drupal help for error messages) I get:

  fwrite(): supplied argument is not a valid stream resource [warning]
  output.inc:29

I believe I have to add path definitions, but am not certain where to define them.  My current configuration on a windows OS has apache & php under C:/Program Files/acquai drupal/ (I used their setup for php and apache, but not their Drupal Site setup.)  I have Drush located under C:/Drush and my site located under C:/Documents and Settings/admin/my-site.

Ashlar seems to have found a solution to the tput problem in his own bug report 'by adding the add-on gygwin command tput from the cygwin installation program "setup.exe". The actual command i not on the list. Look for the "ncurses" package which includes the Tput utility.' ... see http://drupal.org/node/1361510#comment-5327144


Prevent editing for role after date in field Individual nodes of a content type need to have their edit capability for a role removed after a date provided by a CCK field. The idea is that these nodes are entered by various roles, given a "start date" and displayed on the site in a few layouts. After the start date has passed, the node should be uneditable by this specific role.

How can this be achieved, is it possible by using a module-only method or can it be done in code?

Yes, you can do that with

hook_node_access

For example, something like:

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  // If editing target node type
  if ($op == "edit" && $node->type == 'target_type') {
    // Check against passed account or current user
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // If date field is set, user has target role and date is in the past
    if(isset($node->field_target_date[LANGAUGE_NONE][0]['value'])){
      $date = $node->field_target_date[LANGAUGE_NONE][0]['value'];
      if((in_array('target_role', $account->roles)) && (REQUEST_TIME > strtotime($date))){
        // Deny edit access
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;

}


How do you perform a rules action by the quantity of a specific commerce product? I'm working on a module which is going to be used alongside Drupal Commerce so people can buy a set number of digital products. I've written a custom rules action, which will be run once for each purchase of a specific commerce product. How can I add this to a loop, so that the action gets run n times (n being the quantity purchased for this product, as you could purchase more than one).

So far I've added this action to a loop for commerce-order:commerce-line-items but even if I purchase more than one, the action is only run once. How can I make the action run 'quantity of this product purchased' number of times?

Many thanks

The quickest way to do this is with another custom action. Since you already wrote your own module, this shouldn't be a problem.

In your my_module.rules.inc file, do something like:

function my_module_rules_action_info() {
 return array(
  'my_module_loop_based_on_qty' => array(
    'label' => t('Execute a loop based on a quantity'),
    'parameter' => array(
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity added to cart'),
      ),
    ),
    'group' => t('My Module'),
  );
}

function my_module_loop_based_on_qty($qty) {
  // Loop based on the $qty variable
}

Provide whatever other parameters you need for the function as well. You can then pass it the quantity when you create the rule. That other rules action you already wrote can just be wrapped in a helper function that is then called by this new action.


Single form multiple submit I have one simple quick contact form (webform), it's working fine but sometimes when user fill form n submit it get submitted 2 times or 3 times.

I have checked the submission table that same data is submitted on same time 2 or 3 times.

This happens sometime but not for all submit .

If anybody have resolved this type of issue then please let me know how you have resolved it.

Thanks in advance.

You can try out a more general solution for all the forms by using Hide Submit Module

  Some users accidentally click the submit button more than once while
  waiting for their post to be saved. In some cases this may result
  duplicate postings or duplicate e-commerce orders.

  There are few ideas on how to solve duplicate postings but none is
  perfect. One of the solutions is a bit of jQuery to hide or disable
  the submit button after it has been clicked and replace it with an
  informative text such as "Processing..." .

  This module wraps that jQuery code and provides some options. Of
  course this, too, is not a perfect solution as it requires Javascript
  to be enabled. For browsers with Javascript disabled this module will
  have no effect at all.


How to count the number of calls to a rest service? I created a rest service which every user on the site calls from a product we are selling.

How do I count the number of calls for every user so I can generate a report of this.

D8

Do your REST service needs authentication?

If yes, you just log each access attempt by users:
One attempt per one record per user or one record per user and updating the count column always.

If there is no authentication, you will have harder time to achieve this.
It would be also good to know HOW they are making this rest calls (eg: clicking on a button which resolves into a rest call?).

You could still try to check session and find out which user made the requeset.


Loading term references into a custom module I have a term reference field in my content type. I'd like to be able to access the vocabulary items from that field in a custom module so I can pre-select one based on a users selection of an item from a field list. How is this possible?

An example might help illustrate the problem:

Content type: resource
field 1: Category (field list)
field 2: Group (term reference, hidden)

User selects one of eight options in the 'field 1' drop down select box. Selections include things like 'paper', 'metal', 'stone', etc.
The hidden 'Group' field detects which selection the user made above and auto-fills itself by selecting the vocabulary item in the associated taxonomy that maps to the selection they made. There are only three possibilities for 'Group' however so I'd also have to specify in the module WHICH selections from the field list map to which terms from the taxonomy to make sure the selections are correct.

For example, if a user selects 'paper' in the field list then Group should auto-select the term 'recyclable' before saving the record.

Anyone know how to do this?

I was going to approach it with hook_form_alter and hook_node_presave...but I'm not very comfortable with coding in modules yet.

Thanks!

If the field is hidden and doesn't do anything client-side, you shouldn't touch it client-side. Do the Category -> Group translation server-side even if you're not very comfortable with it yet.

hook_node_presave should do the trick.


How to hide the block title? We have a block on some pages which we like it without title, but when using < none > or leave it blank, it just showing the page title on the block title !

So how can we hide the block title ?

In the Block title field, use <none> to display no title. Go to     admin/structure/block/manage/system/main/configure: You will find the following description.

  Override the default title for the block. Use <none> to display no title, or leave blank to use the default block title.


How to display a percentage for a pie chart label using the Charts module? I'm using the Views integration of the Charts module, with HighCharts as the charting engine.

I want to create pie chart, in which I want to also get the percentage displayed when I hoover over any of the pie slices. I cannot find any specific option to do so.

Anybody any suggestions to get this to working?

This is a typical request for the Charts module ... There is currently no out-of-the-box solution available in the Charts module. But since you're using Highcharts, there is a patch available that may help somehow. The patch is attached to Comment nr 4 of issue #2209467. Be aware of the current status of this issue, i.e.:

the patch only works for Highcharts (as charting engine), the Google Charts counterpart of it is still missing (and prereq for adding this feature to the Charts module).
it is related to the Charts API (which is different from the Views integration). So after the Charts API feature gets delivered, some more (minor?) work is needed to also make it available within the Views integration of the Charts module.

The child issues of this issue contain some more variations, which may also help.

So only considering the Charts module as an alternative, and applying the suggested patch is not sufficient. But at least it should help somehow to understand what the missing pieces are. And maybe inspire somebody to submit 1 (or more) additional patch(es) to make it complete?

Note: The issue about "Views field as data label for better tooltips" is somehow related to this issue, and specific to the views integration. Comment # 6 in it contains an interesting patch for it also.

Disclosure: I'm a maintainer of the Charts module, I hope this does not violate the site's policy on self-promotion.


How to print entity referenced fields (node) title in node.tpl.php? I want to print an entity referenced fields (node) title in node--customtype.tpl.php.
<?php print render($content['field_my_entity_reference']); ?> prints the field with some CSS class as below:

Entity Title

What I want to do is to print this field without any pre-defined CSS classes etc..
[field_my_entity_reference] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [target_id] => 11
                            [entity] => stdClass Object
                                (
                                    [vid] => 41
                                    [uid] => 1
                                    [title] => Entity Title
                                    [log] =>
                                    [status] => 1
                                    [comment] => 1
                                    [promote] => 0
                                    [sticky] => 0
                                    [nid] => 11
                                    [type] => project
                                    [language] => es
                                    [created] => 1466009429
                                    [changed] => 1466502663
                                    [tnid] => 0
                                    [translate] => 0
                                    [revision_timestamp] => 1466502663
                                    [revision_uid] => 1
                                    [body] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [value] =>

I tried <?php print $node->field_my_entity_reference['und'][0]['entity']['title']; ?> but it gives error:

Fatal error: Cannot use object of type stdClass as array in

How can I print the title value of entity referenced field in node.tpl.php?

OK, without knowing anything about stdClass Object these kind of questions are normal :)

So, after reading a question about stdClass Object in SO I did what I want as below:

<?php print $node->field_my_entity_reference['und'][0]['entity']->title; ?>

This prints the title as plain text.

Note: Is there another way or better way you're always welcome.


How do you get the tid from a taxonomy term page? I've got a component on a taxonomy term page and need to use the TID in it's preprocess function.

How do I actually get the tid to save as a variable?

You can use menu_get_object():

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  $tid = $term->tid;
}


Trigger on selected field change So I have a Drupal 7 Workflow rule where an email is sent out when a select field on a comment is set to "Approved'.

This works fine with the exception being if I then add an additional comment to the form, the email is then re-sent. the reason being is that I'm just checking the select field value and triggering the email based on the value.

I just want the email to be sent when the select field is initially set to "Approved".

Here is the export of the rule in question:

{ "rules_notify_status_approved_test" : {
"LABEL" : "Notify - Status Approved TEST",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--request_ad_match" : { "bundle" : "request_ad_match" }     },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "request_ad_match" : "request_ad_match" } }
    }
  },
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "4" : "4" } }
    }
  },
  { "data_is" : { "data" : [ "node:field-request-status" ], "value" : "74" }     },
  { "AND" : [] }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "user", "value" : [ "node:author" ] },
      "PROVIDE" : { "variable_added" : { "node_author" : "node author" } }
    }
  },
  { "mail" : {
      "to" : "email@email.com",
      "subject" : "request has been approved",
      "message" : "request has been approved",
      "language" : [ "" ]
    }
  }
]
}
}

Any direction is appreciated.

Thanks!

It seems that to get it to work, you should at least add yet another Rules Conditions, in which you compare the value of your field-request-status field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.

For a variation of your question, with way more details on this, refer to the accepted answer (disclosure: it's mine ...) to "How to send an email using Rules when a node's boolean field is changed?".


Get scheduled rules in rule I need to get the date of a scheduled rule and display it to the user.

I also would like (Not necessarily required, I can also use an invisible CCK field) to use the existence of this schedule as a condition in yet another rule.

Is it possible to get this using rules alone or do I need to use the "Execute custom PHP code" condition/action to find them?

What about doing it the other way around? Use a date field and triggering the rule according to it?


Upload progress on nginx I am using the latest version of Drupal 7 and my webserver is Nginx. I checked the status report and it says:

  Upload progress Not enabled
  Your server is not capable of displaying file upload progress. File upload progress requires an Apache server running PHP with mod_php.

How can I fix that problem?

Try with the FileField Nginx Progress module.

  This module provides support for an upload progress bar for a backend/server implementing the RFC 1867 upload using multipart/form-data. Nginx does not yet support RFC 1867 uploads in
  its suite of official modules. You can use the Upload 3rd party module to do that or just rely on PHP FastCGI support for RFC 1867.


Add your own content to node I've created a module that adds custom content to a node; I'd like to display this custom content in the node view. I think hook_node_view() is the right hook to use, but my content doesn't get displayed.

what I got so far is the following code:

function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
$node->content['mymodule']['#items'][0] = array(
    'value' => theme('mymodule_output', array('mymodule_cid' => $node->mymodule_cid)),
    'summary' => '',
    'format' => 'full_html',
    'safe_value' => theme('mymodule_output', array('mymodule_cid' => $node->mymodule_cid)),
    'safe_summary' => '',
);
$node->content['mymodule']['#weight'] = 12;
}

Can anybody help?

TL;DR: The hook is correct, but $node->content['mymodule']['#items'][0] should at least contain one of these array indexes/properties: "#markup" or "#theme"; if you don't use one of them, Drupal will not output anything.

If the array indexes you use are for properties handled by your theme function, then you should use # at the beginning; for example "format" would become "#format" (the same is true for the other properties).

Anyway, there is no need to use "format" as you do (whatever meaning it has); the function just output HTML, as done in the example shown in the hook_node_view() example.

function hook_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

If you want some more concrete examples of that hook implementations, you can look at book_node_view(), statistics_node_view(), and translation_node_view().

function book_node_view($node, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $node->content['book_navigation'] = array(
        '#markup' => theme('book_navigation', array('book_link' => $node->book)),
        '#weight' => 100,
      );
    }
  }

  if ($view_mode != 'rss') {
    book_node_view_link($node, $view_mode);
  }
}

As side note, I will add that you should use the # character only for properties, or you are going to confuse Drupal, which expects that character to be used only for properties.
In fact, element_children(), which returns the list of child elements of the element passed as argument, uses the following code:

  foreach ($elements as $key => $value) {
    if ($key === '' || $key[0] !== '#') {
      $children[$key] = $value;
      if (is_array($value) && isset($value['#weight'])) {
        $sortable = TRUE;
      }
    }
  }

As you see, elements whose key value starts with # are not taken to be child elements; differently, Drupal would not be able to handle a case like this one (the code is really implemented by a Drupal module, the Search module):

  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $module,
  );
  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array(
    '#type' => 'value',
    '#value' => '',
  );
  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

Are $form['#action'] and $form['basic']['submit'] child elements?

As another side note, I will add that hook_view() is invoked by Drupal only for the modules that implement a content type.
In fact, the implementations of that hook are invoked by node_build_content() using the following code:

  // The 'view' hook can be implemented to overwrite the default function
  // to display nodes.
  if (node_hook($node, 'view')) {
    $node = node_invoke($node, 'view', $view_mode, $langcode);
  }

The code for node_invoke() is the following one:

  if (node_hook($node, $hook)) {
    $base = node_type_get_base($node);
    $function = $base . '_' . $hook;
    return ($function($node, $a2, $a3, $a4));
  }

The code invokes $hook for the module implementing the content type of the node passed as argument.


How to fetch/load a node form using jquery/ajax? In my previous question, I asked on how to fetch views blocks, now I would like to do the same with the node form but somehow this is the code that almost worked for me:

setTimeout(function(){
  $('.custom-form').load('?q=node/add/custom #custom-node-form', function() {
    Drupal.attachBehaviors();
  });
}, 1000);

The ajax/jquery of the form doesn't work anymore, for example: date field - popup calendar, unlimited field.

I also tried this:

setTimeout(function(){
    $('.custom-form').load('?q=node/add/custom #custom-node-form', function() {
         Drupal.attachBehaviors($('#custom-node-form'));

      });
    }, 1000);

still not working.

Are there other ways to load the node form with all it's ajax/jquery settings?

I'm using this kind of approach because I have a super long form. When I try to print it on the template or on the regions/blocks, it affects the load speed. I don't want this to be part of the page load.

UPDATE:
I'm also trying to load the formblock module using the method I used on the ajax views as an alternative, I also can't get it to work.

Thank you.

I don't think you've got the right parameters on the jQuery "load" method. The jQuery API page has this for the signature:

.load( url [, data ] [, complete ] )

This might be a working revision (not tested):

$('.custom-form').load('?q=node/add/custom', {}, function() {
     Drupal.attachBehaviors($('.custom-form'));
});

However, your strategy will load the entire Drupal page, not just the form. The AJAX-loaded page and form will not be in the expected request context - I'm not sure that the form can be successfully submitted in this circumstance.

You might try looking into implementing CTools Modal API instead, which is designed to allow the loading forms into modal windows via AJAX.


Display entityreference field in search-result.tpl The entityreference field (field_parent) shows up in node.tpl using print render($content);, but isn't displayed in search-result.tpl. My search-result.tpl looks like this right now:

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

  <?php print render($title_prefix); ?>

  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

Imported on <?php print $info_split['date']; ?>.

<a href="<?php print $url; ?>">Comments

<a href="<?php print $result['node']-> field_download[LANGUAGE_NONE][0]['url'] ?>">Download

Lipsum: <?php print $result['node']-> field_lipsum[LANGUAGE_NONE][0]['value'] ?>

I tried using <?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['value'] ?> but it gives me the error "Notice: Undefined index: value in include() (line 25 of ...\search-result.tpl.php)."

<?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['entity'] ?> gives

Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 25 of ...\search-result.tpl.php).

<?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['entityreference'] ?>

Notice: Undefined index: entityreference in include() (line 25 of ...\search-result.tpl.php).

I solved this by using teaser view as my search result. My search-result.tpl file now looks like:

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

<?php $v = node_view($result['node'], 'teaser'); print render($v); ?>

</li>


How to change the draggable icon of new theme I am using draggable table in my new theme. Every thing is working properly but

I want to show this icon like in Bartik theme for every draggable rows:-

Currently it is showing as

How to change this?

I suspect it's similar to a problem I had with draggable table rows in a zen subtheme: the icon was just a bit mis-placed. Using Firebug or similar tools you can see what's going on – on my site it looked like this:

Using firebug I could see the reason for this:

The icon was mis-placed. So I suppose you probably don't have to change the draggable icon itself, but you'll have to adjust the position of the icon.

The css responsible for the position should look like this:

a.tabledrag-handle .handle {
background: url("../../misc/draggable.png") no-repeat scroll 6px 9px rgba(0, 0, 0, 0);
height: 13px;
margin: -0.4em 0.5em;
padding: 0.42em 0.5em;
width: 13px;
}

and you should find it in this system css file:
/modules/system/system.base.css

Instead of changing it in that system css file you should however override the settings in your theme's css file. You probably don't have to change much – just have to play around with the settings for margin and padding according to your theme… Hope this helps somehow?


How to check if a password reset token is still valid? Is there a way to hook into the user_pass_reset form to detect if the provided hash is valid? Currently it seems to just throw a 403 error when submitting the form if the hash has already been used to change the password.

Using hook_form_alter(), I can retrieve the hash itself with explode("/",$form['#action'])[5], but am unsure how to check if it's already been used or not, or if it's expired. I see that this information might be part of the UserController class, but I'm not sure how to retrieve that.

Welp, I probably should have gotten the idea to follow where the form action actually takes you and see what its controller does. I pulled the timestamp and hash from the form action with the explode function, loaded the user object from the currentUser id, and used Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp));.


How to set page variable from custom module In Drupal 8:

I have custom module code that declares its own theme can twig template.  How do I make module variables available to my Drupal theme's page.html.twig?

I have tried various preprocess_page* functions; however, those functions don't see the variables the module is passing to it's own themed twig templates.

Can the module's controller inject something into the page variables?

Can a Drupal theme's preprocess functions access some variables flowing from a custom module to the module's twig templates?

The controller file:

class PromtController extends ControllerBase
{
    public function program($id)
    {
        $program = PromtService::program((int)$id);

        return [
            '#theme'   => 'promt_program',
            '#program' => $program,
            '#title'   => $program['title']
        ];
    }
}

The module code:

function promt_theme()
{
    return [
        'promt_program' => [
            'template' => 'promt_program',
            'variables' => [
                'program' => null
            ]
        ]
    ];
}

As far as I can tell, this should be handled in the custom theme, not in the custom module.  This is because the module really has no idea how a custom theme wants to render stuff.

In any case, in the custom theme, the only way I can figure out how to make the data available is to register a hook_preprocess() function in the theme, check the hook that's called, and declare a static variable that sticks around until it can be injected later on.

The custom module's "promt_program" hook will be called earlier than the theme's "page" hook. I'm pretty sure that will always be true.  So, we grab the location_id and then inject it later on.

This preprocess function will get called many, many times, so it seems important to make it thin.

function cob_preprocess(&$vars, $hook)
{
    static $location_id = null;

    switch ($hook) {
        case 'promt_program':
            if (!empty($vars['program']['location_id'])) { $location_id = $vars['program']['location_id']; }
        break;

        case 'page':
            if ($location_id) {
                $query = \Drupal::entityQuery('node')
                    ->condition('status', 1)
                    ->condition('type', 'location')
                    ->condition('field_promt_id', $location_id);
                $nids  = $query->execute();
                if ($nids) {
                    $vars['node'] = \Drupal::entityTypeManager()->getStorage('node')->load(current($nids));
                }
            }
        break;
    }
}


How do I override a default view template from another module? Drupal provides hook_theme(). But is there a hook_theme_alter()? I'm looking for something like hook_menu_link_alter(), which overrides hook menu entries, but for the theme. I want to modify a view hook theme entry so I can specify where to look for one of my custom templates. I am not interested in specifying it through the Views interface, since it look for the theme template inside the theme folder, and I want my template in a feature module.

I found hook_theme_registry_alter() and _theme_process_registry(). You can answer which one is the best to use and why.

Which of these keys should I modify in order to make the view pickup the template from the module?

If I put views-data-export-xml-header--richard-feeds-nokia-movies--views-data-export-1 in the feature, the View defaults to pick up views-data-export-xml-header.tpl.php. If I put that template in the theme layer, the view picks it up (even with the registry alter hook in place).

Your feature should implement hook_theme_registry_alter(). The use case you describe is exactly what that hook is for. The example code linked on the API page should get you started. The basic idea is to target the entry that corresponds to the entry that views_theme() is inserting into the registry, and change the template to match the one in your feature.


Referenced node as menu item is it possible to create a menu item that links to the node that references the current user? I can create a more or less suitable solution with views: a page that contains the referenced node but it'd be more user friendly if the menu link contained the URL of this node.

Try Menu token

  Menu Token module provides tokens, that could be used in title or in
  path of menu items (links). For example, if you create a menu item
  with path: "user/[current-user:uid]", the url will be changed "on fly"
  to: "user/1" (assuming you are user 1).

  Tokens are provided by Token module. Menu Token allows to use both
  global tokens and entity ones: node, user, term, etc. Entity tokens
  have several methods of substitution: from context, random and user
  defined.

If that does not work, you will have to do a custom redirect, either in code or using page manager (part of ctools)


How to get the string value from the function CountryManager::getStandardList()? Input :

 $li = array();
    $list = \Drupal\Core\Locale\CountryManager::getStandardList();
    foreach($list as $key => $value){
        $li[$key] = $value;
    }
    // print_r($li);

Output :

[AF] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Afghanistan
            [translatedMarkup:protected] => Afghanistan
            [options:protected] => Array
                (
                )

How can I fetch String value from the above structure?

To fetch the string value from the translatable markup object use type casting:

$li[$key] = (string) $value;


Is there a drush command to set permissions to true on ALL modules for administrator? I'm getting tired of having to go in the backend and click on some new module's permissions so that I can use them...

Is there a drush command to enable permissions to true on ALL modules in on shot?

This happens on some modules and also when creating content types or using beans or new panels.

You need to look this Permissions API

$ drush help perm-grant
Grant permissions to a role.

Examples:
drush perm-grant --roles="Admin"          Grant all permissions provided by the Node module to the Admin role.
--modules="node"
drush perm-grant --all-modules            Grant all permissions to Admin role.
--roles-="Admin"
drush perm-grant --roles="Editor,Copy     Grant "administer nodes" to Editor and Copy Editor roles.
Editor" --permissions="administer nodes"
drush perm-grant --all-roles              Grant "administer nodes" permission to all roles.
--permissions="administer nodes"

Options:
--all-roles                               Grant the permissions to all defined roles.
--roles                                   Comma-separated list of roles to grant permissions to.
--permissions                             Comma-separated list of permissions to grant to a role or roles.
--modules                                 Comma-separated list of modules providing permissions to grant.
--all-modules                             Grant all defined permissions to a role or roles.

$ drush help perm-revoke
Revoke permissions from a role.

Examples:
drush perm-revoke --roles="Admin"         Revoke all permissions provided by the Node module from the Admin role.
--modules="node"
drush perm-revoke --all-modules           Revoke all permissions from the Admin role.
--roles-="Admin"
drush perm-revoke --roles="Editor,Copy    Revoke "administer nodes" from the Editor and Copy Editor roles.
Editor" --permissions="administer nodes"
drush perm-revoke --all-roles             Revoke "administer nodes" permission from all roles.
--permissions="administer nodes"
drush perm-revoke --reset                 Revoke all permissions from all roles.  Requires confirmation, use with
                                           caution.

Options:
--all-roles                               Revoke the permissions from all defined roles.
--roles                                   Comma-separated list of roles to revoke permissions from.
--permissions                             Comma-separated list of permissions to revoke from a role or roles.
--modules                                 Comma-separated list of modules providing permissions to revoke.
--all-modules                             Revoke all defined permissions from a role or roles.
--reset                                   Revoke all defined permissions from all roles.  Requires confirmation,
                                           use with caution.


View of users flagged by a user, users flagging a user, and nodes from users flagged by a user I have a user flag that is pretty much like a "follow" or "subscribe" function.

Basically I want to create 3 views for my website's user profile pages:

  A list of users flagged by a user (e.g. a "people i'm following" block)
  A list of users flagging a user (e.g. a "my fans" or "my followers" block)
  A list of nodes from all the users that have been flagged by a user (i.e. a news feed function for a user to view all the new content
  from the users he/she flagged)

Would appreciate any help or comments!

Better late than never, To get your followers of fans you can:

create a view of type users.
create a relationship Flags: User's flaggings.
now this is were most people go wrong you should remove "Include only users who have flagged content."
chose your flag.
Add Contextual filter "Flags: Content ID".
make sure to use the relationship.
WHEN THE FILTER VALUE IS NOT AVAILABLE provide default value of "user Id from logged in user".


Drupal Views Inject Content I have a View setup in Drupal that is a list of products. Each product has an associated location and all of the locations in a view are displayed in a map that is on the bottom of the page.

What I'd like to do is to bring the map "INTO" the view so that it works better with the flow of the page. Here's the layout:

Table

 col col map map
 col col map map
 col col col col
 col col col col

What would be the best way of integrating the map with the table?

You can use Gmap. There is also a great screen cast that shows how to use it. You can also take a look into the OpenLayers module to add maps into nodes.


how do robots find node urls I appear to be getting quite heavily crawled by robots that are seeing urls like

?q=node/668

1) how are robot's able to find these urls?

The robots are referring too are not google or popular search engines. Are there anyway apart from robots.txt to defend against these. The amount of traffic i'm getting is quite intense.

I'm using drupal 7

Robots can find urls by following links either on-site or offsite.

You could use a link scanner as suggested by Clive, or look in google analytics to see where referrals are coming from to see if you have a lot of inbound links.

Alternatively, if a robot has figured out (or guessed) that your site is Drupal based then it's a pretty simple matter to start trying ?q=node/1, ?q=node/2, etc... and see what you don't get a 404 from.

I'd say a likely reason that the robot is using "?q=blah" instead of just "blah" is because the former will always work whereas the latter requires you to have clean URLs configured.

As well as robots.txt there are free services like Cloud Flare http://www.cloudflare.com/ that attempt to filter known-malicious bots for you before they can access your server.

You could also add rel="nofollow" to links on you're site that you're suspicious might be generating the traffic, which tells crawlers to not follow that link. Be careful with this as it also stops search engines, meaning it can harm your SEO if used unwisely.


Does get_defined_vars() show variables defined in variable_set()? I'm using Drupal 6, and I'm having problems retrieving a set of variables I set with variable_set() using variable_get(). I'm doing a dpr(get_defined_vars()) to see what's defined, and I don't see my variables; I see only the arrays $form and $form_state (this is inside hook_submit()).

Does get_defined_vars() show all the variables defined via variable_get()/variable_set()? I would just like to see a list of all of them. I just need to see if they've been set correctly, and troubleshoot why I can't retrieve them.

get_defined_vars is a PHP function, not a Drupal function.  It basically shows you all variables that are in scope.

Drupal variables set by variable_set are not automatically within scope.

Variables are stored in global $conf; but I don't recall if non-variables are also stored here.

If you install the Devel Module there is a page for viewing and editing variables.

EDIT:

Curiosity got to me.  The variable editor in the Devel Module queries the {variable} table and not global $conf; to build the form of all available variables, so that suggests that is the proper way to do it.


How to change the condition operator in the search api query? I have a date field facet filter on my search api views page.

When I select a date in the filter, the search api display those results which has that date value selected in the date field.

I want to display those results which has a date value which is greater than or equal to the selected in the date facet filter.

Is it possible? I checked with the search api query alter hook but I can't see any helpful function to alter the condition.

I have overridden these classes in my custom module

Drupal\facets\Plugin\facets\query_type\SearchApiDate;
Drupal\facets\QueryType\QueryTypeRangeBase;

And then modified this function

public function execute()

of QueryTypeRangeBase and used the correct operator.


Nexus theme slider is not showing up when logged out I gradually found that if I comments the following code in custom. css, it shows up.

Any clue what is wrong here.. Any help is appreciated

I faced the same issue, and realised the issues in custom.js
I commented the following code in custom.css and slider showed up

 /* jQuery('#main-menu > nav > ul').mobileMenu({
    prependTo:'.mobilenavi',
    groupPageText: Drupal.t('Main'),
    topOptionText: Drupal.t('Select a page')
  });*/

Yes, it is because your custom.js is causing conflict with the slider.

You need to use the proper synthax for jQuery.

As mentioned in Working with JavaScript and jQuery

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $('#main-menu > nav > ul').mobileMenu({
    prependTo:'.mobilenavi',
    groupPageText: Drupal.t('Main'),
    topOptionText: Drupal.t('Select a page')
    //code ends

  }
};
})(jQuery);


How remove DIV elements in rendered search form in theme designing the rendered search form result in drupal 6 is

<form id="search-theme-form" method="post" accept-charset="UTF-8" action="/drupalcms626/%40q%3Dcontact">

        Search this site:
        <input type="text" class="form-text" title="Enter the terms you wish to search for." value="" size="15" id="edit-search-theme-form-1" name="search_theme_form" maxlength="128">

    <input type="submit" class="form-submit" value="Search" id="edit-submit" name="op">
    <input type="hidden" value="form-40ac94eba9b49795082bf8daf59eae58" id="form-40ac94eba9b49795082bf8daf59eae58" name="form_build_id">
    <input type="hidden" value="e030363baad8b89de124a2d09bcbeaa7" id="edit-search-theme-form-form-token" name="form_token">
    <input type="hidden" value="search_theme_form" id="edit-search-theme-form" name="form_id">

</form>

=======================================
Now I want to remove all DIV tags in rendered result.

I mean

 1.

 2.

 3.

 4.

elements

anybody knows how can I do this via theme functions in template.php or page.tpl.php or modifying other *.tpl.php files.

Please help me.

There are two theme functions you need to override:

theme_form(), in which the wrapping
 is hard-coded with this line:

return '<form' . drupal_attributes($element['#attributes']) . '>
' . $element['#children'] . '
</form>';

theme_form_element() which contains all of the extra
s you're trying to get rid of.

The latter is quite a long function so there may well be some duplication, but I don't know how else you would do this.


correct the url context When using $link = $_SERVER['QUERY_STRING']; in page.tpl.php the result of print is:
f1=All&f2%5Bvalue%5D%5Byear%5D=2009&f2%5Bvalue%5D%5Bmonth%5D=1
Is there a way to correct the url to print as:
f1=All&f2[value][year]=2009&f2[value][month]=1
Thanks.

You just need to decode the string with urldecode():

$query_string = urldecode($_SERVER['QUERY_STRING']);


Optionally redirect a content to another url? I'm using drupal 7.  I have a content type called News Item.   On my home page, I have a block+view that lists the most recent news items.  What is shown is the title of the news item, a brief description, and a read more link to the news item.   When a person clicks on the read more link, it takes them to a page that displays the entire news item.

I want the ability to specify a redirect on some news items.  If a news item has a redirect, whenever a person clicks on the read more link in the home page, they will be redirected to a different url, NOT the url of the actual news item.  And if a person types in the url of the actual news item, they will be redirected to the different url instead.

How do I implement this kind of functionality?

I think you could handle this in a views row level template file.

First set up a field for the redirect which is optional. Then add it to your view. Create the appropriate views row template file. In your template file print out the fields individually adding a bit of logic around the read more link:

<?php if ($fields['news_url']): ?>
  <?php print $fields['news_url']; ?>
<?php else: ?>
  <?php print $fields['readmore']; ?>
<?php endif; ?>

Obviously the field names are wrong but hopefully this gives you the idea.


Using ajaxComplete in view pagination I have (drupal 7) view where I have pagination with Ajax enabled.
When any pager item is clicked I want to perform certain thing after the view is reloaded with ajax.
I am trying the following code:

(function($){
Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {
    $(document).ajaxComplete(function( event, request, settings ) {
        console.log("Ajax Completed");
    });
   }
 };

})(jQuery);

There is no output form console.log(). What am I doing wrong ?

I found a solution here. Based on @djayp34's answer, this is how I achieved what I wanted.

Basically the idea is:
Drupal does not support adding a JS snippet through drupal_add_js() or any other function at AJAX callback. So what we are doing here is:

Step 1: We register/load that particular JS code during normal page load.
In template.php:

function MYTHEME_preprocess_html(&$vars) {
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status){
       //The JS code that needs to be called after completion of ajax
      }',
      'inline'
     );
}

Step 2: We call that JS code when we want it. Here we want it to be called during AJAX callback.

In module file.

function MYMODULE_views_ajax_data_alter(&$commands, $view){
  if($view->name == 'MY_VIEW'){
    $commands[] = array("command" => 'myFunction');
  }
}


hook_form_alter - validation function does not get called in Internet Explorer I created my own function to validate username and password from the login form, and it's working great in FF and Chrome, but does not work in IE 8 and 9.

I'm using hook_form_alter to catch the loginform and then I replace the default validation function "user_login_authenticate_validate" with "my_own_validation_function" in the $form['#validation'] array.

But for some reason the new validation function never gets called in IE, but I've verified that the default validation function is replaced by printing the $form info, and it all looks great.

I'm not really sure of where to go from here, I've spent way to much on this now ;)

Any help appreciated!

The Form API works via PHP and is executed in its entirety on the server. There really should be no question of browsers being involved in the equation. That is, unless you are doing something with JS (or CSS/anything client side) that might affect form input.

I would:

Clear all my caches.
Ensure that I'm working on the same page, site (and as the same user) in both FF and IE.
When you mention "printing the $form info", I assume that you are using the Devel module. If you aren't, you should be. Devel's dpm() function is the best way to debug these things by adding diagnostic print statements in each step - the form, the validation hook and the submit hook.


Class loader not finding form class I am trying to create a custom form in my drupal 8 instance, and I have followed a few different tutorials, but every time I try to go to the forms path I see the following error on the page:

The website encountered an unexpected error. Please try again later.

When I check my apache log, I see it came because of this error:

Uncaught PHP Exception InvalidArgumentException: "Class "Drupal\report_service_call\Form\ReportServiceCallForm" does not exist." at /var/www/html/abcnj/core/lib/Drupal/Core/DependencyInjection/ClassResolver.php line 24

I do have my ReportServiceCallForm set up at the following path under my module:

lib/Drupal/report_service_call/Form/ReportServiceCallForm.php

this is the contents of that file:

<?php
/**
 *@file
  *Contains /Drupal/report_service_call/Form/ReportServiceCallForm
  */

  namespace Drupal\report_service_call\Form;

  use Drupal\Core\Form\FormBase;
  use Drupal\Core\Form\FormStateInterface;
 /**
  *Implements Drupal form Interface
  */
 class ReportServiceCallForm extends FormBase{

 /**
  *{@inheritdoc}
  */
  public function getFormID(){
     return 'report_service_call_form';
  }
 /**
  *{@inheritdoc}
  */
public function buildForm(array $form, array &$form_state){
  $form['company_name'] = array(
    '#type'=> 'textfield',
    'title'=> $this->t('Company Name')
  );

$form['cotact_name'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Contact Name')
);

$form['current_system_type'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Current System Type')
);

$form['telephone_number'] = array(
  '#type'=> 'tel',
  'title'=> $this->t('Telephone Number')
);

$form['email'] = array(
  '#type'=> 'email',
  'title'=> $this->t('Email Address')
);

$form['service_request'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Service Request')
);

$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
    '#button_type'=>'primary',
);
return $form;
}

  /**
  *{@inheritdoc}
  */
  public function validateForm(array &$form, array &$form_state){

  }

 /**
  *{@inheritdoc}
  */
  public function submitForm(array &$form, array &$form_state){

  }
}

Also I have the contents of my routing.yml as follows:

report_service_call.form:
    path: '/Customer-Service/Report-Service-Call'
defaults:
  _title: 'Report Service Call Form'
  _form: 'Drupal\report_service_call\Form\ReportServiceCallForm'
requirements:
  _permission: 'access content'

The file needs to be located at [MODULE FOLDER]/src/Form/ReportServiceCallForm.php


In-place Views block field edits I have a Views block showing the profile of a user. I would like to make it look like so:

where there is a button next to some of the changeable fields, when clicked will make the field value a textbox, where the user can update it.

How can I achieve this with Drupal?

Config: Drupal 7, Bartik theme.

Any help is appreciated.

It is difficult to have such functionality working with views generated fields. Solutions that are close to this functionality are available but may not provide acceptable UX.

For Views you can check out Editable Views and Edit Views modules.

You can also try Quick Edit module, but you will have to give up rendering your fields w/ Views, as it doesn't support fields generated by Views now and not sure if it will.


How can I create a View utilizing the Access Log hits (Hits in last 4 weeks) When creating a View, the only statistics available are total, today, and most recent. Is there a way to utilize the Access Log statistics (Number of views in last 4 weeks by example) instead?

See here for example of how to set up the typical Statisics Hits View: https://www.ostraining.com/blog/drupal/track-hits/

But instead I want only the hit count from the Access Log (Set for 3 days in the above example, mine is set for 4 weeks) so I can restrict the counter to a larger time period than "today", but shorter than "total".

Maybe the visitors module might be a valid alternative to consider? Refer to its community docu for some more details.

Be aware: I'm the new maintainer of this module, it was unsupported until recently ...


latest zen theme make the admin drop menu failed to work I am using the zen 7.5x, however when I tried it, the dropmenu for the admin doesn't work any more.

any one know how to solve this, is this because of javascript side?

Is it possible you've confused the Drupal 7 "Toolbar" module (which is enabled by default on D7) with the behaviour of the familiar "Admin Menu" module?

If so, then you can get the behaviour you want by

Install Admin Menu module
Visit your modules page and disable "Toolbar", then enable "Admin Menu" (and if you like, "Admin Menu Toolbar"

Or, with Drush -

drush dl admin_menu && drush -y dis toolbar && drush -y en admin_menu_toolbar

(Enabling Admin Menu Toolbar style implicitly enables Admin Menu also.)


How to use CiviCRM Entity for searches with Facet API I am trying to create a faceted search on CiviCRM contacts. I have created an index using the Search API module and the Facet API module, but currently the CiviCRM contacts can only be indexed on their ids, not their names. Obviously, that ain't so useful for humans to read...

For example, config/search/search_api/index/MYINDEXNAME/fields brings up the CiviCRM contacts as a possible field, but the default value is integer, not fulltext or string.

I was suggested CiviCRM Entity as a fix for this, but I can't quite work out how it could solve the problem -- would be very grateful for any pointers, or any other ideas!

A wee bit of info here:

http://forum.civicrm.org/index.php?topic=32169.0

but seems like u'll need to dig around and help build it

lobo


Storing objects of custom type in $_SESSION - legal way? I'm trying to figure out: can I load custom class (defined in module) to be loaded before session starts and its contents processed by PHP (unserialized) - is where any legal way to do this? (without hacking Drupal core)

without it I get _PHP_Incomplete_Class if I store something of a custom type to $_SESSION variable.

I did a research:

hook_boot is not called unless page is cached in NO DB mode otherwise it's called after session is loaded
hook_init is called too late (always after session load)

Any thoughts?

actually, I have found a workaround to do so without patching the core.

it is simple.

Drupal 7 core includes all module files which have hook_boot() registred, prior to open session, but hook_boot() is called only then session is started.

What you need to do - is to manually include class declaration outside of a hook_boot() (in a root context of a file containing hook_boot() of your module).

Such code is immediately executed as file being included by Drupal Core (prior to session_start() call), which gives us the desired behavior - we now can store objects of a CustomClass in $_SESSION variable and they wont become corrupted on next page load.

but be carefull if your CustomClass is extending from AnotherCustomClass located in different module and loaded by same mechanics (as described above) - you cannot be sure in order file loads.
This can lead to fatal runtime error: Undefined class


Media player for Drupal 7 that can play remote http-accessible files I'm looking for a simple module for Drupal 7 to be able to have an embedded player that can play files that are stored on a different server and that is accessible via this URL:

http://[servername]/WebPlay/MCWS/v1/File/GetFile?File=[FileID]

(where [servername] is not a drupal site)

I think that file formats may vary, but should be the common ones (mkv, avi or flv containers).

Ideally the player should be able to play remote audio and locally (i.e. inside drupal) stored audio\video as well.

Note that the URL to be played (the one above) is stored in Drupal in a Token Field, but if needed by the player I can try and store it in a different field type.

Can anyone help me? None of the players I can find on drupal.org for D7 have documentation on how to do what I need and to me is not even clear if those players can do it (let alone how).

I tried the MediaElement + Link combo (putting the URL in the link field), but there's an issue with query parametesr in URLs being stripped, so it's not working.
The say the issue is fixed, but I tested it with MediaElement latest version (7.x-1.2) and it's still there.

If this were me; I'd be using a media-compatible media player (such as MediaElement with the 2.x branch of Media) and using remote stream wrapper to allow me to place the remote URL into the media field: https://drupal.org/project/remote_stream_wrapper

This should let you use local media or remote media that the media player can play, and will keep things tidy for you to manage.

/Robin


How to programmatically add custom markup to every displayed user name Drupal 8.x

I am currently using hook_preprocess_user().

I would like to alter the username to add some custom markup to every username.

MYMODULE.module:

function MYMODULE_preprocess_user(&$variables) {
  $variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}

This returns Name Hello Hello. Concatenation adds 'Hello' twice so this approach is not working.

I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.

How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.

Seems hook_user_format_name_alter() is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.

The following won't work for Views for example. It will print just a string.

use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Implements hook_user_format_name_alter().
 */
function MYMODULE_user_format_name_alter(&$name, $account) {

  $name = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $name = $variables['title']['#markup']->__toString();
    $variables['title'] = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
  }
}

So, what I'd recommend now is, you maybe take the *_preprocess_page_title hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.


How do I create a user relationship to show author name in Views? I want to show node title and it's author but I'm not able to find how to show the author name. I don't see Content:Author in Relationship.

How do I configure Views to show it?

In Drupal 6 you don't need a relationship for the author name of a node, it is directly available in the fields' list.


How do I load classes using the ctools plugin class loader? Perhaps, the question should be how do I implement ctools plugins using classes to extend different types of an object? I can't find a simple explanation.

mymodule.module:

<?php
/**
 * Implements hook_ctools_plugin_api().
 */
function mymodule_ctools_plugin_api() {
    list($module, $api) = func_get_args();

    if ($module == 'mymodule' && ($api == 'plugins')) {
        return array('version' => 1.0);
    }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function mymodule_ctools_plugin_type() {
    return array(
        'plugin_type' => array(
            'classes' => array('handler'),
        ),
    );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($owner, $plugin_type) {
    if ($owner == 'mymodule') {
        return "plugins/$plugin_type";
    }
}

plugins/plugin_type/example.inc:

<?php
$plugin = array(
    'title' => t('Example'),
    'handler' => array(
        'class' => 'ExamplePlugin',
    ),
);

plugins/plugin_type/ExamplePlugin.class.inc:

<?php
class ExamplePlugin {
function __construct($plugin){

}
}

Anywhere:

<?php
// Get all available plugins
$plugins = ctools_get_plugins('mymodule', 'plugin_type');

// Load a specific plugin
ctools_include('plugins');
$plugin = ctools_get_plugins('mymodule', 'plugin_type', 'example');
$class_name = ctools_plugin_get_class($plugin, 'handler');
$example = new ExamplePlugin($plugin);


Add cache context to altered links I am using hook_link_alter(&$variables) to alter links depending on the user's role. I'm doing this for links in the main menu as well as for custom links shown on entities. This works good except caching.
If I change a user's role still the previous behaviour of the altered links is shown. If I clear all caches, it works fine again.

I thought of adding cache context user.roles. But hook_link_alter seems not to support to add caching meta data to $variables see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_link_alter/8.5.x. (Or I'm doing it wrong.)

What can I do to make caching of my altered links aware of the user's roles?

My code looks like in hook_link_alter(&$variables)

$roles = \Drupal::currentUser()->getRoles();

if(!in_array('member_gold', $roles)) {

  $url = $variables['url'];

  if (($url->isRouted() && $url->getRouteName() === 'view.my_content.page') OR ... ) {

    $url = Url::fromRoute('myModule.ajax_callback', ['op' => 'do_action']);
    $token = \Drupal::service('csrf_token')->get($url->getInternalPath());

    $variables['url'] = $url;
    $variables['options']['query']['token'] = $token;
    $variables['options']['attributes']['class'][] = 'use-ajax';

  }

}

Update:

The links that I alter are in a) the main menu, b) in pseudo fields and c) by other modules. I succeeded adding some cache context to a) and b) and skipped c). It seems to work, but I don't know why, it was more or less trial and error:

For the menu links:
    function mymodule_preprocess_menu(&$variables) {

if(isset($variables['menu_name']) && $variables['menu_name'] == 'main') {

  $variables['#cache']['contexts'][] = 'user.roles';
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($variables, \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()));
}

In my pseudo fields:

$build['action_my_action'] = [
    ...
    '#cache' => [
      'contexts' => ['user.roles'],
    ],
  ];

  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($build, \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()));

I don't understand why this works. I initially only tried adding the cache context, but this did not work. Only if I add the dependency to the current user. However I don't know whether this is correct, as I don't want to vary by user but by role.

Would be great if someone can explain me if this is right and why it works?

Since you can't have the role sensitivity reliably in the links themselves, I'd tackle this differently by using an intermediary routing function.

So if you have a link you want to point to mypath/role_1, mypath/role_2 etc, you might point it to role_route/somekey defined in mymodule.routing.yml like so:

mymodule.role_route:
 path: 'role_route/{key}'
 defaults:
  _controller: '\Drupal\mymodule\Controller\RoleRouteController::route'
 requirements:
   _permission: 'access role paths'

The route function of the controller might be something like:

function route($key) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  // logic to process roles and key to get wanted route
  ...
  $role_route_name = ... ;
  return new RedirectResponse( Url::fromRoute($role_route_name);
}


rewrite with nginx conf result 502 bad gateway My code is based on http://wiki.nginx.org/Drupal and the result is 502 bad gateway. I have tried so many ways but dont work.... how  i can solve this? thanks

server {
        listen 8093;
        server_name localhost;
        root /home/ITEP;

        # Enable compression, this will help if you have for instance advagg module
        # by serving Gzip versions of the files.
        #gzip_static on;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # This matters if you use drush prior to 5.x
        # After 5.x backups are stored outside the Drupal install.
        #location = /backup {
        #        deny all;
        #}

        # Very rarely should these ever be accessed outside of your lan
        location ~* \.(txt|log)$ {
                allow 192.168.0.0/16;
                deny all;
        }

        location ~ \..*/.*\.php$ {
                return 403;
        }

        # No no for private
        location ~ ^/sites/.*/private/ {
                return 403;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
                return 403;
        }

        location / {
                # This is cool because no php is touched for static content
                try_files $uri @rewrite;
        }

        location @rewrite {
                # You have 2 options here
                # For D7 and above:
                # Clean URLs are handled in drupal_environment_initialize().
                rewrite ^ /index.php;
                # For Drupal 6 and bwlow:
                # Some modules enforce no slash (/) at the end of the URL
                # Else this rewrite block wouldn't be needed (GlobalRedirect)
                #rewrite ^/(.*)$ /index.php?q=$1;
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                fastcgi_intercept_errors on;
                fastcgi_pass unix:/tmp/phpfpm.sock;
        }

        # Fighting with Styles? This little gem is amazing.
        # This is for D6
        #location ~ ^/sites/.*/files/imagecache/ {
        # This is for D7 and D8
        location ~ ^/sites/.*/files/styles/ {
                try_files $uri @rewrite;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

I'm using drupal 7.... fresh install

The location of file phpfpm.sock may vary depending on Operating System:

Try find the phpfpm.sock file on your server:

find / -name php*fpm.sock

and then change the following line

fastcgi_pass unix:/tmp/phpfpm.sock;

to reference phpfpm.sock from the correct location.

Example (Ubuntu 14):

fastcgi_pass unix:/var/run/php5-fpm.sock;


How to trim a field that's been excluded from display? In Views, in order to group certain fields inside a common div, i excluded them from display and inserted them in a global text field by using their 'replacement pattern references'.

Here's what the div looks like :

[title]

[name] - [created]

More details &raquo;

The thing is i wanted to trim the node title to 50 characters max.
Trimming works fine when displaying the field 'as is' but not when it's been used as a replacement pattern in a different field.

Any help on how to achieve this ?

Thanks

I've double checked your problem and it seems to works like a charm.

In your view go to Field -> Title -> [edit] -> Rewrite results -> Trim this field to a maximum length -> set maximum length to 50

Add Global: Custom text field and place [title] in text field.

Result should looks like this:


How to create an entity-reference field programmatically? I'd like to know how to create an entity-reference field programmatically, and where should I put this script.
Could I call field_create_instance() in hook_form_alter()?

Could I call field_create_instance() in hook_form_alter()?

field_create_instance() is normally called in hook_install(), or hook_enable() from a module, or an installation profile.

You don't call it in hook_form_alter(), especially if the hook is altering the node edit form: Fields are attached to bundles (content types), not to single nodes. When a node is created, its content type is already created, and any field that content type requires is created before its nodes are created.
If there is a setting form that allows users to decide which fields to attach to a content type, then field_create_instance() is called in its submission callback.

A call to field_create_instance() is normally coupled with a call to field_create_field(). To be sure the field doesn't exist, you should first call field_info_field(). It returns NULL when the field doesn't exists.


No route found for custom REST resource I'm trying to create a custom REST GET resource for a specific node type, and I have the class created and enabled via the REST UI module settings (using the current 1.x-dev release so configs are generated w/o me having to manually create a routing.yml file). For reference, here's the class code:

<?php
/**
 * @file
 * Custom Rest resource for video nodes.
 */

namespace Drupal\video_export\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "video_export_source",
 *   label = @Translation("Video Export Source"),
 *   uri_paths = {
 *     "canonical" = "/videos/feed/{site}"
 *   }
 * )
 */

class VideoExportResource extends ResourceBase {
  /**
   *  A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
    * @param array $configuration
    *   A configuration array containing information about the plugin instance.
    * @param string $plugin_id
    *   The plugin_id for the plugin instance.
    * @param mixed $plugin_definition
    *   The plugin implementation definition.
    * @param array $serializer_formats
    *   The available serialization formats.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
    *   A current user instance.
  */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
    * Responds to GET requests.
    *
    * Returns a list of video nodes to be imported into the target site.
    *
    * @return \Drupal\rest\ResourceResponse
    *   The response containing a list of bundle names.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
  public function get($site = NULL) {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

However, when I access my URL via http://mysite/videos/feed/sourcesite?_format=xml, all I get is this error:

  No route found for "GET /videos/feed/newsbusters"

and my debugger doesn't even hit my get() function. In reading the RESTful Web Services API overview docs it appears that I might be missing the second part of the uri_paths setting in the class annotation. However, the example doesn't make sense to me for my use. if the canonical url is just /videos/export/{site} (where {site} is a parameter), what is the correct second part? Just http://myite.com/videos/export?

Or,

Thanks.

As far as I can see, the REST UI module is just thought to change the content of the YAML files for the REST resources. It is up to the module correctly define the URL to use.

In your case, the annotation of the class should contains:

 uri_paths = {
   "canonical" = "/videos/feed/{site}",
   "https://www.drupal.org/link-relations/create" = "/videos/feed"
 }

I am not sure the placeholder makes any difference, but all the examples use {id}.


Profile 2 Not showing fields on user edit page I install Profile 2 module and create separate registration page.
after login with this user
not showing that fields on edit user page
Can any one help me in this

Give the permission "[PROFILETYPE]Edit own profile" under "Profile2" section to the respective user roles.

And the fields will be appeared on edit user page.


Get Last Node Access Timestamp Per Node by User Drupal 8.x

I am trying to compare the current users last access timestamp to other timestamp values and am wondering how to get the current users "last_access" in HOOK_preprocess_node().

MYMODULE.module:

function MYMODULE_preprocess_node(&$variables) {
  kpr(\Drupal::currentUser()->getLastAccessedTime());
}

This returns a timestamp, however, it updates quite infrequently and not on node load, or even after cache clear, and does not seem node specific.

I've accessed this value in HOOK_preprocess_user() with $variables['elements']['#user']->access->value, however, I would like the same value available in node.

How do you get the timestamp of the user's last view of a node per node?

This doesn't work because the node is cached. Disabling caching of the node wouldn't be a good idea, performance-wise. Try instead a lazy builder to retrieve the access time and create a placeholder, so that the node can be cached, no matter how often the access time is updated:
/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mymodule_preprocess_node(&$variables) {
  $variables['content']['timestamp'] = [
    '#lazy_builder' => ['mymodule_timestamp_current_user', []],
    '#create_placeholder' => TRUE,
  ];
}

/**
 * #lazy_builder callback; builds timestamp markup with current user access time.
 */
function mymodule_timestamp_current_user() {
  $timestamp = \Drupal::currentUser()->getLastAccessedTime();
  return [
    '#markup' => $timestamp,
    '#cache' => ['max-age' => 0],
  ];
}

Drupal ^9: The callback needs to be in a class implementing TrustedCallbackInterface or RenderCallbackInterface. See https://drupal.stackexchange.com/a/303039/47547 for a code example.

Statistics
This code extends the code you had so far. If you are referring to statistical node view data have a look at the core Statistics module, which provides a timestamp when the node was last viewed. However, not on a per user basis, but this gives you an idea how you can record such statistical data.


How do print the query which is built using search api I have created a view using search api now i just want to print my query.But when i used hook_views_pre_execute(){
   dpq($view->build_info['query']);
}
it does not show my query.

Enable Views query preview in Views Settings (admin/structure/views/settings) by checking the box "Show SQL query".

Then you will be able to see the query created by your view while you constructing it.


What is the latest drush version and how do I install it? I have drush installed using what in principle is the latest stable build as per the instructions. When I run drush version then i get the reply 8.0.3, however on my workstation with Dev Desktop installed it tells me it's 8.0.5.

Running drush dl drush proposes a version 8.x-6.x-dev dated 30 September 2013 which seems very old, and I can see no sign of a v8.1

Looking at the documentation I have not been able to see any other indications of how to go about this, and I am confused. Can anyone tell me whether the drush dl drush is still valid and what the current latest version actually is?

drush dl was never supposed to be used to download Drush. It happens to work because Drush is hosted on drupal.org as module, but the latest development are done on github.com. On drupal.org, you find just old versions, dated 2013.

As per July 17, 2016, the latest version is 8.1.2. You can install it using Composer, if you are using any Linux OS, or OS X, and in this case it is easy as running the following command:

composer global require drush/drush:~8

Don't forget to add ~/.composer/vendor/bin to your shell PATH variable, or the shell will not find Drush's executable.