views argument to header I have a Search view that uses the Filter: Search terms.

I've tried using <?php print arg(0); ?> in the header, but that only returns the view url (search).

How do I get the value of the query key /search?keys=term to be able to use it as a token in a Global: Text area in the Header?

My header title would be something like : Results for [search term]

$_GET['keys'] should give you the term value.


unique fivestar rating for each user I have a fivestar rating field "field_rate" in comments. I have only allowed a role "reviewer" to rate. if one reviewer say A sign in and rate the field the average is stored as stars. Now if another reviewer say B visits the same node, he can see the vote (overall avg of number of votes). I want that reviewers will not able to see each other rating so when reviewer B signs in he see only blank 5 stars instead of avg votes. At the same time i want editor role to view the average vote for that field. How can i achieve this?

I have found a solution, its so simple. Just have to tweak display setting for the rate field in managed display to "user's vote". Enable permission to vote for reviewer only.

For editor, I have used hook_node_view and displayed average rating. Since editor has no permission to vote, he can only see the average votes on the field in the node view. While reviewer can see his vote as per display setting.


Computed field - count number of taxonomy terms in term reference field So I simply want to count the number of tags on a term reference field.. I've tried a count (below) and it simply returns "1" (there are a lot more terms tagged than 1):

$entity_field[0]['value'] = count($entity->field_termref);

Also something like below does not work either and also returns "1" - I'm thinking I have to loop through the multiple tags somehow but I'm not sure how to do it. Thanks a lot for any help.

$myterms = array();
foreach($entity->field_guests as $tmp) {
  $myterms[] = $tmp_field_term;
}
$entity_field[0]['value'] = count($myterms);

Your first code was correct as far as it went: count($entity->field_termref) will return a count of one because the array has only one item, the list of terms.

To count the members of the list your will need to drop down into the array to actually count the list:

$entity_field[0]['value'] = count($entity->field_termref[LANGUAGE_NONE]);

The members of the list can then be counted:

$entity->field_termref[LANGUAGE_NONE][0]
$entity->field_termref[LANGUAGE_NONE][1]
$entity->field_termref[LANGUAGE_NONE][2]
...etc


How to save file with custom form? I try to use that script in my Drupal site https://tutorialzine.com/2013/05/mini-ajax-file-upload-form

I did not use drupal form api. I used my html same with that script.

I created 2 pages with hook_menu.

On first page I use that script to upload files.
That script sends files via ajax to 2. page. But I could not save files as managed file.

On second page I save datas as json to logs to see what i get in that file.
That is an example json;

 {"name":"aa.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpWkCoI6","error":0,"size":8575}

How can I save files as managed file on second page?

I solved like that

$file_name = $file['name'];
$file_get = file_get_contents($file['tmp_name']);
$new_file = file_save_data($file_get, 'public://images/'.$file_name);


How to programatically hide node field on viewing? Using Drupal 9,
How do I hide a node field when viewing it?
Let's say I have field info. I would like to conditionally not display the label or the value.
I assume I use hook_node_view_alter but I'm not familiar with how to manipulate the build render array.
Thanks!

You could make use of the hook_preprocess. If its on the specific entity such as the case of a paragraph it will look something like this where I am hiding some labels from a view based on some condition:
function [MODULE_NAME]_preprocess_paragraph(&$variables){
    $paragraph = $variables['paragraph'];
    // Get the parent bundle.
    $parentBundle = $paragraph->getParentEntity()->bundle();
    //check View type
    if ($parentBundle && $parentBundle == 'category_views') {
      if ($variables['content']['field_language_name']['#object']->get('field_language_name')->value != 'English') {
       //Removing labels
        unset($variables['content']['field_language_name']);
        unset($variables['content']['field_language']);
      }
    }
}


Autofill billing Information on checkout page in Drupal Commerce I need to autofill the billing information on checkout with Drupal commerce.

I added to drupal user a field called 'field_commerce_billing' like a reference to 'Customer profile' entity and I want to autofill the checkout with the customer profile fields values if an user is logged in.

This code works for me.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'commerce_checkout_form_checkout' && $user->uid) {
    $user = user_load($user->uid);
    $loaded_billing = commerce_customer_profile_load($user->field_commerce['und'][0]['profile_id']);

    // For each field in customer profile, fill the form field with the $user value.
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address'] = $loaded_billing->commerce_customer_address['und'][0];
    $form['customer_profile_billing']['field_telephone_number']['und'][0]['value']['#default_value'] = $loaded_billing->field_telephone_number['und'][0]['value'];
  }
}

I tried to retrieve the commerce_customer_profile field list, but I didn't find a way to generalize an action for filling every field type in the form.


Drupal 7 how to use item menu as MENU_LOCAL_TASK and MENU_NORMAL_ITEM simultaneous? I have hook_menu with 3 pages they are defined by default as MENU_NORMAL_ITEMs and I see them from in main menu:

$items['accounting'] = [
    'title' => 'Accounting',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'weight' => 10,
  ];

  $items['accounting/extras'] = [
    'title'   => 'Extras',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'weight'  => 0,
    'menu_name' => 'main-menu',
  ];

  $items['accounting/report'] = [
    'title'            => 'Report',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'report'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 1,
    'menu_name'        => 'main-menu',
  ];

  $items['accounting/transfer'] = [
    'title'            => 'Internal transactions',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'transfer'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 2,
    'menu_name'        => 'main-menu',
  ];

But I also need to see them as MENU_LOCAL_TASK and if I add type = MENU_LOCAL_TASK then they disappear from menu and appear as local tasks

What to do to see them in both places? Thank you.

You can use a bitwise operator for that, e.g.

MENU_LOCAL_TASK | MENU_NORMAL_ITEM

There's a real-world example in the core comment module (comment_menu()):

$items['admin/content/comment'] = array(
  'title' => 'Comments',
  'description' => 'List and edit site comments and the comment approval queue.',
  'page callback' => 'comment_admin',
  'access arguments' => array('administer comments'),
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'file' => 'comment.admin.inc',
);


How can I have an URI with two GET? I wrote my custom rest endpoint. I need to 2 URI both called with GET

/api/item/{id} to get single item identified by ID
/api/item to get the list of items.

i try with

  @RestResource(
    id = "my_id",
    label = @Translation("My label"),
    uri_paths = {
      "canonical" = "/api/item",
      "https://www.drupal.org/link-relations/index" = "/api/item/{id}",
    }

into my class i have

class ApiRestResource extends ResourceBase {

    public function get($id = NULL) {

but only canonical URI is found. the message for the second URI is

"message": "No route found for \"GET /api/item/1\""

how can i have 2 GET in my class?
thanks in advance

you can create two resource files, one that receives the parameter and another that does not.

Example:

  demo_rest_api.info.yml.

name: Demo REST API
description: Define's a custom REST Resource
package: Custom
type: module
core: 8.x

  /src/Plugin/rest/resource/DemoResource.php

<?php

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/item"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {

      $response = ['message' => 'Hello, this is a rest service:'];

    return new ResourceResponse($response);

  }
}

  /src/Plugin/rest/resource/DemoResource_item_id.php

<?php

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "DemoResource_item_id",
 *   label = @Translation("Demo Resource item id"),
 *   uri_paths = {
 *     "canonical" = "/api/item/{id}"
 *   }
 * )
 */
class DemoResource_item_id extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get($id= null) {

      $response = ['message' => 'Hello, this is a rest service and parameter is: '.$id];

    return new ResourceResponse($response);

  }
}


How do I the add vocabulary name or the ID to the  CSS classes? For theming purpose, I would like to add in body class the vocabulary name (or ID) of the current taxonomy.
I know how to add a class based on the taxonomy term ID.

For example, I have the following vocabulary (Color).

red (term id = 1)
green (term id = 2)
yellow (term id = 3)

I know how to get <body class="term-id-1">. I would like to get <body class="vocabulary-id-1"> or <body class="vocabulary-name-color">.

I've tried the following code.

function mytheme_preprocess_html(&$variables) {
  // Works
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['term_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  }
  // doesn't work
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_vocabulary.canonical') {
    $variables['vocabulary_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_vocabulary');
  }
}

As said in the comments, it doesn't work, and I am not able to use the vocabulary name, or its ID as CSS class to add to the <body> tag.

How can I achieve this?

The vocabulary id is not a route parameter, unless you have a route to view/edit a vocabulary, but these are all admin routes. So you need to get the information from the term:

function mytheme_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    // load the term entity and get the data from there
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term_id'] = $term->id();
    $variables['vocabulary_id'] = $term->bundle();
  }
}

bundle() returns the vocabulary of the term. This is the same as a content type of a node. Or a block type of a custom block. All are fieldable bundles of entities.

So if you use bundle() on a node you'll get for example the machine name article.


"Call to undefined function views_get_view()" error What do I need to load before calling views_get_view()?

I'd say you just need to have Views module enabled to have this function globally available. You enable/disable modules at /admin/modules.


MSSql or SQL Server Wrapper for custom module? I'm writing a custom module and I need to access data that is currently stored in an MSSql database. It would be great if I could use the built-in database abstraction layer, but obviously that isn't possible.

Are there any modules or resources that provide a similar abstraction layer for MSSql?

If not, how would I go about writing my own? I feel very badly about just putting the connection and query strings directly in the module, it seems so.. antiquated.

Since you didn't specify a Drupal version, I'll try to answer for both Drupal 6 and 7.

Drupal 7

See http://drupal.org/project/sqlsrv

Drupal 6

Even if there would be SQL Server integration in the official db-api, it wouldn't help you much because with Drupal 6, you can only connect to multiple databases of the same type. This is why https://github.com/dereine/views_pgsql was created for example.

However, it might be an option to use the DBTNG project, which is a backport of the new Drupal 7 database abstraction layer and use that in combination with the sqlsrv project. I haven't tested that but it could work. And if not, maybe with a few changes (which you could contribute back)


Rules schedule force actions In Drupal I've scheduled, on the future, some e-mail, using rules schedule module. Now I want to force the delivery, before the scheduled time, to check the text of e-mail.
Is this is possible?

Yes, you can do it by clicking the execute link in your components tab.

OR, you can click the schedule link and schedule something to run 1 min from now. Just remember that your scheduled action will only run after cron runs. So if you have set cron to run once a day or every 1 hour, it won't happen until then. So will have to manually run cron, by clicking the run cron button to see if it gets delivered after 1 min from now.


Accesing blocks from the server via FTP So I created a custom block and put the block on every page but unfortunately the block causes a white screen... I can't login to change the block because the block is on every page, as I mentioned.
Is it possible using an FTP program to access blocks via the server and delete/change them?

First of all, blocks are stored in the Database, not in your web directory. Therefore, FTP is useless here.

If the custom block was created using a custom module, simply disable the module.

If the custom block was created using the Drupal User Interface, you can disable your custom block by changing the status from 1 to 0 or edit the block body by login in into your Database using PHPMyAdmin and finding the correct block table.


Drush rsync command failed: No such file or directory I am new to use Drush.

this following is my .drushrc.php file

$aliases['server'] = array (
  'remote-host' => '162.243.78.240',
  'remote-user' => 'root',
);
$aliases["dxb"] = array (
  '#name' => 'dxb',
  'root' => '/var/www/dev/daxuebao',
);

I try to use this following command to sync local site to remote site

$ drush rsync @self @dxb

But it alert me:

rsync: mkdir "/var/www/dev/daxuebao" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at /SourceCache/rsync/rsync-42/rsync/main.c(544) [receiver=2.6.9]
rsync: connection unexpectedly closed (8 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /SourceCache/rsync/rsync-42/rsync/io.c(452) [sender=2.6.9]
Could not rsync from /Users/tangmonk/Sites/drupal/daxuebao// to      [error]
/var/www/dev/daxuebao/

It seems directory /var/www/dev/daxuebao do not exist, so I try to mkdir to my server :

$ mkdir /var/www/dev/daxuebao

The I type $ drush rsync @self @dxb again, But still above problem.
How to solved it?

Make sure the string containing the directory does not have extra blank spaces at the end. Trim it if possible. I was getting a similar message when I was using the option --files-from=myDirList and I have some spaces after the directory name inside the myDirList.


Conditional rewrite on views according to singular / plural I am building a website using views and the answer module.

In my view, I add "Content: Answer Count" which is the number of answers.

I want to be able to rewrite the following output:
(1 Answer)
(2 Answers)
(3 Answers)
...

I know how to output "(no answers yet)" when the count=0.
But, how can I differentiate between singular and plural and output "Answer" or Answers" according to the count?

Drupal views provides a singular/plural option, if the field value is an integer type. In your case, if its not available in Field settings try using views_php contrib module.

This module will allow you to add a field in views with php code that will executed on the fly. You can get existing values of row data inside php from $data variable. Now you can get your output based on the singular/plural in php.

But it is suggested to check the field settings properly if same option is available.


How to use feeds module to import multi-value fields? I want to import a csv file using the feed module. This feed corresponds to an article content type, but the problem is the image field in the article content type contains multiple images. If I want to use the feed module to import, I can only import one image, if I paste multiple image urls, this causes errors.

Feeds and Feeds Tamper worked for me too. To get one row for each multi-value field I used the GROUP_CONCAT() function from MySQL. I used this in conjunction with the Feeds_SQL module.


Storing data for every country for an interactive chart I need to store one and possibly more values for each and every country so that I can populate an interactive SVG world map. This data will be updated often by hand by one of the content moderators. So it should be easy to maintain by someone with basic drupal content editing knowledge.

So far I have tried:

My initial work had me use a Field Collection, in which I had a dropdown field with all the countries, and another dropdown to select which data point to use for that specific country. This works, but gets extremely memory intensive as the country goes up. It becomes exceptionally difficult to find a country as well since they are not in alphabetical order. I attempted to create each Field collection item prefilled for each country upon creating the node create form. but I would constantly run out of execution time, with it taking more then 4 minutes to get to 200 countries, and getting exponentially slower as the country count went up. Never managing to get to 250.
I then tried to use TableField, and import the data from a CSV, with one column for the iso2 code, one for the name, and one with the numerical value for the value on the chart. This was okay, but nearly always crash when trying to import an updated version of the csv. It also was difficult to ensure the integrity of the country codes and names, since anyone could easily make a inadvertant change when modify data. This would then break either the map, or the translation of the names.

So my question is, how can I go about structuring a content type, so that I can list all the countries and set a value for them which I can choose from a select list, that allows me to view the data, sorted by country, and doesn't bring the browser to a standstill?

Note: I'm using Ammaps to display the data on the front.

I did something similar sometime ago.
My svg had a path per country with each path being identified by a unique id (namely the country name camelcased). These were stored directly in the template.
I created a taxonomy with all the country ids, and a content type for the user-contributed country data, with a reference to the country-ids taxonomy.
After that I used EntityFieldQuery to get the list of country-ids with published data, so as to display them highlighted in the map.
Then on click of a country I'd retreive the country data via an AJAX request and display it besides the map using jquery.

Beyond my original implementation you could probably load all data via EntityFieldQuery and then just handle it via javascript without further requests.

Does that make sense to you ?


Saving 1 vocabulary deletes all terms of all vocabualries in the site | Data mining Since I migrated D7 to D8 I suffer from the following problem and need help regarding mining the data that could be useful to make a fine report to the Drupal community.

The story:

When you visit nodes created before migration, you can see their taxonomy terms.

If I save a node with taxonomy data that was created before migration - All its taxonomy data is vanished if its from selection box or radio buttons (if its from autocomplete, the node saves just fine, as weird as it sounds)... It happens in all nodes, and in all content types, (even new ones I create after migration whether from migrated or new content types).

A milestone in my efforts to understand why it happens is this:

When I save any taxonomy vocabulary like in the following image, all of its terms, including the terms of all other vocabularies are just suddenly deleted... Insane as it sounds --- Right after I hit "Save", all of the terms in all vocabularies in the site, just vanish.

But this deletion is only in the UI level; that is, If I go to the table containing taxonomy terms, that is taxonomy_term_field_data I can see all 30 terms that appear in all nodes.

I have consulted a Drupal programmer on this and he told me this is most certainly a migration bug, given it happens on an all-core site and there are no errors in drush ws --full.

Note:

I don't ask anyone to debug this for me; Since I learn basic programming and haven't yet learned to debug, all I am asking is what PDO data should I monitor and present in my report to the Drupal community.

I would thank you dearly for giving me any direction because I suffer from this problem very much.

You should look into the database if the taxonomy terms are deleted indeed or just have changed the tid, the language or anything else.

The most probable is the terms are not deleted but when you try to load them by some parameters the parameters has changed and the result is no terms.


Problem between Organic Groups and Articles/Pages? I am currently working within Drupal 7 and I have all of the Views and Organic Groups modules enabled. Currently when I create a new article or page on my site it appears fine on the front page of the website. Yet when I click to view/edit the article/page I am unable to see the body of the article/page even though I can see it on the front page.

When I disable the module Organic Groups Field Access I am able to see the body of the article/page at the front page, view and edit screens.

Is there some way to keep the module Organic Groups Field Access and still be able to see the body?

I had this problem too. It turns out the current 'stable' version of Organic Groups is not so stable. This along with some other annoying bugs are fixed in the development version of OG. Give that a try :-)


Code to display multiple images using .tpl.php file in drupal 7 I use the following code to render the image from the template file. This code is used when the image name is known. Multiple images can be displayed by adding the same lines of code with different image names.

global $base_path;
print "<img src='" . $base_path . path_to_theme() . "/../../../default/files/styles/thumbnail/public/xyz.jpg' width='100' height='100' />";

Is it possible to render the multiple images from the content type with the field name created but without changing anything in the template file every time we upload the image?

If you have multiple images from the content type, and you want to render them. The .tpl.php file must have $node variable and in that variable you will have the image path and image uri for each image with field name, which you want to render. Just save the image path or image uri of image in some variable and do as following:

$img_uri = <image uri path here>;
$image_url = file_create_url($img_uri);
print '';

In case your are using Image Styles then you will need to get the image's url and style name and use it like this:

$style_name = <image style name>;
$file_path = <image file path>;
$image_url = image_style_url($style_name, $path);
print '';

And I can see that are using Image Style in which your path is something like:

 /../../../default/files/styles/thumbnail/public/xyz.jpg

The rest I think that once you get different image file paths then you can easily loop them as you like.


How can I let users register for a certain node type? In Drupal 7.15, I use the Webforms module to allow guests to sign up to courses. I therefore created a content type Registration Form.

Courses themselves are individual content nodes, of the type Course.

Now, I'd like the user to be able to select a course to sign up for, and save that in the web form as well. How can I do that?

It seems that the Webform Associate module does exactly that:

  The Webform Associate module is designed to allow attaching webforms to particular node types. The example would be event registration. Event node types might need starting and ending dates, descriptions, etc. With Webform Associate a new webform node is automatically created, and the webform itself is appended to the bottom of the event node.

However it says that "Webform 3.0 Obsoletes this module and is not compatible in any way." Haven't found out how, though.

I was finally able to associate the event using the Node Registration module.

  Allows (authenticated and/or anonymous) users to register for events. Events are nodes with certain node types. You can enable registration for any node type and add fields and manage display per type and per node.

The module depends on Value is and Entity as well as Views and CTools.

What you'll have to do after installation:

Go to admin/structure/types/manage/<course>/edit, where <course> is your course
Enable registrations at the bottom under Registration Settings
Go to admin/structure/node_registration/manage/<course>/fields and add fields to your registration form, as required.
Don't forget to enable the right permissions too for anonymous users.


A way to let themes hook into modules? I'm working on a module which works as an adapter between Drupal and a framework which sends e-mails.

The framework supports inline image attachments, meaning that those images can be carried in the actual message and displayed in the recipients e-mail client without having to download those images from an external location.

I'm thinking that users of this module would be interested in having their e-mails themed so that they reflect the look and feel of the sending website. This is right now done through an 'email.tpl.php' file which the module requests the theming system to theme e-mails with.

Consider a themer/designer that works on theming e-mails. That person then figures out that it would be a good idea to have an inline image attached in  e-mails - say a logo. However, how does the designer (via theme functions) tell the module to include one or more pictures which are required by the theme?

I had hoped that my module could make a hook available which other modules and themes could implement, but it appears that only modules can implent hooks. This, at least, applies when using module_invoke_all().

My question is thus; is there a way to let any theme provide feedback to a module similar to how other modules can interact with each other via hooks?

If you want to pass data into the module, then you don't want to do it at the theme level. The theme layer should be all about output, not data. Try solving it with a fielded entity, templating through a text field with full HTML filter and  adding CSS through another field. Images could then be added with a file field.


How can I have admin language English and frontend language another? I would like to create a site to display the frontend of the site in one language and still keep the backend in English (or another language).

Is there a module like "Administration Language" or any configuration for Drupal 8?

First go to Administration - Configuration - Regional and language - Languages - Detection and selection tab and make sure to have “Account administration pages“ enabled.

Then go to People and edit your user. Go down to the Language settings section. You should now see a Administration pages language dropdown. Select and save.


How to ensure CiviCRM checksum / cid are valid in custom Drupal module Follow up to an earlier question:

I am writing a simple custom Drupal module to display information about a contact's related organizations (see above for more background if interested).

One use case is that a logged in user sees this info, in which case determining whether to show the info is easy (I just use the Drupal contact ID to pull information from CiviCRM).

However, if someone visits the page from a checksum link sent via CiviMail, Drupal considers the user to be anonymous. I can pull the cid (CiviCRM contact ID) from the URL easily enough, but I need to be able to also verify the checksum in order to display information without a possibility of an information leak. How do I do that?

I found this function:
CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId) but this generates the checksum. I just need to verify an existing checksum (from the URL), not create a new one.

A little grepping around and I found this:

CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])

which takes a CiviCRM contact id ($cid) and compares it to the checksum in the URL and did the trick for me as follows:

  $cid = check_plain($_GET['cid']);
  if ($cid != "" && CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])) {
        //Contact ID and Checksum match up, embed a view
        //with $cid as an argument (or other custom functionality)
  } else {
        //Not a match, decide what you want to do in this case
        //(e.g. check if user is logged in, or display error...)
  }

UPDATE:

It looks like the usage has changed slightly in core since I pulled the above out of there (although the above was still working for me). Try this (taken from here):

    //check if this is a checksum authentication
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
if ($userChecksum) {
  //check for anonymous user.
  $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
  if ($validUser) {
    return $tempID;
  }
}


Redirect to the registration page of the main domain I have a master site at http://www.abc.com and a subsite at http://www.abc.com/xyz.

I want to redirect a user to the registration page of the main domain, whenever a user tries to register on the sub-domain.
As they are different Drupal setups, how do I redirect a user?

Follow below steps to solve your issue.

Install rules module in subsite.
Create a rule with condition as page being viewed is user/register
Add an action redirect to URL with url as main site user/register path

Other way to do is using custom module in sub site

Use hook_init in custom module

   <?php
      function yourmodule_init() {
         if (arg(0) == "user" && arg(1) == "register") {
           drupal_goto("http://www.abc.com/user/register");
         }
      }
   ?>


How can I make a field appears when you check on a checkbox? I'm making a module and on the administration page there is a form and I want to make one of the fields appears only when user check on a checkbox. Like the option to add a new content to a menu.

You can use #states from FormAPI that drupal provides.
Below is the link
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states

Below is the code from drupal form api

$form['email_canceled']['settings'] = array(
    '#type' => 'container',
    '#states' => array(
      // Hide the settings when the cancel notify checkbox is disabled.
      'invisible' => array(
       ':input[name="email_canceled_toggle"]' => array('checked' => FALSE),
      ),
    ),
  );


How do I retrieve all forums? I'm trying to retrieve all Forums on a Drupal 7 site, using the Services module.

I can get a list of all "forum topics" (which I think of as forum entries or forum posts) this way:

curl -i -X GET \
  -H Cookie:SESSedeadbeef=B0ZkiW3-U2x93yJU-jusjw6A-SgeShSNTYEkG \
  -H Accept:application/json \
  'http://myserver.com/rest/node?parameters\[type\]=forum'

How can I get a list of all the Forums? The parent containers for those posts?

Also, where is the documentation on the Services module?  I am having trouble finding anything.

ok, I got it to work, I think .

Accomplishing the goal requires two steps. First, find the "taxonomy vocabulary" for forums.  Then query the tree for that "taxonomy vocabulary".

Step 1:

curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'

Result:

[{
  "vid": "1",
  "name": "Forums",
  "machine_name": "forums",
  "description": "Forum navigation vocabulary",
  "hierarchy": "0",
  "module": "forum",
  "weight": "-10",
  "uri": "http://myserver/rest/taxonomy_vocabulary/1"
}]

Step 2: Using that vid, Query the tree (via POST!!)

curl -i -X POST \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 -H content-type:application/json \
 'http://myserver/rest/taxonomy_vocabulary/getTree' \
 -d '{ "vid" :"1" }'

Result:

[{
  "tid": "1",
  "vid": "1",
  "name": "General discussion",
  "description": "",
  "format": null,
  "weight": "0",
  "uuid": "dbf914e7-42c2-45f6-b77a-e66a0da72310",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "4",
  "vid": "1",
  "name": "Security and Privacy Issues",
  "description": "",
  "format": null,
  "weight": "1",
  "uuid": "7496bfd7-2cb8-4f87-a1e4-f45b1956a01e",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "5",
  "vid": "1",
  "name": "etc....",
  "description": null,
  "format": null,
  "weight": "2",
  "uuid": "9fde5519-16b2-453d-852b-a8c416189e30",
  "depth": 0,
  "parents": ["0"]
}, ...]

Or, you can do a parameterized GET:

curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'

The same data is returned.

My next challenge will be to retrieve the list of posts for each particular forum.

Editorial comment: I saw this documented NO WHERE. I really don't understand how developers who use Drupal manage to use the Services module.


Webform radio button sets common functionality I have 2 sets of radio buttons which have different data and because they are radios, you can only select a single option per set.

However, I am trying to achieve a setup which will allow only one selection between the 2 sets of radios.

So, if I select an option in set#2, any previously selected option in set#1 will be deselected and vice-versa.

Can anyone help with this?

ps: I know JavaScript should fulfil this need but I am trying to find alternative solutions in case javascript is switched off and the functionality breaks.

AFAIK javascript is the only option and I do not see any help in the Drupal webform module

You could do it effectively in javascript/Jquery.

Another option as Beebee suggested you could force all the 4 radio buttons into a single set.

<div id="content">
 <input type=radio name="chooseme" value="1" />
 <input type=radio name="chooseme" value="2"/>
 <input type=radio name="chooseme" value="3"/>
 <input type=radio name="chooseme" value="4"/>
</div>

Now,user would be left to choose any one of the four radios.


Node content is not listing for author I have a view page with url user/%/plans.Which listing contents by a particular user.But listing can be seen only for the administrator when visit their dashboard(from admin/people)(screenshot 1).
But logged in user(content author) cannot see the list(screenshot2).

I gave all the permission to the author to view his content.But it is not working.Can any one give suggestions to solve this issue?
This is my views(screenshots 3 & 4)

Your Contextual filter should use Validator Current user ID matches argument value instead of User:


How to always print submenus from menu module? I'm using Drupal 7.35, with the stock menu module. I've set up a menu that has multiple submenus, and ran into something interesting: the submenus only are printed to HTML when you're on that menu's parent page.

For example, let's say this is my full menu:

- Link 1
  - Link 1.1
  - Link 1.2
- Link 2
- Link 3
  - Link 3.1
  - Link 3.2
  - Link 3.3
- Link 4
  - Link 4.1

Each submenu shows up only if you're on that menu's parent item. So, when you're not on any of those pages, the Menu is printed like this:

- Link 1
- Link 2
- Link 3
- Link 4

If you're on the Link 1 page, or any children thereof, it prints like such:

- Link 1
  - Link 1.1
  - Link 1.2
- Link 2
- Link 3
- Link 4

If you're on Link 4, it looks like this:

- Link 1
- Link 2
- Link 3
- Link 4
  - Link 4.1

I want all the menu items to always be printed. How do I do that? Is this normal behavior, because I'm pretty sure I didn't have this issue on the other Drupal site that I've worked on.

One of the solution is to use Menu Block. It allow you to display any menu items based on depth. So you have all the control. To list all the menus, in Menu Block you can change the "Maximum depth" to Unlimited.

--- Updated 07/06/15 10:25am ---

You may need to use the Advanced options in your situation. Then check the "Expand all children of this tree". See below screenshot for details.


Use tokens for cck field default value Is there any module or code hack to use tokens to set cck field default values ?
i have a content type with contact details fieldset, this fieldset have some fields to collect data from current logged in user.

Indeed: Field default token.

  This module enables to use tokens as field default values.

See the related core discussion if you're interested.


How to access rules condition values in the rule event? I have created a rule (using Rules) in which I added 3 conditons. Now I want to access the conditions values in the action that on which condition the action is performed.

I am attaching the screenshot :

As shown in the screenshot, I want to access

[commerce-license:type], Data value: Diamond Subscription

How can I achieve this ?

I'm not sure if it'll be the only thing you need to do to get this to work, but I think you may get closer (= simplify your challenge) by ALSO using the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):


Git cloning a project asks for git@git.drupal.org password I'm trying to switch to SSH keys as the password authentication is now deprecated and I am having an issue. I've created a new key pair and entered the public key in my account and setup my Git Bash to use the private key.

When I try to clone one of my projects, I get a password prompt asking for "git@git.drupal.org' password.

However, when I run  ssh git@git.drupal.org -v, it asks for my private key password and the output log says that I was authenticated.

  debug1: Authentication succeeded (publickey).
  Authenticated to git.drupal.org ([140.211.10.43]:22).

Why does the above appear to authenticate but running something like the following does not?

git clone --branch 8.x-1.x git@git.drupal.org:project/MY_PROJECT.git

EDIT: I'm using Git Bash on Windows.

I was finally able to solve the issue by removing all git programs from my computer and then reinstalling only Git (bash). I think Tortoise Git was interfering somehow and causing the issue.

After removals and clean install, my clone worked right away. Simple.


Taxonomy term option is missing in view category I have several site on Drupal 8.5  where I don’t see the "taxonomy term" option in view. So I can’t create a view that lists taxonomy terms of a vocabulary.

See the first screen shot to see the problem.

Why I don’t see this option ? Is there something to install or enable ? I’ve checked a lot of things and I still don’t understand.

Below, there is a second screen shot of an other Drupal where I have this really useful field.

Finally, this is what I would like to add in fields and Filter in view.

All you have to do is to choose "Taxonomy terms" under VIEW SETTINGS when you add a new view on MYSITE/admin/structure/views/add.


Drupal.t() and language code I want to write some JavaScript code for my project. I need to use Drupal.t(), but it seems that Drupal.t() only accepts English, and I don't want to write my JavaScript in English.

Is there any way to inform Drupal.t() that my string is not in English, just like t() that let you specify the language code.

Nope, not really. Drupal is built from ground up in English and that's the way you need to build your modules too. Some parts of the code tries to enable you provide default texts in another languages, but it's a disaster if you decide to change default language later.

It is possible to built functionality like you need in a custom module, it is even possible someone did, but I don't know of any reliable solution.


What's the functional difference between the "disabled" and "external" caching setting? I've seen the answer elsewhere that "External lets you use varnish, etc" but what are the internal differences between external and no caching? Does external actually cache anything, or is there a difference in headers sent?

External caching is just a caching system that doesn't use the database tables used by Drupal to cache data, or doesn't use any table in the database used by Drupal. Example of external caching systems includes APC, eAccelerator, Memcache/Memcached, Varnish, XCache, or even a system that uses files instead of database tables.

All those systems surely cache data, or there would not be any difference between using them, and disabling the cache completely. The only difference with the standard Drupal cache system is where the data are cached.


Shared database during development? Sometimes I need to collaborate with a more frontend-centric developer to help implement a site. So typically they're only changing CSS and minor template changes.

The way we've handled this in the past is that I work locally. When I have everything in a good state, I clone my environment to a staging server. The frontend dev then uploads his changes via sftp.

We'd like to move toward a setup where we're both working locally. The problem of course is keeping the configuration changes all in sync. I have been using Features, but there is still a lot of global configuration that would need to be manually migrated between instances.

I'm not quite ready to make the jump to each of us having a local database. I have considered taking a "half step" by having a shared database that we both connect to over the network.

I've found a few blog posts here and there where people have suggested it, but I thought I'd ask here: have you tried this, and if not, is there's any reason this is a bad idea?

We've been through the same scenario as you in our company, and currently we've ended up with a situation where we work on a remote development server and have our code locally via sshfs mounts. It works pretty well, you can read more about it in this blog post I wrote.

You can't use graphical clients (e.g. gitx or gitl) so we use git and drush on the commandline, but that actually made people more aware of how those tools works rather than just clicking the same buttons every time.

On a different note, you should also use memcached so your cache doesn't get shared via cache tables in the shared database. It's pretty simple to setup and after that just make sure every developer has a unique memcache prefix.


How to hide an empty block with no results The block is generated by Views and I the only field comes from a relationship and is not accessible in the filters, so I can't set a filter.

I have tried to use another field, rewrite the results but the filter only considers that initial value of the field, not the rewritten one.

I suspect I have to do something with a template file, but a precise how-to would be very helpful.

Thanks in advance!

try restricting the block's display using "Pages on which this PHP code returns TRUE (experts only)"  and checking for the final re-written value there.


Search API with Panels in Drupal 7 I want to create a search that is able to index panels. The content in my Drupal system is mainly located in Panels (which contain Blocks with the content).

I installed Search API along with Fuzzy Search and i only get results for "normal" nodes/pages, but none for my Panels. Is there any way to add Panels to the search index?

Here is your answer: Page manager search. It works with the Search API module. Here is an excerpt about it from the module's project page:

... adds the ability for Page manager pages to be searchable via the Drupal core Search module or the Search API module.
Support for:

Drupal core Search module.
Search API module (via the Entity API module)

Note: this is a new module.


Why and when is feeds_entity_load needed I have the feeds module enabled and when I load a basic view, it generates 688 calls to the function feeds_entity_load which generate as many database query, which degrades the performance.

Why are these call needed ? For me feeds is only use to import data, so why is it impacting every single page load ? I'm thinking of deactivating this function but I would like to understand if it's safe to do so.

Why and when is feeds_entity_load needed

It isn't.

feeds_entity_load() was removed from the Feeds module 3 years ago. It no longer exists in the codebase (download and grep -nr feeds_entity_load feeds, the only reference you'll find is in the changelog).

You should upgrade your version of feeds ASAP, you must have an outdated version installed.


Create nodes out of Webform submissions We are using Drupal 8 and trying to solve this problem: A form shall be presented to website visitors that asks them to submit questions (in our case: concerning nutrition) and give some structured background information like the region the user comes from etc.

The submitted information shall then be transformed into a node of a given content type to make it easier for the editorial staff to edit that question in the backend, add an answer to it and publish the whole thing.

The forms shall be used by anonymous users and we do not want to let them create nodes directly via /node/add - for security reasons on one hand and with regard to the complexity of the creation form which is not needed at that point on the other hand.

I have read this: How to create a node with submissions of a webform? but I am not sure whether that would be a solution to our task. It says: "Hide the toolbar for other users and give them permission to add new content. Lastly, adapt the node form to your needs with a template file and style it with CSS." Would I have to expose parts of the backend to anonymous users and give them the right to create new nodes? We would like to avoid that due to security concerns.

I did this previously on Drupal 7 and it might be possible to adapt the process I used:

Via hook_form_alter add an additional submission handler (i.e. form['#submit'][] = '_webform_submit_handler';)

Inside the submission handler function:

Create a new node (i.e. $node = new stdClass();)
Assign the relevant fields (i.e. $node->title = 'Title';, $node->type = "type";, etc.)
Save the node (i.e. $node = node_submit($node); and node_save($node);)


Change node during saving it I am using Drupal 7.34 and I have a problem..

My module is reacting on node changes. When a node is updated one or more other nodes are automatically being updated, too. I call a function that triggers that update in hook_node_save.

Everything is fine until I try to make changes to the node that was initially saved and is passed to the hook_node_save. The reason is actually pretty obviuos: The changes prepared during the inital save process are overwriting the changes made during the function that is called in hook_node_save.

So here is my question with an example: I want to change field_a of node 100 after node 100 is updated from somewhere around the system. How do I achieve that while having access to the initially updated values of node 100?

Edit 1:

My hook_node_presave:

if (!$node->is_new) {
  $items = field_get_items('node', $node, 'field_oc_revision');
  if ($items) {
    _trigger_steps($items[0]['value'], $node);
  }
  debug($node);
}

The _trigger_steps() function changes the $node object passed by reference.

Now when I click save on a node form hook_node_presave is triggered twice. The first time the debug shows that the field is changed in the normal $node field, but not in the $node->original field. The second time the debug shows that the field is changed in the $node->original field, but not in the $node field.

Hope that gives more insight.

Edit 2:

One more thing to mention: When using the same code with manually calling $node = node_load(100); node_save($node); everything works like it should.

Edit 3:
This is the part of the code of the _trigger_step function that is executed.

$connected_node = user_activity_get_step_base_node($base_nid, $step['connected_node_type']); // In this special case this loads the node that was just updated

$items_base_field_name = field_get_items('node', $connected_node, $step['base_field_name']); // $step is a definition of a step to trigger.

$expert_uid = $process['coordinator_user'];

$expert_nid = $items_base_field_name[0]['target_id'];
$expert_nid = node_load($expert_nid) ? $expert_nid : '';
// check if expert uid is set and node is not already linked
if($expert_uid && !$expert_nid) {
  $expert_node = new stdClass;
  $expert_node->type = $step['node_type'];
  node_object_prepare($expert_node);

  $expert_node->language = LANGUAGE_NONE;
  $expert_node->title = $node_type_names[$step['node_type']];
  $expert_node->uid = $expert_uid;
  $expert_node->promote = 0;
  // connect the nodes
  $expert_node->{$step['assignee_field_name']}[LANGUAGE_NONE][0]['target_id'] = $connected_node->nid;
  // tree assignment
  $expert_node->field_oc_revision[LANGUAGE_NONE][0]['value'] = $base_nid;
  $expert_node->field_oc_tree_element[LANGUAGE_NONE][0]['value'] = $step['sid'];

  // save new node
  node_save($expert_node);

  // if the updated node is the one that we want to change here, we just change the passed node. it is saved after hook_node_presave.
  if($updated_node) { // $updated_node is passed by reference
    $updated_node->{$step['base_field_name']}[LANGUAGE_NONE][0]['target_id'] = $expert_node->nid;
  // if not we set save it directly
  } else {
    $connected_node->{$step['base_field_name']}[LANGUAGE_NONE][0]['target_id'] = $expert_node->nid;
    node_save($connected_node);
  }
}

Thanks a lot!
cheers
j

After a long night of debugging I finally found the bug. I always thought that hook_node_presave is called twice when submitting a form. That is wrong. Took me a while to find out.

I then searched for node_save operations in my code through like 20 modules and found a module calling node_save in a custom node form submission handler. I removed it and it works now.

Thank you all for your help!


Remove Post Date from Views RSS Feed I have created a rss feed in a view and it's displaying too much information.
I found out that I could exclude certain fields from the feed by clicking the exclude boxes at admin/content/node-type/[content type here]/display/rss.

My problem is this: each feed displays a heading (which is a link) and underneath that there is a date (and the rest of the information below that). This seems to be the post date for the content type.

I would like to get rid of this date (it's confusing since the content type is an event which has its own date and they don't correspond). How can I do this?

Is the only way to fix this by editing the php code somewhere? I did notice that if I click on the theming: information (in the basic settings in the view) it lists some files for style output (such as views-view-rss.tpl.php) and row style output (such as views-view-row-rss.tpl.php).
Is this where I need to start?

Here's a solution for exactly that setup. (The fields you can control under display/rss are only the CCK fields, not the XML element you want to remove from the feed).


What determines which fields are available in the relationship options? What determines which fields are available in the views relationship options?

When creating a view, you can use Relationships, choosing from a list of available fields. Are all created fields supposed to be available for relationship in any view? It seems that some fields are available and some are not.

Example: I have Students and School as my Content Types. Students uses a Node Reference to School. When creating a view, I use Relationship, and a bunch of fields are there to choose from. As expected, School is there, because it is referenced in a field. But there are a lot more fields available. Why are those fields available? What criteria do fields fill to be available to use?

One thing that affects the choice of the fields that are available is the show box when you first create the view this allows the developer to refine the criteria that is being chosen.


How can we make edit Body input area larger? The Body field of the content on our website is generally quite large -- multiple pages.  When Editing in Drupal 8, the Input Area is quite small -- 98 characters wide by 9 lines.  The first thing we do is drag the bottom right of the Input Area and increase the size to 30-40 lines.  This makes editing much easier.
Is there a way to make the Body Input Area size 30 lines long for our website?  This would eliminate one step on every Edit!

You can go to the content types (or paragraph type) Form display settings and set the number of rows. No dev needed:

e.g. /admin/structure/types/manage/content_type/form-display

Click on the gear in the right column
Click update
Click save at the bottom


Where is the "add to cart" configuration? I'm trying to find the Add to cart form configuration for a product type in the UI.

When I export configuration, core.entity_form_display.commerce_order_item.TYPE.add_to_cart.yml contains the configuration for the Add to cart form, such as this (hiding quantity, creation date, and unit price):

content:
  purchased_entity:
    type: commerce_product_variation_attributes
    weight: 0
    settings: {  }
    region: content
    third_party_settings: {  }
hidden:
  created: true
  quantity: true
  unit_price: true

Where is the configuration page for this in the UI?  I keep clicking around and I cannot find it.

Go to the 'Order item types' page and click the "Manage form display" link for your order item type. You will then see a tab for the "Add to cart" form display.

For the 'default' order item type the url will be: /admin/commerce/config/order-item-types/default/edit/form-display/add_to_cart

There is an open issue for finding a more discoverable way to expose these settings.


Is there something like block_field? I need to be able to include block in the content of a node. I use display suite to accomplish this, but just wondering if is there something like block_field?

You can use the http://drupal.org/project/blockreference.  It's a standard on our projects now.  It also works well with the http://drupal.org/project/bean module


How to default a content type's Language field to the authenticated user's language? We are using Entity Translation so that content can be created in several language. One item we noticed is that on the basic page, for example, has a language field that you can set when you create a piece of content. As of right now, any users regardless of if their profile's preferred language is set to French (for example), the French user is still able to create a content in English.

Ideal scenario:

If a French user logs in and creates content of type basic page, then the language field should be set to French. If a German user logs in and performs the same actions, the language should be restricted to just creating content using the German language.

Any thoughts on how I would set this up?

actually, i would create a custom module (i hope, you know how to code a bit)

the code should be something like the following:

    <?php
    function YOUR_CUSTOM_MODULE_node_presave($node){
        global $user; // gets the current user account
        $node->language=$user->language;
    }


List all terms under a parent I want to create a taxonomy view, which only displays terms that belong to a certain parent.

However, the "Term ID with depth" filter that appears in a normal view seems to be missing in the Term View type.

Any ideas how I might go about achieveing this?

just add a relationship for "Taxonomy term: Parent term" and select "require this relationship".
Then add a contextual filter for termID, select "parent" as the relationship and select a fixed value of the parentID.

You can also do it without using relationships. Just add a contextual filter for "Taxonomy term: Parent term" and provide a fixed value for the parent term.


Unable to export and import custom block type fields I have created a new custom block type and added some fields to it.
I am able to export and import the custom block type in another Drupal instance via configuration management, but there are no fields.

How do I import the fields too?

The field definitions are in their own yml-files. To check this, export the full archive and search for the dependencies. For example the body of the block content type basic has this yml-file:

field.field.block_content.basic.body.yml

and there you find the dependencies for the block content type:

dependencies:
  config:
    - block_content.type.basic


No class for images when working with a specific theme (no .field--name-field-) I have installed a new theme and when I go to DOM I can't see classes for the image fields; These are available for styling the page's image fields.

For example, if I write in the css file: .field--name-field-bestimageever img {display: none;} the image keep appearing.

This never happened to me with any other theme and I would thank an experienced themer for giving an explanation on how to add this, from which many other people could enjoy.

The most likely scenario is that the theme does not implement those field classes. Not all themes implement classes the same, but rather take a bottom up approach - the theme starts off very "clean" with only enough classes to support core behaviours etc, leaving it to the themer to add more classes as required. An example of this is the Stable base theme.


Creating a block that lists various posts for various categories I need to achieve something like this:

This is a block on a page. Stuff like U.S., Politics, World etc. are the categories (created by adding a custom vocabulary) and the sub-links are articles under those categories. I'm using Drupal 7.8 and have the Views module installed.

Maybe I could write some PHP code and save as a block and then add that to a region. If so, which functions would I need?

Views are you friend. A View can also generate a Block. The sub-links are categories ordered by publishing date? Fairly easy.


Show a view of Related Terms to a given Taxonomy term How can I create a view and show only taxonomy terms related to the term you are currently viewing (term id in URL)? I have tried a handful of relationship and argument configurations, but can't seem to simply list the related terms to the term being viewed.

Edit: I have related the terms through the core taxonomy interface.

I have done the same thing through Panels. I was stuck with views for a long time. All you have to do is to override the "Taxonomy Term Template" in panels. Add a new Variant with settings of your choice (default ones would be fine too). Go to 'content' section and add new one. Choose 'list of related terms' and inside it you would find the related terms you need. Make sure you give it a valid path and there you have it!

I don't know how this could be done in views but for me this is more than fine.. :)


Set placeholder for views exposed input I create a search section with view and I want hide label of search inputs and set placeholder for them.

Is there any section to set this?

Drupal 8

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if($form_id == 'views_exposed_form'){
      $form['field-name']['#attributes']['placeholder'] = t('Placeholder Keyword');
   }
}


How to grant User Points to viewing user when user has viewed content? Can anyone provide me with a simple rule that adds 1 user point to a user when this user has viewed an entity of "Article" (for example)?

I have enabled the User Points module and the "Userpoints rules" integration module. But I can't find a way to get this to work.

Interesting question, worth to be considered as a great question for a Drupal site building exam!

Have a look at this rule:

{ "grant_user_points_after_content_view" : {
    "LABEL" : "Grant user points after content view",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "node" ],
          "description" : "View of node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022",
          "operation" : "NodeViewed",
          "reference" : "Viewing of [node:content-type] \u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E\/node\/[node:nid]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Some details about this rule, which you should be able to import in your own site if you have the Rules UI, and Userpoints Rules (a sub-module of Userpoints), enabled and after you enable the rule also:

Rules Event: a Node of content "Article" is viewed (adapt the machine name of the used content type to any type that fits).
Rules Condition: user is authenticated (to be able to grant user points).
Rules Action: grant 1 point to the user viewing the article. And use some of the available tokens to add some more details to the actual User Points transaction (description, operation, reference) ... just for fun.

Easy, no? Sorry you had to wait for 2 years ...

PS: The previous answer is not really an answer to the question here I think.


Set the inital number of empty values for a cck multi-value field I have CCK fields that can hold multiple values, I would like some of them to default to showing say 5 values initially.

I'm not looking for any validation that all 5 values are used however.

Thanks!

Unfortunately there is no way to do this without altering the module code of CCK.

There have been a few patches created that will allow you to set the number of fields initially shown and let you choose how many more to add when click the "Add another" button. However, this feature is not available in the core of Drupal 7 which may be a problem if you choose to upgrade.

Patch created for CCK 2: http://drupal.org/node/530828#comment-3397196

Patch created for CCK 3: http://drupal.org/node/841914#comment-3209072


Migrate module showing error messages I am importing database from Drupal 6 to Drupal 7 with migrate module.

The progress bar is 5%.
The importing data taking a long time.

How could I make it faster? Using Drush?
And the error messages below are having problem?

  Processed 263 (0 created, 0 updated, 263 failed, 0 ignored) in 27.8
  sec (568/min) - continuing with '1cf4f3dbbFile'

  Processed 260 (0 created, 0 updated, 260 failed, 0 ignored) in 27.3
  sec (571/min) - continuing with '1cf4f3dbbFile'

  Processed 258 (0 created, 0 updated, 258 failed, 0 ignored) in 27.5
  sec (564/min) - continuing with '1cf4f3dbbFile'

  Processed 253 (0 created, 0 updated, 253 failed, 0 ignored) in 27.5
  sec (552/min) - continuing with '1cf4f3dbbFile'

I have gone thorugh drupal migration many times and it takes much time if DB is heavy.So Take a breath and keep it going.....once 100% migration is done then you proceed.
And also D2D module provides option to select which content types you want to migrate first.In this way you can divide your migration into parts and process will be fast then previous.
Good Luck :)


Adding a title to a ul in the menus I need to create the following to a menu system in drupal 7. I want to be able to create a href that is not connected to a content type. Is this possible?

link

link

I need this link to not be attached to a content type

link

link

try this module "Nice Menus" and this "Menu Attributes".

You can follow these tutorials for more informations:
http://codekarate.com/daily-dose-of-drupal/drupal-7-menu-attributes-module
http://codekarate.com/daily-dose-of-drupal/drupal-7-nice-menus-module

I hope it helps you out. Thank you


Programmatically set the default value for a field In Drupal 6, we could use PHP to set default values, but the same code cannot be used with Drupal 7.

I am trying to do this through hook_form_alter(), but the code doesn't work.

function my_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);

  switch($form_id) {
    case 'accounts_node_form':
      $form["field_accounts"]["und"]['#default_value'] = $default;
      // …
      break;
  }
}

Assuming that your form alter function is actually running (which you can confirm with that call to dsm()), there are actually 2 more levels of array you need to go down to in order to get to the field element:

$form["field_accounts"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;

In Drupal 7 you have a an array of values for each language the field has been translated into (so that fields with multiple/unlimited cardinality can be catered for), and under each of those is in array for the various different field columns. In the majority of cases this will be 'value' but not always (for example an image field has a file id column, alt column etc)

Hope that helps


Changing the menu active-trail depth So it looks like drupal menus only have a active trail depth of one, which is problematic for my nested pages since my menus wont be marked active once I drill into the nest. Is there a module or setting to fix this?

What I mean is if I have the following pages:

about/board-directors/john-smith

and a menu that shows:

about
board of directors
something else

I could be on "about" and the about link would be active. I could be on "about/board-directors" and 'board of directors' would be active. But If Im on the page "about/board-directors/john-smith" I would like the 'board of directors' menu item to be active. How can I accomplish that? Im a bit of a noob so I'm in the dark here.

The Menu Trail By Path module will accomplish this:

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.

  For example if you are at yoursite.com/blog/category1/article1
  Menu
  Items with these paths will get the active-trail class on them and
  expand accordingly.

  blog blog/category1 blog/category1/article1


Views XML individual taxonomy output I am using Views and Views Data Export to create a page of XML data from a specific node type.

The node type has a taxonomy field with unlimited output so that views returns all the selected terms as a comma separated value.

However, I need to output the taxonomy terms as separate XML nodes rather than a comma separated list of one.

So, I currently get this output:

<nodes>
 <node>
  <nid>12</nid>
  <categories>Corporate, finance</categories>
 </node>
</nodes>

I would like to get the following:

<nodes>
 <node>
  <nid>12</nid>
  <categories>Corporate</categories>
  <categories>finance</categories>
 </node>
</nodes>

The difference being that I have two categories fields instead of one.

Can anyone help, please?

In your views panel, if you edit your taxonomy field, one of the options is "Multiple Field Settings", with a checkbox for "Display all values in a single row". If you uncheck this box, you will get multiple rows, however, it doesn't group them into one node. You get the entire node repeated. The setting mentions adding a "group by" to your display, but the data export display doesn't seem to support that.

So I did a search and found this article on drupal.org: https://drupal.org/node/1187712
It looks like there have been a couple of patches created for adding group by functionality. It doesn't look like they've been integrated into the base code, but maybe one of the patches will work for you.


Embed a view in the body of a node I want to embed a view into the body of a node on Drupal 7. I've tried the module Insert View and that didn't work.

I also saw support from Drupal on inputting PHP code, but I have no idea where to put that code.

When I want to display a View on certain content types, I make use of the functionality offered by the EVA: Entity Views Attachment module. On the entity's Field Display administration page, you can (like any other field) set the order for outputting the Views' result.

An interesting feature of the EVA: Entity Views Attachment module is that it allows to pass any token generated from the specific entity to the View as an argument.


Drupal Json Output strange characters when pulling from other language Hi Fellow drupal experts,

I have a problem, I developed a custom page intended to do a drupal json output :

and here is the code :

    function blogpull_menu() {

$items = array();

$items['blogpull'] = array(
    'page callback' => 'blogpull_view',
    'delivery callback' => 'drupal_json_output',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);
return $items;

}

function blogpull_view() {
    global $base_url;
    global $language;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'blog')
      ->propertyCondition('status', 1)
      ->propertyCondition('language', $language->language, '=') // filter by current language
      ->range(0, 5)
      ->addMetaData('account', user_load(1)); // Run the query as user 1.
    $result = $query->execute();
    if (isset($result['node'])) {
      $blog_items_nids = array_keys($result['node']);
      $blog_items = entity_load('node', $blog_items_nids);
    }

foreach ($blog_items as $key => $blog_item) {
    $arr = array('date' => date('M. j, Y', $blog_items[$key]->created), 'title' => $blog_items[$key]->title, 'description' => $blog_items[$key]->body['und'][0]['value'], 'href' => $base_url.'/node/'.$blog_items[$key]->nid);
    $arrs[] = $arr;
}

return $arrs;

}

and some how when it's loading the japanese language it is showing this strange characters :
ã‚¯ãƒ©ã‚¦ãƒ‰ã‚²ãƒ¼ãƒ äº‹æ¥ã®æ–°ä¼šç¤¾ã€Œã‚·ãƒ³ãƒ©ãƒ»ãƒ†ã‚¯ãƒŽãƒã‚¸ãƒ¼ã€ç™ºè¶³

I tied using utf-encoding, mb_encoding and so on but nothing happen

can someone help?

thank you!

just check HTTP response headers it should have utf-8 charset.


Use title instead of nid for node reference contextual filter I have a view with a node reference field as contextual filter. Instead of using
pagename/[nid] I would like to use /pagename/[title] or the pathauto url.

For uid fields there is an option to either use the uid or the name (or even both). I don't see such an option for nodes.

Is it possible?

The reason Views' user reference field allows both the user uid and name is most probably because they are both unique, while the title of a node isn't guaranteed to be so, but of course the nid is.

If, however, your content titles are unique, you might try using it as the contextual filter, hooking it up with a relationship (or rather whatever the D7 term is for it :) to the node reference field, and using all of the lower case transforms and spaces to dashes stuff.

That only leaves a problem if the title has funky characters in it, eg, if the title is This & That your path has to be pagename/this-&-that for the view to work which is ugly to say the least.

Now, how I've dealt with this is to create another text field in my content types that I want to search for by title and I store a url safe title in there.  I auto fill them here in D6 land like this:

function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

  if (isset($node->field_url_safe_title) && $op == 'presave') {
    module_load_include('inc', 'pathauto');
    $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }

  // all the other nodeapi stuff here

}

and now I can use pagename/this-that by filtering on this field instead of the title.

I use the nodeformcols module to hide this field on the node edit/add forms and don't display it in the node itself, but I am sure there are D7 ways of doing that.  Obviously, in D7, I'd also assume you'd use hook_node_presave() instead of hook_nodeapi() and add in a language array field when setting the field, but the logic would remain the same.


Change existing configuration at theme installation I am creating a custom Drupal 8 theme, and I want to change the image style of the indexed article content of the frontpage - only the article content type.

To do that properly - avoiding using CSS hack - I have to *change the image style the image field of the display mode Teaser of the article content type**, the display mode "teaser" is used by the native view "frontpage" to index content. And I have to do that modification at the theme installation and thus configure the theme properly to do that modification at installation. It's not working with conf file because the configuration already exist.  i am asking here advice on how to do that.

In details: I need to change the image style of the field "field_image"  of the mode display "teaser" of the content type "article".

By default it use the image style "large" and I want it to use a new image style "hp_wide" that the theme import -  successfully - at theme installation.

From my research, I've found that I've to create a PHP function in MyThEme.theme with \Drupal::configFactory()->getEditable($name), it is the correct way? If yes how can I target that specific field settings, how can I know the "path" of that settings?

i've found a solution: define the style of the image directly into the twig  template. As a theme can define new style of image when it is installed it's possible to use a non native style of image. In the example below i use the style "wide", created at the theme installation, instead of the native style "medium" used in the indexed content in the homepage.

 {% for item in content.field_image['#items'] %}
  {% set image = {
    '#theme':      'image_style',
    '#style_name': 'wide',
    '#uri':        item.entity.uri.value,
    '#alt':        item.alt,
    '#width':      item.width,
    '#height':     item.height
  } %}
  {{ image }}


What does 'Drupal-friendly' hosting mean? I'm new to Drupal and web-hosting generally. My question is what constitutes a totally Drupal-friendly host? I know that the installation is made easier by the host provider letting you have SSH access and the ability to extract compressed files on the server.

What else should I look for in a Drupal-friendly host?

There are some things you may want to look into:

Drupal Requirements:

PHP 5.2+ (Drupal 7)
MySQL Database
128mb Memory Limit (For Heavy Imagecache processing)

Not Requirements but perks:

SSH
Drush
Git (Latest)
Crontabs
Curl


Add/attach a field to all content types I know that I can attach a field to any content type. I have to attach a field to all content types in a my site which are more than 40 content types. It is hard for me to attach this field manually. I'm seeking for an automated way to do this. Is there any module to do that?

Use your favourite SQL client and amnually populate {field_config_instance} table:

In Drupal, create field in one content type.
In your favourite editor create set of 39 queries (40 content types minus that one you worked out manually), with the same field values. Just leave id empty so autoincrement can work, and populate entity_type with your conetnt type names. I use spreadsheets to do that, first spreadsheet column is first query part, second is for the names of content types (obtained by querying {node_type}, third is for last part of the query.
Paste that query set into your SQL client and execute.


Main menu is hidden from unauthenticated users I am using a slightly modified Responsive Batrik theme. The odd thing is that the main manue and site logo are hidden from unauthenticated users. When they log in, they can see the menu and logo.

I'm wondering why this happen and how to solve it?

Follow Below things:

1) Make sure that in admin/people/permissions "View published content", "view own Unpublished Content are "Unchecked" for the "anonymous user".

2) Still if you are getting those "Disclaimer and Policies" menu links. i) Create a new menu and add those links in to that menu. While adding links Give the Parent menu link to "Main Menu". and save the menu. ii) Then admin/structure/block, configure the menu block: Give the permission to access only to Authenticated User and save the block

or,

If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):

<?php print theme('links__system_main_menu', array(

  'links' => $main_menu,

  'attributes' => array(

    'id' => 'main-menu-links',

    'class' => array('links', 'clearfix'),

  ),

  'heading' => array(

    'text' => t('Main menu'),

    'level' => 'h2',

    'class' => array('element-invisible'),

  ),

)); ?>


How to add constrain validation on entity_create So in my BaseFieldDefinition I have this below

 $fields['name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Name'))
  ->setDescription(t('The name of the Crypto entity.'))
  ->addConstraint('UniqueField')

And I was hoping this would make this "name" field unique when creating new enteties. It does when I try to do that in UI, but when programmatically making new entities it is just ignored.

 $crypto = entity_create('crypto', array(
  'name' => "Dai",
  'status' => '1',
));
$crypto->save();

So should I use some other method for creating entities or do I need to add some manual validation here?

Also extra question, how do I find list of "addConstraint" values that are present in core?

Entities aren't validated automatically when saved via the API. (I'd be interested in knowing more about why not.) See the validation API docs for examples of validating a field and a whole entity:

$violations = $entity->field_text->validate(); // single field
$violations = $entity->validate();             // whole entity

if ($violations->count() > 0) {
  // Validation failed.
}

To find all possible constraints, look for anything extending (possibly indirectly) \Symfony\Component\Validator\Constraint.


How do I completely unpublish a node (not just change revision state) when using Workbench Moderation with rules? I am attempting to use rules scheduler to automatically 'archive' content after a set period. Essentially, I want the content to disappear for everyone except administrators. Ordinarily, I would just use the standard 'unpublish node' action, but I have installed workbench moderation and this does not unpublish the node. If I attempt to simply change the revision state to Draft, the state changes but the node is not unpublished. Is there any way I can unpublish the node programatically? Should I look at some kind of access control module instead?

Well, I suppose it's a bit late, but this issue is discussed in and should be mostly solved by https://drupal.org/node/1436260 once the issue is fixed. You should be able to unpublish the node, and as long as the code calls node_save, workbench moderation should set the state back to draft. If you want a different state, e.g. "archived", you'll probably have to come up with something custom.


Auto-create Nodes based on Content in current node? In Drupal 7, is there a way to auto-create a node of "Type B" whenever a node of "Type A" has been created? Ideally, certain info would be passed on to the new "Type B" content item as well. For instance...

Let's say I create a new Type A content item, and that the Type A content type has several CCK fields. One of those CCK fields is a Node Reference field, which refers to content items of "Type C". Another of the CCK fields in Type A is a basic integer/text field.

When I create that new Type A content item, I choose "Content Type C Content Item #1" from the Node Reference drop-down select list. I also add "100" to the integer/text field. I'd then like a new Type B content item to be auto-created, with the same node reference info in its own node ref CCK field and the same integer/text in its own integer/text CCK field.

The purpose of this is to track usages of parts in sort of a macro and micro situation... Type C is the macro/master, Type A is the sub-macro/sub-master (if that makes sense) and Type B is the micro/slave of Type A. There will be many Type B's associated with a single Type A, but there will likely only be a single Type A content item associated with any given Type C content item.

I'm open to any all all suggestions, including scrapping this implementation concept in favor of something else that might work better and might be easier to manage.

Thanks!

You can do this kind of stuff with Rules. You could also look into hook_node_presave() yourself and do logic when nodes of TypeA are being saved.


what is the hook name in order to alter theme function of specific element imagine that we have a list if items in $items array that it's theme function is list_item in specific page.

code is

theme('item_list', array('items' => $items));

but in my module, I want to alter the parameter 'item_list' and I want to use my custom render function 'custom_item_list'

I know that I must register and define custom_item_list function but I don't know in what hook I am able to alter the theme_function parameter of specific element.

You can use hook_theme() function to use custom item list.

Hook theme:

function mymodule_theme($existing, $type, $theme, $path)
{
  if ($type == 'module')
  {
    return array(
      'custom_item_list' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'custom-item-list',
      ),
    );
  }
  return array(); //will raise fatal error if void
}

Call it as usual:

theme('custom_item_list', array('var_name' => mymodule_variable()));


Responsive bootstrap grid with 6 columns of equal heights In the front page of our website, I would like to list down groups led by researchers and each group is having a thumbnail picture and a title where the picture is of fixed width/height but, the title is not (could be small or large - title appearing a the bottom of the image).

For some reason the grid is not displaying properly and I feel like it is due to the big/small titles of the groups which cause this issue. Column heights could be an issue.

My settings are as follow:

Drupal 7
Views 3 (Block and/or Page)
Unformatted
Fields

http://www.bootply.com/wtGxTJjXva  (I have 18 divs and they have to be divided into six in each row but, it does not) - could anyone point out what I am missing?

According to the image, first row and last column is showing two divs rather than one and in second row I got three divs squeezing into single column.

You should use 'Bootstrap Grid' format for Views in some cases, which you'll be able to select after install/enable of the Views Bootstrap module. Here is a quote about this module (from its project page):

  ... enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.


How can I create a link to permission group and configuration page on module install page? When you install modules I can see some modules have links on the install page directly to the permission groups and the configuration page. How can I create those links for my own module?

For settings page, in your_module.info.yml

configure: 'your_module.route_to_settings.form'

Permissions link is automatically shown whenever you have permissions defined in your module.


How to remove a help text from the registration form? I'm writing a custom function to now allow spaces and other special characters for the username on the registration form.

How can I remove the text "Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores." on that page?

I figured it out:

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

  if (!($form_id == 'user_register_form')) {
        return;
  }

  $form['account']['name']['#description'] = 'Username has to be between 5-20 characters long and can only contain letters and numbers.';
}


Limit caching for a specific page I'm working on a module, which includes a page that displays a select from a database table. The page content is getting cached for long periods, so is out of date for users.

What's the simplest way to set the cache timeout for this page to a shorter time (or even set that page to never cache)?

(As an aside, I intend to turn this table into an entity and integrate with Views later on, but I need an interim fix).

In case you know exactly when something changes (it is your own code doing it), you can also use a cache tag.

'tags' => ['my-tag'] within #cache and then when it changes, you invalidate it with \Drupal\Core\Cache\Cache::invalidateTags(['my-tag']).

The advantage is that your data is cached as long as possible and also immediately updated when it changes.

If you have constant changes, and that tag would actually result in shorter cache times, then setting a max-age might be more efficient, but that's usually not the case.


multisite or multi install? I am planning a Drupal 7 site for video sharing, where registered users can share videos.

Main Site: example.com
Subdomain for blog for registered users would be: blog.example.com.

The database would be different for main site and subdomain. Since the target of main site would be very high traffic, what would be the efficient choice ? either Multisite or Multiple Drupal installation (one installation for Main and another installation for blog) ?

what would you advice and why ? (I mean from personal experience, difficulty to handle and maintain, performance issues, etc)

Your choice of site architecture (e.g. multisite or multiple drupal installations) doesn't necessarily play into performance. Meaning any site can be made performant using the right mix of modules (memcache, Varnish on the front end, etc.);

With that in mind, look at the following criteria when selecting multisite over multi-installation instead:

Will most of the modules on the sites be shared with one another?
Related, will the modules always be in sync via version? i.e. Context 3 vs. Context 2.
Will the versions need to be in sync? i.e. If you upgrade the main site, will the blog site also need to be upgraded?

If the answer to any of these questions is yes, use a multisite. If there is concern about them, use two document roots with one site a piece. Sharing content can easily be done through any of the following projects so multisite or multi-installation doesn't matter:

http://drupal.org/project/feeds
http://drupal.org/project/migrate
http://drupal.org/project/services


Extend the drupal contact form How do I add fields to the standard Drupal contact form? Can this be done programmatically or is it a task for a module?

Yes, you can do that programmatically using the function hook_form_alter in a custom module. Follow this for creating a custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'contact_personal_form') {
    $form['new_field'] = array (
      '#title' => t('New field'),
      '#type' => 'textfield',
      'description' => t('The description of the new field goes here...'),
      '#required' => TRUE, // make the user to fill it compulsorily
    );
  }
}

Update: I forgot to mention that, the above code will just add the field to the form. The field is not added the mail you send. You should implement hook_mail_alter and add the field to the body, by something like:

function MODULE_mail_alter(&$message) {
  if($message['id'] == 'contact_user_mail') {
    $message['body'][] = $message['params']['new_field'];  //value of key 'new_field' same as in $form['new_field'] above in form alter
  }
}


How to resolve the negotiated theme for any other user? I have found How can I programmatically get the theme name?, which works for the current user, but would I apply such logic to learn what theme another user would use?

I can get the active theme for current user and the default theme by using:

$my_theme = \Drupal::theme()->getActiveTheme();
$default_theme = \Drupal::config('system.theme')->get('default');

I was hoping there would be something like \Drupal::theme()->getActiveTheme($other_user); to discover what theme another user would be using.

Is such a thing even possible and how?

UPDATE

To clear things up, I am attempting to figure out what theme was negotiated for a certain user. This could be the global default theme, but it could also be the theme that was negotiated based on a certain role, user selected theme, or any other contrib theme negotiator that might be in place.

So the better question would be, how can I discover what theme a user would be presented if he visits the site (no specific page)?

As far as I remember, this type of functionality was built in in Drupal 6.

In Drupal 7 there was the ThemeKey module .

Unfortunately, as of this date ThemeKey is not yet ported to Drupal 8, however I think you can achieve pretty easy that functionality by using the user data object inside custom module.

In order get something from the user data object:

$data = \Drupal::service('user.data')->get('mymodule', \Drupal::currentUser()->id(), 'key');

In order to set something in the user data object:

\Drupal::service('user.data')->set('mymodule', \Drupal::currentUser()->id(), 'key', $value);

Update:

you can combine the code above with the solution posted here:

https://www.drupal8.ovh/en/tutoriels/259/theme-negotiators-switch-theme-dynamically

where your negotiator will be called last by adding priority in the services.yml

you can implement the business logic inside the function the function determineActiveTheme. Combine this with hook_user_login where the information is stored inside users_data and you have a working solution (If I don't have a mistake somewhere).


Sub-directories in module's templates directory I have created a module in Drupal 8, which contains a large number of custom templates - these only theme the module's output, and don't override existing template files.

I would like to place these templates in sub-directories of the module's templates directory - for example:

templates/account
templates/orders
etc

If I place a template in a sub-directory, and set the renderer to use a #theme such as 'account/list_block' then the block doesn't render at all, but I get no errors.

However, critically, if I keep my template in the subdirectory but change #theme back to 'list_block' I get the following error:

Template "modules/contrib/mymodule/templates/list-block.html.twig" is not defined
(Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/contrib/mymodule/templates/list-block.html.twig"
 in the Drupal theme registry.).

Doing the above to deliberately break things would indicate that in the first example Drupal knows the template exists, and where to find it (in the account sub-directory of templates), but is choosing not to render it. Very odd.

Is what I'm looking to do possible?

You just need to specify the path to the template in hook_theme(), eg

function MYMODULE_theme() {
  return [
    'list_block' => [
      'variables' => [],
      // Underscores are not converted to dashes automatically in this case.
      'template' => 'account/list-block',
    ],
  ];
}


Display images filed in views slideshow in node content page Are there any ways to format/replace the images display in a node(e./g node/1)? I add a image field for my content type which allow multiple images, i want to display it in gallery/thumbnail/jcarousel/slideshow....

I know how to make a viewslideshow in a view, but it seems no way to do the same thing in node display (e./g node/1)

Create slideshow view block.
In view configuration, provide contextual filter of field "Content: Nid" and then provide default value "Content ID from URL".
Now place this block into Content region.


Simulate submission of custom form as a webform I've a custom module that generate a form, it allows user to submit some data to website.
I'm looking for a nice way to display those submit and I would very much like to use webform module for this (because it is already used a lot in company).

I would appreciate any help especially with some snippets.

I found only this post:
Submit a custom form as a webform submission
but that is almost nothing.

Here's how to create a Webform submission programmatically:

global $user;
$node = node_load(YOUR_NODE_ID);

// Prepare the data. Do note that the keys in this array must match the elements
// in your webform.
$data = array(
  1 => array('Field one value'),
  2 => array('Field two value'),
  3 => array('Field three value'),
);

// Create the submission object.
$submission = new stdClass();
$submission->uid = $user->uid;
$submission->nid = $node->nid;
$submission->submitted = REQUEST_TIME;
$submission->remote_addr = ip_address();
// This is necessary to mark the submission as complete.
$submission->is_draft = FALSE;
$submission->data = $data;

// Store the submission.
module_load_include('inc', 'webform', 'includes/webform.submissions');
webform_submission_insert($node, $submission);

// If necessary, invoke the email sending for this Webform.
webform_submission_send_mail($node, $submission);

Hope this helps.


Display Nodes from Taxonomy Category Term and Parent Terms I am using Views and Drupal Commerce but not sure this should matter as all my products are also nodes. I have a taxonomy hierarchy for categories. Example

Exterior Accessories
|_ Top
   |_ Soft Tops
   |_ Hard Tops
|_ Bottoms
   |_ Right Bottoms
   |_ Left Bottoms

I can easily make a page that shows me the Hard Tops if on that location or Soft Tops if at that location. But is what i can not for the life of me  figure out how to do is if I click on TOP I want to see Soft Tops and Hard Tops, and if I click on Exterior Accessories I want it to show products that are from any of the child elements with unlimited depth. So when viewing one of these pages it needs to work like so with the url.

categories/Tops -> Would show soft tops and bottom tops
categories/Soft-Tops -> would show soft tops only
categories/External-Accessories -> Should show everything

There is a function called taxonomy_get_tree() that you can use to fetch all the term IDs under a given parent ID. You can then call taxonomy_select_nodes() with an array of term IDs, which will return all nids that match that collection of tids.


How do I set my views to return a 404 using Global: Null under contextual filters? Standard Drupal behavior is to pass all arguments through, whether or not they requested. Sometimes this behavior is desired. However, I need to return a 404 for anything but a query string.

Example of the problem
http://drupal.org/project/modules
http://drupal.org/project/modules/google.com <- This should return a 404; 200 given. Duplicate content penalty!

The views 404 module assumes that by default you do not want arguments passed through. However there is no D7 version of the module.

But the project page says that 404s for views can also be accomplished by setting the Global: Null under Arguments.

Obviously in D7 "arguments" are now "contextual filters", but I am unsure as to what settings to add to the Global:null contextual filter to get my desired result.

Any help would be appreciated.

In Contextual filters select Add; in the dialog box that appears, select Global: Null.

Click on Add and configure contextual filters.

In the dialog box that appear next, in the fieldset When the filter value is available or a default is provided, check Specify validation criteria, select - Basic validation - for Validator, and select Show "Page not found" for Action to take if the filter value does not validate. In the fieldset More, check Fail basic validation if any argument is given.

I tested it with an "Articles" view I created, and it works.

The "Global: Null" argument must be the last one. If you need a user ID, for example, first you add it as argument, and then add the "Global: Null" argument.

I altered the "Article" view to accept a user ID as argument, which is used to filter the list of article nodes. The view still works, as it doesn't accept an extra argument.