Finding good minimalist base themes I am working on a Drupal project and teaching myself the system as I go along. I am trying to find a minimalist theme to use as a base for developing this site. I don't want a framework, because I don't have time to learn that too. I really just want a minimalist theme that looks good out of the box, but that can be easily modified in basic ways.

In my experience so far, most Drupal themes are either overly designed, or completely lacking in any formatting whatsoever. In the WordPress world, there is (for example) something like Thesis, which looks good out of the box but also has lots of potential for modification. Another example would be WooThemes' Canvas. Is there anything similar in the Drupal world?

Zen is all right but after using it a while I ran into problems since it's not built on the grid system. I found Omega pretty amazing as a grid-based starter theme for Drupal 7 with a responsive option. The steep learning curve was worth it, and it provides great tools and help.


How to display the node title in different region 2 using theme method in drupal 7 I want to display the breadcrumb and page title in my main content area.

For breadcrumb I used theme('breadcrumb', array('breadcrumb' => $breadcrumb));

What should I use for page title?
I have tried theme('pagetitle',  array('title' => $title_text)), but it is not working.

Also that how can I use the built in theme styles of paragraph tags or heading tags...
e.g. I used the following for generating a table in built in theme style

theme('table', array('header' => $headers, 'rows' => $rows));

You're looking for the $title variable.

<?php print $title; ?>

Here is a list of all of the variables that are available to you in a theme file (for a page).


entityQuery filter by content moderation state I need to filter a node by moderation state. I am using the Drupal 8 content moderation module.

I basically want to get NIDs of all nodes in draft state. Something similar to this.

$nids = \Drupal::entityQuery('node')
      ->condition('moderation_state', 'draft')
      ->execute();

You try the code :

$query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
    $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
    $query->fields('ms');
    $query->condition('ms.moderation_state','draft');
    $results = $query->execute()->fetchAllAssoc('content_entity_id');

Because entityQuery not filter content moderation


how to make unique fields in profile type in drupal 7 I am using drupal 7 and want to save unique mobile number for users. I have created a profile type field of phone number type.I have installed unique field module but not getting any option to make it unique while editing the phone number type field. I want make it a unique so there will be one mobile number for only one user.So how can we make a unique field in a profile types? Or will we have to make a unique field in a database itself??

You can use the http://drupal.org/project/field_validation for unique validation. When this module is enabled, there is a validation tab for each fields in content type. If you want to validate the unique value. Just go validation tab and click on the "Unique values", do some configuration, the unique value rule will be applied for current field.


Importing PDFs into Drupal as content types I'm new to Drupal and I have a question.

Is there any way to import table data on PDFs into Drupal, creating them as events?

I don't believe there is but I want to double check.

Not an easy task, I guess. Apache Tika is a toolkit to detect and extract metadata and structured text from various documents, PDF included. Is used, for example, by Apache Solr to parse and index PDF (and other) documents.

You may use Apache Tika to parse PDF documents and get the data you want, then create what you need (a Content Type, an Event).

Apache Solr Attachments seems to use Tika to index PDF documents, you can start looking at its code.


How can I provide a filter with context/nid of node invoking? I'm currently working on a custom module that has a filter that requires the node object for the output.

Originally the filter was simply pulling in the NID from arg(1) and using that to load in the node object, but unfortunately if the filter cache is flushed and the nodes rebuild their output from anywhere other than the node page itself arg(1) will not contain the NID and therefore the filter will break.

I'm considering putting the NID into the token that the filter converts, but obviously the NID would not be known during the creation of a node. It wouldn't be overly difficult to alter the token via hook_nodeapi() to insert the NID, but it seems like a lot of hastle.

Is there a simpler way to provide a filter with some sort of context so it can be aware of which node invoked it?

Filters are not context-aware and AFAIK, there is no way at the moment to do what you want. This has been a feature request since 2008, but the proposed patch didn't make it into Drupal 7.

If this is very important to the site you're building, you can consider patching Drupal core. However, once Drupal core is patched, you will need to take extra care (and time) when updating your site.


Alternate webform UI is buggy I have been experimenting with the Webform Alternate UI module for Drupal Webforms. As you would know it requires a few excess modules like options_element, ux element and form builder. The thing is, the webform alternate UI shows up but it does not really work when I attempt to drag and drop the form fields onto it. Its' clearly buggy. And it seems like it has some unfixed issues persistent along with it.

I want to check on stackoverflow with anyone who has played along with the webform Alternate UI and found it to be buggy and has a fix for it?

Thanks much

I have found Webform Alternate UI to be quite buggy as well and have opted to use just the Form Builder module by itself, which gives a good UI for users to build forms (and is not buggy).


Is there any way to run hook_form_alter based on a form ’s class instead of it’s ID? Is there any way to run a hook_form_alter based on a form ’s class instead of it’s ID?

I have a class of commerce products and am needing to do form alterations on their add to cart forms. There are too many of them to do this using their form id’s.

Pseudo code might be:

function  theme_form_alter(&$form, &$form_state, $form_class) {
    //code goes here
    }

No - forms are only referred to by their ID (or 'base ID'), which is essentially the name of the function that defines them, or generally speaking, closely related to it.

So if you have

function MYMODULE_some_form($form, &$form_state) {
  // ...
}

Then the ID of that form is MYMODULE_some_form. It's not related to the HTML ID attribute, in case that's what you're thinking, so there's no class equivalent.


Is there any way to get only the custom roles? I would like a list of all custom roles.
Currently I am loading all of them using

$roles = $this->entityManager->getStorage('user_role')->loadMultiple();

but am wondering if there is any function that only brings the custom ones besides manually creating a static filter for the Anonymous, Authenticated and Administrator.

As @stevekeiretsu said in a comment ->

The Role entity doesn't really make any distinction. Looking at the roles in my own db (filter config table by name LIKE user.role%) the only potential contender I can see is that the three default ones have a dependency on _core, so you could check that via getDependencies, but that feels arguably flakier than a static filter to me.

So for Drupal 8 there is no function defined.


Views: Page by view-group where multiple results are loaded under each group from a relationship I have a view displaying data as follows:

Course name 1

Course instance a
Course instance b

Course name 2

Course instance a
Course instance b
Course instance c
Course instance d

Course name 3

Course instance a
Course instance b
Course instance c
Course instance d

The view is grouped by Course name, and there's a relationship with the course instance table to bring in the course's course instance.

The pager is set to 10, but the list displays 10 course instances. How can I get it to display 10 Course names, with all of their instances underneath.

One possible solution would be to use the Views Field View module.

You can make a view that displays course instances as an unordered list, with a contextual filter that is the parent course nid.

Then create a view of courses, limited to 10, and add a view field to the view, using the first view you made. You can pass in the course nid as the contextual filter, so that field just displays the result of the first view for that particular course.


How to find out what modules are adding links to a menu? I was wondering if there's any way to find out what modules are adding links to what menus using hook_menu()? I don't care if it's a module or custom code added to Drupal core, I just need to know. There's a link showing up in my main menu and I have no idea what's putting it there. I'd really rather not go through every single module and check their menu hooks.

You're after module_implements(). It will allow you to specify the hook (in this case 'menu') and then get an array of module names back.
Of course, you'll still need to manually open the files to check, but you should be able to narrow it down from the menu path and title.

It might be worth flushing the caches too.


Jquery version issues: Flexslider doesn't works only with 1.5 and bootstrap needs 1.8+ This is my site: investassure and I tried incorporating the code for 'button dropdown' from bootstrap. This works only with jquery-1.8+ but the flexslider I used works ONLY with 1.5. As a result, I'm getting this error:

 Uncaught TypeError: Object [object Object] has no method 'on'

I tried using jquery_update, didn't work. There is only one version added on the page right now, which is 1.5. I didn't find a version of flexslider which works with version 1.7+. What else can I do?

I recommend the jQuery Multi module.

It allows you to use the default drupal jQuery version for most of you site, and use newer versions of jQuery just for plugins that require it.

It gives an administration page where you can choose which libraries to load using the newer jQuery.

It also has hooks you can use to tell it to load your libraries using different jQuery versions.

If you are writing custom js it also namespaces the jquery versions so you can do something like:

(function ($) {
  // All your code here
})(jq172);

That is how the module would namespace jQuery 1.7.2 and you can load your scripts like that to use the newer versions.

One thing to note is that if your plugins with new jQuery require things like jquery UI, jquery.once etc., that drupal core uses already, you have to make sure they are added a second time, so they are added to the normal drupal jquery and the newer one.


How can I make revision log message required based on revision checkbox by node_form_alter? My goal is to make the "revision log message" required if "Create new revision" is checked on create/edit node.

I do able to add the visible and required mark based on the "create new revision" field.

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

  $form['revision_information']['log']['#states'] = [
    'required' => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
    'visible'  => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
  ];
}

I also able to make the "revision log message" as required.

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

  $form['revision_information']['log']['#required'] = [
    'required' => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
  ];
}

But I don't know how to make the field required based on the "create new revision" checkbox.

PS: I want to make this simple and don't want to use the "Enforce revision log message" module.

// update 1: I found it require a custom hook validate and Im searching for it

I found an answer after hours of searching. Basically, I just need to add a custom hook validation for revision log. See below for my code.

function MYMODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
    // change revision log status based on revision checkbox
    $form['revision_information']['log']['#states'] = array(
        'required' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
        'visible' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
    );
}
function MYMODULENAME_node_validate($node, $form, &$form_state) {
    // add revision log validation
    if (empty($form_state['values']['log']) && ($form_state['values']['revision'])) {
        form_set_error('log', 'Revision log message cannot be empty!');
    }
}

I hope this helps someone who needs revision log message required.


Simple way to add a class to the body when creating/editing an entity In Drupal 8.4, I am trying to add a class to the body (like Drupal 7 had) when the page viewed is a node (or entity for that matter), something like [entity]-[create or edit], so that, when a user is editing or creating a node, a class like page-node-edit gets added to the body classes array.

You can use hook_preprocess_page and check the current route:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  // This would add a class based on the route.  You'd need the
  // pathauto module enabled.
  $vars['page_classes'][] = \Drupal::service('pathauto.alias_cleaner')->cleanString($route_name);

  // This would add the classes asked for in the question.
  if ($route_name == 'entity.node.edit_form') {
    $vars['page_classes'][] = 'entity-edit';
  }
  elseif ($route_name == 'node.add') {
    $vars['page_classes'][] = 'entity-create';
  }
}


Javascript calander to pick contents on a particular date Is there any module available in drupal which can be used to pick a date and afterwards contents from a particular content type can be displayed ?

You can get this sort of functionality with the very powerful FullCalendar module. It provides extensions to Views enabling you to build complex calendars displaying content, users, and basically anything else a View can display.


Public and Private file system path is the same My company inherited a Drupal 7 site that may not have been properly set up. For example I recently noticed that under Configuration, File System, the "Public file system path" and the "Private file system path" have the same path:

sites/default/files

I'm just wondering what the repercussions might be if I suddenly changed the private files to

sites/default/files/private

Is it too late for this, since there might be sensitive private files already there that can't just be moved because they're registered in the database? I haven't looked too closely at the files yet.

Thanks

The private files path should always be outside the webroot directory since users can directly access all those files through just adding /sites/default/files/private/.. to your URL. Private files means that they are delivered through Drupal to add some access permissions.

What you should do now:

Backup your databse and put your site into maintenance.
Go to your files_managed table and find all files stored as private files.
Move those files to a new directory outside your webroot.
Change your private files path to the new path and test if everything is working.


Cart page content in simple block in ubercart 3 Can i use http://www.mysite.com/cart page content in simple block using ubercart 3 in drupal 7? I want same http://www.mysite.com/cart page content area ("cart form") in a simple block for show cart content in any region to authenticated user.

Thanks

There is a module Ubercart pictured cart block which will display the content of the cart page into a block. It will provide all functionality which are cart page. You can set the block in a region from block administration page in admin.


How to alter cck field title using hook_form_alter? I want to change #weight, #prefix, #title for a cck field.

First I tried the following code.

function test_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    //Working
    $form['field_test1']['#weight'] = -5;
    $form['field_test1']['#prefix'] = 'This text will rule them all!';

    //Not working
    $form['field_test1']['#title'] =  'test title';
    $form['field_test1']['und']['#title'] = 'test title';
    $form['field_test1']['und'][0]['#title'] = 'test title';
}

It is working good with #weight, #prefix elements.

//Working
$form['field_test1']['#weight'] = -5;
$form['field_test1']['#prefix'] = 'This text will rule them all!';

But not working for #title element in anyways.

$form['field_test1']['#title'] =  'test title'; //Not working
$form['field_test1']['und']['#title'] = 'test title'; //Not working
$form['field_test1']['und'][0]['#title'] = 'test title'; //Not working

I tried with #after_build as well but no luck.

function test_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    $form['#after_build'][] = 'test_after_build';
}
function test_after_build($form, &$form_state) {
    //Working
    $form['field_test1']['#weight'] = -5;
    $form['field_test1']['#prefix'] = 'This text will rule them all!';

    $form['field_test1']['#title'] =  'test title'; //Not working
    $form['field_test1']['und']['#title'] = 'test title'; //Not working
    $form['field_test1']['und'][0]['#title'] = 'test title'; //Not working

    return $form;
}

Please give me the solution for alter cck field title through form_alter.

Thanks in advance,
Logan

First, you may check the exact field array with dsm()

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

In the result returned by dsm(),  #title is set in 2 places. So just try :

$form['field_bibliographie']['#title']= t('Foo');//doesn't work
$form['field_bibliographie']['und'][0]['#title']= t('Foo');//correct one

I see no reason for which it would not take the correct value if you set the exact field array


How can I name the template file for the edit page of a certain content type? I would like to override only the edit page of a certain content type.
Theme developer module says:

page-"content_type".tpl.php < page-node-edit.tpl.php < page-node-"nid".tpl.php < page-node.tpl.php < page.tpl.php

If I use page-"content_type".tpl.php, it also overrides the node view page and if I use page-node-edit.tpl.php it overrides the edit page of all content types.

Update:
I tried the code below, and put it in my template.php but it doesn't work.

function my_theme_preprocess_page(&$vars) {
 if (isset($vars['node'])) {
   $edit_or_add=basename($_GET['q']);
    if ($edit_or_add=='edit' || $edit_or_add=='add') {
      $vars['template_files'][]='page-' . str_replace('_','-',$vars['node']->type . '-' . $edit_or_add);
    }
    else {
      $vars['template_files'][]='page-' . str_replace('_','-',$vars['node']->type);
    }
  }
}

function my_theme_name_theme($existing, $type, $theme, $path) {
  return array(
    'story_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'node-story-edit'
    )
  );
}

This code from here worked for me, for example for the story content type.


Properly merge array values We have the following mymodule_preprocess_node hook where we add two arrays with two key-value pairs. In twig, we would like to merge the values.

How would we merge the two arrays in twig?

Here is what we tried.

mymodule_preprocess_node

function mymodule_preprocess_node(&$variables) {
  // perform some logic.

  $variables['content']['ary']['foo'] = 'foo_value';
  $variables['content']['ary']['bar'] = 'bar_value';
}

node--article.html.twig

{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

This results in twigAry only having the following. It basically prints the last key and value, which is bar and bar_value. Strangely enough, instead of setting the key to bar it results in the key being key.

[
  'key' => 'bar_value'
]

Desired Output

[
  'foo' => 'foo_value`,
  'bar' => 'bar_value',
]

In the twig template, we are adding an inline <script> tag that needs to have the array in the desired output as such we need to have in this format in twig. For example, when we load the Marketo form, we want to set some values like this. Rather than hardcoding items in twig, we will just use the ['foo'] and ['bar'] from the preprocess method.

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Set the value of the Phone and Country fields
    form.vals({ "Phone":"555-555-1234", "Country":"USA"});
});

Final twig:

{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
  // Set the value of the Phone and Country fields
  form.vals({ twigAry });
});

Associative arrays must use curly brackets in Twig:

{% set twigAry = {} %}

Arrays with square brackets [] defined in Twig don't have key names


Repeating group names in Pathauto path My pathauto patterns are giving me trouble with organic groups. All books are contained within groups.

Book_main_page shows as:

  Group_name/Book_main_page

A child of Book_main_page shows as:

  Group_name/Group_name/Book_main_page/Child

A child of the child page shows as:

  Group_name/Group_name/Group_name/Book_main_page/Child/Child_of_child

How do I get rid of the repeated group names?

The group content type "book page" has a "Pattern for all Book page paths" of:

  [node:og-group-ref]/[node:book:parent:url:path]/[node:book:title]

The group type "Group" has a "Pattern for all Group Paths" of:

  [node:og-group-ref]/[node:title]

My page uses one group content type "book page" (from the books module) and one group type "group".

For the "book page" content type, try using the path:

[node:og-group-ref:title]/[node:book:parents:join-path]/[node:book:title]


How do I restrict GraphQL access with Basic Auth? According to this Gitbook (near the bottom), its possible to require GraphQL query authentication with Drupal Core's Basic Auth module. This allows GraphQL to authenticate against a user stored in the Drupal DB.
https://drupal-graphql.gitbook.io/graphql/authentication/authentication
I created an event subscriber that adds the Basic Auth option to the route like this:
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('graphql.query.default:default')) {
      $route->setOptions(['_auth' => ['basic_auth']]);
    }
  }
}

However, when I make a curl request without an Authorization header it still goes through:
curl -X POST -H "Content-Type: application/json"   --data '{"query":"{fileById(id: \"33\") {changed}}","variables":null,"operationName":null}' http://MYLOCALHOST/graphql

Response:
{"data":{"fileById":{"changed":1572374455}}}

I did enable my custom module with the RouteSubscriber information above and also the Basic Auth module. When I visit the /graphql Drupal path in a browser, access is denied but when I make the CURL request it goes through. I was hoping to restrict CURL access as well.
Here is the Drupal 8 documentation on Basic Auth:
https://www.drupal.org/docs/8/core/modules/basic_auth/overview
I am using v3 of the Drupal 8 GraphQL module.

I got it!
I needed to add
$route->setRequirements(['_user_is_logged_in' => 'TRUE']);

...And then do the curl request with the username and password.


How do I remove the authoring information? I want to publish some static pages, but when I try they always show the publishing date and author, which makes them look more like a blogs.

I have looked at a way to disable the feature "authoring information" for this page, but the best I can find is how to make it anon, which is not what I want either.

The content types I have on the site are:

Article
Basic page
Blog entry
Book page
Forum topic
Poll

The theme I am using is Bartik 7.15, if that makes any difference.

You can disable it for each content type, going on admin/structure/types/manage/<content type> (e.g. admin/structure/types/manage/article for the Article content type).

What you are looking for is in the "Display settings" tab visible at the bottom of the settings page.


Print rendered field in views-view.html.twig I try to render a custom node field in a views-view.html.twig and it works, the only thing is that i get the machine name and not the formatted name. Please can somebody describe me what i am doing wrong?

I have tried several ways like:

{{ view.field.field_my_field.value(view.result[0]) | render }}

or

{{ view.field.field_my_field.value(view.result[0]) }}

Thanks for helping!

this does get the value

{{ view.field.field_my_field.value(view.result[0]) }}


Import xml with Feeds module. Only one value is imported I have a xml (http://pastebin.com/q64L3ECX) that I need to import with Feeds module into my site. Basically, with this xml example, I need to import 3 nodes where my GUID (set as unique) is "test_case". Each test_case is inside a test_set.

The problem is that I can only get the first test_case of each of the two test_set of that file. Can someone help me understand what is wrong?

Debug output:

xpathparser:0 :
<test_set_name tl_label="Name" tl_name="name" tl_physicalname="CY_CYCLE">GUI.00 Launch Applications</test_set_name>
<test_set_name tl_label="Name" tl_name="name" tl_physicalname="CY_CYCLE">GUI.02 EM NE.000 EM NE Generic.Generic EM NE tests</test_set_name>
xpathparser:1 :
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">Launch TNMS</test_case_name>
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">Open</test_case_name>
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">ManualNetworkScan</test_case_name>

Created 1 node.

For example, our relation's key will be test case's GUID (Test cases (Entity reference by Feeds GUID) (field_test_cases)):

Content type test_set:

field_test_cases: Type - Entity Reference, Target type - Test case
(type test_case), Number of values - unlimited.

Content type test_case: standard Title and Body fields.

Test case's importer's config:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_cases';
$feeds_importer->config = array(
  'name' => 'Test cases',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'text()',
        'xpathparser:1' => 'text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
      ),
      'context' => '/report/test_sets/test_set/test_cases/test_case/test_case_name',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_case',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

Test set's importer's config:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_set';
$feeds_importer->config = array(
  'name' => 'Test set',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'test_set_name/text()',
        'xpathparser:1' => 'test_set_name/text()',
        'xpathparser:2' => 'test_cases/test_case/test_case_name/text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
        'xpathparser:2' => 0,
      ),
      'context' => '/report/test_sets/test_set',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
          'xpathparser:2' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
        2 => array(
          'source' => 'xpathparser:2',
          'target' => 'field_test_cases',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_set',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);


Are there any pitfalls pointing config sync to profile's config/install? Is this good practice? I have pointed my config sync to:

$config_directories['sync'] = 'profiles/PROFILENAME/config/install';

Experiments with drush cex have worked, allowing a cycle of UI changes, config export, and re-installation with the new changes.

We will not be going live with D8 for a while, so the team's plan is to use this method to gain familiarity with the config system and other parts of D8 using this simple method.

No, I don't think that is a good idea. default configuration is something else than the config sync folder. For example exported config has a UUID and system.site has a site UUID while default config shouldn't.

They are two different use cases. default config is for installing new sites and the config export is to deploy configuration between different installations of the same site.

What you might want to look into is https://www.drupal.org/project/config_installer, a simple installer that allows to install based on an config export/sync folder.


presave like option for adding vocabulary and terms similar to one provided by hook_nodeapi I'm a Drupal newbie and trying to customize the 'Add Vocabulary' and 'Add Term' provided by taxonomy using a module named Domain Taxonomy.

To customize it as per my own requirement I'm gonna have to insert the domain specific data when the term is saved without messing up over the existing code provided by domain taxonomy rather wish to override it.

I'm looking for a hook similar to hook_nodeapi where in '$op == presave' after validations and before saving node it can be customized with user added data.

To my understanding hook_nodeapi doesn't apply for stuff like taxonomy or user profile. Does something similar exist for taxonomy that i could put to use here. Kindly let me know if my understanding is flawed and provide valueable comments/feedbacks and possible solution.

You can add a validation function to the form in hook_form_alter(). If you give your module a high weight, that validation function will be added last to the validation functions array and thus be executed last. The validation function can call form_get_errors to check whether errors occurred. If no errors occurred, you can be pretty sure that the vocabulary or term will be saved to the database, making it something like hook_nodeapi($op = presave').

Note that you cannot use hook_form_FORM_ID_alter(), because these hooks are executed before hook_form_alter(). Also, I found no easy way to react on the installation of other modules.


Choosing which comments field to display when published I'm using the basic comment module to allow users to leave comments (name, phone, email, comment, and rating) on each resource for that specific comment type. One of the fields is an option to allow users to choose to share their personal information to others if they want. All comments are unpublished by default and have to be moderated to be published.

So, my question is this: how can I selectively choose to publish a users email or not depending on if they selected to share that information with others?

Either a manual or automatic way would work fine. Thanks!

You could use the template_preprocess_comment function. First you need to check the value of the "share my personal information" field or whatever you called it and act on that to display the user's email.


Rules - Set language of message notification We need to set up a rule that will send an email in the language of the Customer of an order LANGUAGE.

But the Message notify action in rules takes the CURRENT user interface language... so that might be fr or en, depending on the path in fact. The recipient language might be different.

1-Can you tell me what selectors I should use to set the mail language to the customer language? I guess I need to change some kine of data-value?

2-And maybe you can point how I can easily find this in the future. Would DEVEL help? Something else?

thanks!

Consider investigating if the patch in comment #3 of issue # 1472316 might be of any help. Even though it is not the exact same question here, it may help to find inspiration about how to answer your question.

For more details about this issue, visit the question about  "Rule condition to check which language is used by the visitor?".


What's the correct way to add attributes to a Link field? So I'm preprocessing a field: preprocess_field and trying to add attributes to a Link. I've tried:

      $variables['items'][0]['attributes']['target'] = '_blank';
      $variables['attributes']['target'] = '_blank';
      $variables['#attributes']['target'] = '_blank';
      $variables['content_attributes']['target'] = '_blank';
      $variables['content_attributes']['attributes']['target'] = '_blank';
      $variables['items'][0]['#attributes']['target'] = '_blank';
      $variables['items'][0]['options']['attributes']['target'] = '_blank';
      $variables['items'][0]['#options']['attributes']['target'] = '_blank';
      $variables['items'][0]['#options']['target'] = '_blank';
      $variables['items'][0]['#content']['#options']['attributes']['target'] = '_blank';
      $variables['items'][0]['#content']['options']['attributes']['target'] = '_blank';
      $variables['items'][0]['#options']['attributes']['target'] = '_blank';

A silly amount of attempts, none of these worked. How can I add attributes to a link?

There were some close ones, but this is the correct way to set an attribute to the first link:

function mymodule_preprocess_field(&$variables) {
  if ($variables['field_type'] == 'link') {
    $variables['items']['0']['content']['#attributes']['target'] = '_blank';
  }
}


How to use a content type form as a block I need a page to be half content, half node edit form.
How can I do this? I thought I'd put the content type's form display into a block. Sounds easy enough.
I've been trying contrib and custom modules, but I can't seem to grab the form.
Thought I could get away with something like this.
class EvaluationBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $render_array = EntityFormDisplay::collectRenderDisplay($node, 'project_evaluation_form');
      // error_log($render_array);
      return $render_array;
    }
  }
}

Thanks to the comments above, the working module code is here:
project_evaluation_form_block.module
<?php
/**
 * @file
 */
 function project_evaluation_form_block_entity_type_build(array &$entity_types) {
   $entity_types['node']->setFormClass('project_evaluation_form', 'Drupal\node\NodeForm');
 }

src/Plugin/Block/EvaluationBlock.php
<?php
/**
 * @file
 * Contains \Drupal\article\Plugin\Block\EvaluationBlock.
 */

namespace Drupal\project_evaluation_form_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;

/**
 * Provides an 'evaluation' block.
 *
 * @Block(
 *   id = "evaluation_form_block",
 *   admin_label = @Translation("Evaluation form block"),
 *   category = @Translation("Evaluation form block test")
 * )
 */
class EvaluationBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    $edit_form = \Drupal::entityTypeManager()->getFormObject('node', 'project_evaluation_form')->setEntity($node);
    return \Drupal::formBuilder()->getForm($edit_form);
  }
}

Had to adjust the submission settings for the content type to have the save button appear.
And with this, I am able to add this form as a block to a page.


How to add order status to commerce_line_item_table view in same way as in the commerce_user_orders view? I am trying to add user's order status to commerce_line_item_table view same as it is present in commerce_user_orders view. When user click on order no in commerce_user_orders view and it goes to commerce_line_item_table view here the order status is not present i want to add order status in this view. Any Help please

Well, you can add the Commerce Order: Order ID relationship to the view and then add the Commerce Order: Order status field and it'll provide the line item's order's status in the view.

Add the relationship:

Then, add the field:

Now, your view will have order status on the line items:


How do I find services? What is the best way to find right service for dependency injection? Googling is not efficient yet. For example I spent quite long time figuring out that if I need current request passed to constructor by DI I have too use: $container->get('request_stack')->getCurrentRequest()

Full code example:

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

And I've found above example in drupal class Documentation

Before that I've just found this
services list
but there is no description, no examples, nothing. Just a list with possibility to search.

How do you search for right service provider?

A better way to accomplish this is to use the Drupal Console's  container:debug command. This command outputs a list of Drupal service ID's and its corresponding namespace & class.

$drupal container:debug

 Service ID                 Class Name
 class_loader               Symfony\Component\ClassLoader\ApcClassLoader
 kernel                     Drupal\Core\DrupalKernel
 service_container          Drupal\Core\DependencyInjection\Container
 cache_context.ip           Drupal\Core\Cache\Context\IpCacheContext
 cache_context.headers      Drupal\Core\Cache\Context\HeadersCacheContext
 cache_context.cookies      Drupal\Core\Cache\Context\CookiesCacheContext
 ...

This command can be employed along with grep to search for a specific class name or service ID. For example: drupal container:debug | ag 'DatabaseStorage' to find a DatabaseStorage class.

Also of interest is the PhpStorm / IntelliJ Drupal Symfony Bridge plugin if you use PHPStorm.


Entity Field Query OR condition,between node title and a custom field I am executing a query for searching in the node title and a field using LIKE.How do I use the OR condition?
`function hook_somefunction($keys) {
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'product_display_one');
  //$query->addTag('customproductstag');
  $query->addMetaData('keys', $keys);

//both conditions below are working fine individually ,but I need to use OR in between them
  //$query->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE');
  //$query->propertyCondition('title',$keys .'%', 'LIKE');
  $result = $query->execute();
  return $result;
}

//This part below is not working
function hook_query_customproductstag_alter(QueryAlterableInterface $query) {
  $keys = $query->getMetaData('keys');
  $or = db_or()
    ->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE')
    ->propertyCondition('title','%'.$keys .'%', 'LIKE');

$query->condition($or);
}  `

Thanks.

`
function hook_query_customproductstag_alter(QueryAlterableInterface $query) {
  $keys = $query->getMetaData('keys');
  $or = db_or()
    //->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE')
    //->propertyCondition('title','%'.$keys .'%', 'LIKE');
    ->condition('usage.field_usage_number_value', '%' . db_like($keys) . '%', 'LIKE')
    ->condition('node.title', '%' . db_like($keys) . '%', 'LIKE');

$query->condition($or);
}  `

fieldCondition didn't work because db_or is not a part of entity query.


edit content on content's language I have a couple of nodes (using node translation) shown on /en/admin/content. All the edit links point to /en/node/*/edit which always has the English language on the URL. This is problematic because for French items the entityreference fields show English nodes and not French. In order to solve this I have to manually edit the URL to /fr/node/*/edit.

The same applies when initially translating a node. The "add translation" link at /en/node/*/translate always starts with /en/.... If it'd start with the target language (e.g /fr/...) then this problem with the entityreference fields would not exist.

Is this a problem of entityreference or Drupal? Can it be fixed or configured from somewhere?

The edit links where fixed in i18n 7.x-1.6. When I crated this issue I was using 7.x-1.5.

http://drupal.org/node/1649596


Userpoints: deduct points programmatically Is there a way to programmatically deduct points from user points?

I want to deduct points from users if a certain "featured Item" field is checked when they create a new content, but don't want to deduct points from users that created content without "featured Item" checked.

You can use userpoints_userpointsapi and pass points in negative if you want to deduct.

example

    $params = array(
      'uid' => $user->uid,
      'points' => -5,
      'operation' => 'mymodule_some_operation',
    );
    userpoints_userpointsapi($params);

For more information http://drupal.org/node/993376  http://api.worldempire.ch/api/userpoints/userpoints-7.x-1.x%21userpoints.module/function/userpoints_userpointsapi/7-1


Does drupal_add_css not load duplicate filenames by design? If I try to add a css file using drupal_add_css to a custom module where there is already a css file loaded with the same name elsewhere (in my case in the theme, based on Zen), the module version does not load at all. Nothing to do with overriding styles - the two files contain completely different style information. If I change the filename in the custom module to something else which does not conflict, it loads correctly.

The question is is this by design? If not, is it a known bug? In my opinion this should not happen as a module developer has no idea what css files will be called in any custom theme.

Looking at the drupal_add_css() function, it seems this behaviour is by design.

For any CSS that you add using the function without using 'inline' as an argument, the array of files is keyed by the first argument (string) that you pass in. So if you were to run:

drupal_add_css('file.css');

And another module has also called drupal_add_css() with the same file name, the original will be overwritten.

As Marius Illie mentions in a comment above, the best way to avoid this is to prefix any CSS files you add with your module name.


Programmatically create a node with alias and menu item using Entity API I've seen the excellent documentation on Drupal.org about how to create a node in code, but that documentation doesn't address how to create the node's alias.  I've seen code snippets that use $node->path; and $node->menu with node_save($node); which works, but with $entity->path->set(); or with $entity->menu->set(); I'm receiving the following error message:

  Unknown data property path.
  Unknown data property menu.

Why does this not work with entity api and how can I modify my code (below) to make it work?

<?php
/**
 * Testing programatic content creation.
 */
function mymodule_update_7000() {
  $about = _create_node_and_menu_item('About', 'about', 'main-menu', 'About the site');
  dpm($about);
}

/**
 * Helper function creates a node, with alias, and menu item, and
 * returns the mlid.
 * @param  string  $title      the title of the node
 * @param  string  $alias      the URL alias
 * @param  string  $menu_name  the machine name of the menu, eg 'main-menu'
 * @param  string  $menu_title the title of the menu item, if none is
 *                             provide, the $title will be used.
 * @param  integer $plid       the numeric id of the parent menu item
 *                             (defaults to 0).
 * @param  integer $uid        the numeric user id (defaults to 1)
 * @param  string  $body       the body copy to use on the node, defaults
 *                             to lorem ipsum.
 * @return Entity              the node entity object that was created.
 */
function _create_node_and_menu_item($title, $alias, $menu_name = '', $menu_title = '', $plid = 0, $uid = 1, $body = '') {
  if (!$body) {
    $body = '
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus
';
  }
  $node = entity_create('node', array(
    'type' => 'page',
    'uid' => $uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  ));

  // Get a wrapper for adding meta-data.
  $entity = entity_metadata_wrapper('node', $node);
  // Using the wrapper, we do not have to worry about telling Drupal
  // what language we are using. The Entity API handles that for us.
  $entity->title->set($title);
  $entity->body->set(array('value' => $body));

  if ($alias) {
    // FIXME this line is broken :'(
    $entity->path->set(array('alias' => $alias));
  }
  if ($menu_name) {
    if (!$menu_title) {
      $menu_title = $title;
    }
    // FIXME this line is broken :'(
    $entity->menu->set(array(
      'link_title' => $menu_title,
      'menu_name' => $menu_name,
      'plid' => 0,
      'enabled' => 1,
    ));
  }
  // Save the entity and its meta-data.
  $entity->save();
  return $entity;
}

I realize there are other ways to create a path using path_save(), but this is predicated on knowing the node id first.  A valid answer here would show how to do this purely with Entity API and one call to $entity->save(). Is it possible?

I would suggest that you use the node_save() and have a $node->path set to create the desired path alias, rather than using $entity->save() because if inspect (via dpm()) the output of an entity_load() of a node, you would see nothing there related to the node's path alias.

Of course you could use $entity->save() > then fetch the node/entity id > and then use [path_save()][1] too.


How to filter groups of paired values in Views I have a Field Collection field in a node. The field collection has two fields, so I can associate a group of paired values to a node. For example, {a,1}, {b,2},{c,3},{d,4}.

I have a View in which I want to filter by the values above. If I use a filter for the first type of values and put a, it will return the first 2-tuple. If I put 2 in the second filter (and nothing in first filter), it will return the second 2-tuple. But if I look for c in first filter and 4 in the second filter simoultaneously, it will return the 2 last values, because c matches the condition and 4 matches the condition, separatedly. How can I make  the View filter so I get the desired result, which is empty result in this case?

I am not able to reproduce the behavior you describe. In configuring a Field Collections and Views in the way you describe I do get the desired results.

Here is a screenshot of my configuration:

And here are the results:

And here is the filtering:

By letter:

By number:

Mismatched letter/number yields no results:

And here is the full View export:

$view = new view();
$view->name = 'stacktest_fieldcollection';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'stacktest_fieldcollection';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'stacktest_fieldcollection';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Content: FC (field_fc) */
$handler->display->display_options['relationships']['field_fc_value']['id'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['table'] = 'field_data_field_fc';
$handler->display->display_options['relationships']['field_fc_value']['field'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['required'] = TRUE;
$handler->display->display_options['relationships']['field_fc_value']['delta'] = '-1';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Field collection item: Letter */
$handler->display->display_options['fields']['field_letter']['id'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['table'] = 'field_data_field_letter';
$handler->display->display_options['fields']['field_letter']['field'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['relationship'] = 'field_fc_value';
/* Field: Field collection item: Number */
$handler->display->display_options['fields']['field_number']['id'] = 'field_number';
$handler->display->display_options['fields']['field_number']['table'] = 'field_data_field_number';
$handler->display->display_options['fields']['field_number']['field'] = 'field_number';
$handler->display->display_options['fields']['field_number']['relationship'] = 'field_fc_value';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Contextual filter: Field collection item: Letter (field_letter) */
$handler->display->display_options['arguments']['field_letter_value']['id'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['table'] = 'field_data_field_letter';
$handler->display->display_options['arguments']['field_letter_value']['field'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_letter_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_letter_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_letter_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_letter_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_letter_value']['limit'] = '0';
/* Contextual filter: Field collection item: Number (field_number) */
$handler->display->display_options['arguments']['field_number_value']['id'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['table'] = 'field_data_field_number';
$handler->display->display_options['arguments']['field_number_value']['field'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_number_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_number_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_number_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_number_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_number_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'stacktest-fieldcollection';


What is the process to upload custom drupal themes to Drupal.org? What is relevance of "PayWithPaytm"? I am new to this community, so apologies in advance for some ignorance.

I know there are forums, chat channels, ect, so I also apologize if this is the wrong medium for such questions.

Basically, I want join the community by building my own Drupal Theme and eventually upload it to Drupal.org for other users to download and use if they wish.

I went to my dashboard on Drupal.org where there are tabs for "Your Projects" and "Your Commits" and such, but commits is just a blank page, and projects is empty but with a message "To learn about projects, see Contributing code on Drupal.org.".

Clicking this hyperlink goes to this page: https://www.drupal.org/contribute-projects .

So my confusion starts here. What does this e-commerce payment gateway plugin have to do with contributing code? I downloaded it, the readme mentions nothing. Under the download option, there begins the info I need (like how to create a sandbox project and eventually

So what does that PayWithPaytm plugin have to do with anything? Do users need to pay Drupal to create a project or something? Why does the "learn about contributing" link go to an e-commerce plugin?

Below is a screenshot of my dashboard and the link to PayWithPaytm.

The Drupal community pages are basically a Wiki done in Drupal.  As such, anyone can get authorized to make changes.  However, like a Wiki, people can add spam like this.  This page was spammed today.

I've reverted the page back to the last revision so it should now be helpful.

Welcome to Drupal.


Make a password security check for the register form I have a register form that is output in a controller using the following code.

 $form = $this->getUserProfileForm();

    return [
      '#theme' => 'maubl_user_inscription',
      '#form' => $form,
    ];
  }

  protected function getUserProfileForm() {
    $entity = \Drupal::service('entity.manager')
      ->getStorage('user')
      ->create(array());

    $formObject = \Drupal::service('entity.manager')
      ->getFormObject('user', 'default')
      ->setEntity($entity);

    $form = \Drupal::formBuilder()->getForm($formObject);

    return $form;
  }

In a custom module, I'm using the following code to alter the password.

function maubl_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $formState) {
  $form['actions']['submit']['#submit'][] = 'maubl_user_form_login_after_registration';
  $form['account']['pass']['#process'][] = 'maubl_user_form_user_register_form_process_pass';
}

function maubl_user_form_user_register_form_process_pass(&$element, \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form) {
  $element = \Drupal\Core\Render\Element\PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password');
  $element['pass2']['#placeholder']= t('Confirm pwd');
}

Yet, any password would be accepted as long as they are the same. I want something like password_confirm to check if there are special characters, special length etc, but I couldn't figure out how to make it works.

When I try to use the following code, nothing happens.

function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['pass']['#process'][] = 'mymodule_form_user_register_form_process_pass';
}

It seems like you might want to look into the Password Policy module which probably has a lot of the features you are trying to rebuild.

I also wonder whether it makes sense to build your own user inscription form instead of altering the existing core registration form. Altering forms tends to result in easier integrations with existing modules.


Fix Faq Ask Email Layout Question I am using FAQ Ask along with the FAQ module. Everything works well but the emails are coming all bunched up. I need to be able to re-arrange the layout as I want (simple text with active links).

Below is what I see:

These emails are assembled in the faq_ask_mail function (faq_ask,nodule, line 1013). The body is assembled beginning at line 1077.

If you wish to open up the body, you can go in and include some newline ('\n') characters into the text.

Since this hacks the module core, perhaps you should submit a patch as a feature request.

EDIT:

faq_ask_mail is an implementation of hook_mail. You can define your own hook_mail in a custom module to override the output. You must, however, adjust the weight of your custom module so it is processed after the faq_ask module. You would handle it as follows:

function MYMODULE_mail(&$key, &$message, &$params) {
  $body = $message['body'];
  switch ($key) {
    case 'notify_expert':
    case 'notify_asker' :
      /*** Change the formatting of $body ***/
      $body = str_replace("\.", "\.\n\n", $body);
      break;
  }
  $message['body'] = $body;
}

Remember that this will have no effect if it is executed before the faq_ask_mail function.


Show content as per Taxonomy Term I am new to drupal and using drupal 7. I have created some taxonomies and using it as menus using Taxonomy Menu module. The Taxonomies are being shown as menus.

Now I want to change content of the page as per term of the taxonomy. I have searched the problem but found different modules doing this task like Taxonomy Display, Taxonomy Menu Block. But I don't want  to use any of the module and want to do it manually so that I can understand the inner working of Drupal themes.

Any help will be much appreciated.

You can do this by Views:

Create view of block type (admin/structure/views)
Add fields want to display on term page.
Go to "Contextual filters" settings under "Advanced" tab.
Add the filters: "Content: Has taxonomy term ID (with depth)" and "Content: Has taxonomy term ID depth modifier". You can configure this on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." → now check the boxes of the taxonomies you want involved here.
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid.
Chosse the option "when argument is not present" to "Provide default argument".
Choose the "Default argument type" to "Content ID from URL".
Go to "MORE" , and check the "Exclude" box.
Move the filter "Content: Nid" to the top position.
Add a block to your view and embed the block on your node pages.
Save your view


Triggering an action after user resets password? I was hoping there was hook_user_pass_reset, but I seem to be out of luck. Some background:

I made a new field on users called "email_confirmed"
This field gets set = 1 when the user has confirmed their email address
I don't use the "blocked" value, or the normal Drupal way, because I want users to still log in and do stuff. I only want to limit certain actions, which will only become possible after email_confirmed = 1

So all I want to do is update this field = 1, the moment the user uses the confirmation link to change their password. So it will not be good enough to this when the user changes his password. It needs to happen the moment the user has executed the confirmation link?

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function MODULE_user_update(Drupal\user\UserInterface $user) {
  if (!empty($user->original)) { // check previous value exists
    if($user->original->pass->value != $user->pass->value) { // check if pass changed
      $user->field_email_confirmed->value = 1; // set new value
    }
  }
}


How do I programmatically get the URL of an entity referenced media image field using on a custom_preprocess_html() hook on THEME.theme? Reason: I need to create an Open graph meta tag og:image and pass the URL as content.

On THEME_preprocess_html(), I loaded the node using

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
      $nid = $node->id();
      if($node->hasField('field_image')){
        $image_id = $node->field_image->target_id;
        $image = \Drupal::entityTypeManager()->getStorage('file')->load($image_id);
      }
}

I have loaded the node and I was able to get the field_image_entity_id as shown. I want to get the URL of the image field of entity referenced field.

The below code gives me NULL. How can I load the media entity and get this value?

$image = \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id);

ok, here is what worked for me. After digging through stack overflow, found that I was missing the ImageStyle and this resulted in not rendering the url.

I added

use Drupal\media\Entity\Media;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\MediaInterface;
use Drupal\node\Entity\Node;

and then on preprocess function, I loaded the media using the target_id that I got form the $node->field_image->target_id;

Then, I loaded the ImageStyle using

$media = Media::load($image_id);
$media_url = ImageStyle::load('TYPE_OF_CROP')->buildUrl($media->image->entity->getFileUri());
$variables['media_url'] =  $media_url;

Hopefully this helps people.


Render comment parts individually with Panels/Page manager? Is there any way to create panels template for comments (comments attached to node). So far I've only found that "Node comments" thing under the node tab (Variants -> content) which outputs default comments and Mini panels block which renders only one comment from random node.

I'm trying replace forum node template with panels and render node and comments with same layout.

Thanks.

There's no out of the box solution for doing this today.

If you look at a file like ctools/plugins/content_types/node_context/node_links.inc you'll see how it's done for nodes and their links. The other files in the same directory do the same but to different pieces of nodes. For historic reasons, there's a lot of Node specific content in there.

Today it should be possible to generalize the same approach onto all entities, but as far as I know, that hasn't happened anywhere.


How to add different installation profiles in drupal 7 I have my own custom built theme. I want to add installation profile like many premium themes have. Is this is achievable by any module?

You might be looking for the Profiler Builder module:

  Profiler Builder is an extension of the Profiler installation profile simplifier. This module creates a downloadable tar package that gives you a well made installation profile and associated drush make file based on the site its installed on. This is a fast, simple way of creating a distribution with options that take into account either local host development or drupal.org packaging scripts.


Register Drupal Commerce user before checkout completes The default behavior for Drupal Commerce is that an anonymous user get's registered only after the checkout process completes and an order is paid in full. I am trying to create a new checkout rule to register an user just after he/she enters his/her e-mail address, but failing to find the right rule on admin/config/workflow/rules/reaction/manage/rules_sd/add/event.
I have modified my checkout flow, so that a user can enter his/her e-mail at the first step like shown in the screenshot:

Unfortunately, there is no rule something like "After entering an e-mail". Does anyone have a suggestion how to overcome this problem?

On /admin/commerce/config/checkout/rules it says:

When a customer advances to the checkout completion page, rules
reacting on the Completing the checkout process are evaluated. Default
rules handle standard tasks like updating the order status, sending
order e-mails, and creating accounts for anonymous users. You can edit
these or add additional rules to customize your checkout workflow.

Does this mean I can't trigger any actions until checkout completes? Not very much convenient if so.
Edit: I've also found this somewhat similar discussion: How to force account creation before commerce checkout is complete?

If you are wanting to do something during the checkout process, your best bet is to use a hook_form_alter() on the checkout forms and add your own submit handler. In this case you're looking at the commerce_order_account_pane. Remember that panes are fieldsets within a per-page form, so you'll want to look for the router page form and put your submit handler there.


How do I properly pass taxonomy term from panels to the context filter in views? I have a Book Listing content type and a Series content type. Both of these have a Book Series taxonomy term applied to them. What I want to do is override the Series page with panels and embed a view that will list every book with a matching Book Series tag.

What I've tried is creating a content pane view with a contextual filter of "Content: Book Series", Argument input set to "From context", and Required Context set to "Book Series".
I've inserted the view and set the argument to the only one available: "Node being viewed".
I've tried everything I could think of including creating contexts and relationships in the panel, creating relationships in the view, etc. I'm at my wit's end here. At the moment I'm relying on a separate view page to show what I want, but it's making the site navigation a pain to deal with. What am I doing wrong here and where can I find a good explanation of contexts?

it depends how you are trying to get the taxonomy term, but here is one solution. In my example I'm using a node as my context, and a taxonomy field of that node as the contextual argument.

There are basically two things you need to get this to work. One, you need to use view panes, so you can get the arguments from the panels context.

How can I show a view in panel with argument in drupal 7

Second, if your trying to get the taxonomy term from a field you need to convert the term to a term id using validation.

Views contextual filters taxonomy name

For instance this would work if you were trying to create a panel that diplayed a node, and a view of content related by a certain taxonomy term that that node belongs to.


Add another item by multivalued fields directly from node (or entity) view page I have a file field which can have unlimited number of values. I am using File Entity module. As default, if users want to add more files, they must edit the node.

I'm looking for a solution to give the user the possibility to add another file directly from the node page where the files are displayed/listed. Just like the edit/delete functions from file entity, which the user can edit or delete an existing file directly from the node display using the contextual links hovering the file.

Is there any setting, API function or any hook that I can implement to provide this feature? Any advice will be very helpful.

UPDATE:

I don't want editable fields (Edit or Editable Fields as suggested as an answer. They may provide this functionality, but their main purpose is making fields editable, which is much more than I need and I already have the editing and deleting features through the File Entity module, and I only need this functionality for file fields.

I hope I was clear enough, otherwise I could expand my question and provide some screenshots.

You can able to achieve it using Edit module which supports D7 and file Entities...

Project page says

  In-place editing for fields on any entity. Including WYSIWYG editing
  powered by CKEditor.

  In-place editing through forms will work for any field. For textual
  fields, "direct" editing is used, powered by contentEditable.

Here is the sample screenshot which shows inline editing of Multiple File Field.. Here is how i can able to achieve it..

Install like any other Drupal module.
Download Underscore 1.5.x and Backbone 1.x from http://underscorejs.org/ and
http://backbonejs.org/, respectively and put them in sites/all/libraries, in
a "underscore" and a "backbone" subdirectory, respectively. Either the
development or production version will work. Edit module will automatically
use the production (minified) version if it's available, because it's more
efficient.
Grant the 'Access in-place editing' permission to relevant roles.
Contextual links on nodes will now have a 'Quick edit' link. Clicking it will
start in-place editing of that node!

Seems like editablefields module also provides same functionality..


Jquery Validation & number field with comma In my form i have this element :

   $form['poidsMin'] = array(
        '#type' => 'number',
        '#title' => $this->t('Poids minimum en gramme'),
        '#default_value' => $frais_port_entity->get('poidsMin'),
        '#description' => $this->t("Poids minimum du produit"),
        '#required' => TRUE,
    );

When i put 10 or 20, all is good but if i put 10.3 or 10,3 drupal 8 jquery validate tell me to insert a value like 10 or 11 with no comma.

My field in mysql is a float, how can i disable this validation for number type field ?

Browser support may vary, but essentially you want to add an attribute of step="any":

$form['poidsMin'] = array(
    '#type' => 'number',
    '#title' => $this->t('Poids minimum en gramme'),
    '#default_value' => $frais_port_entity->get('poidsMin'),
    '#description' => $this->t("Poids minimum du produit"),
    '#required' => TRUE,
    '#attributes' => ['step' => 'any'],
);


Adding/Editing Node tab links through preprocess method When editing/adding/removing tab links to a Node page (View/Edit) is there a quick way doing this with a hook_preprocess method and not via creating a module to alter them? Such as using hook_process_page() and then editing the $title_prefix array since this is where they are stored.

Example: I created a module for editing the contextual links, but what if I wanted to skip creating a module and directly inject my changes in the template.php via  hook().

function mymodule_contextual_links_view_alter(&$element, &$items) {
      $element['#links']['new-links'] = array(
        'title' => 'Add something new',
        'href' => url('/admin/config/add/something/new', array('absolute' => TRUE)),
      );
    }

All _alter() hooks can be implemented by themes as well as modules, so in that specific case you can just use

function mytheme_contextual_links_view_alter(&$element, &$items) {
  ...


How to sort terms in Views by their weight I have Dictionary with several taxonomy terms. When I use Edit tab near each term in Structure/Taxonomy I see that I can give weight for any term.
Also I can drug and drop them in any order in list of terms for my vocabluary.
More than it, when I after this procedure go and look at weights - they are in new order.

So, problem is that then I use Views to make block with my taxonomy terms (I use unformated list) and use Taxonomy weight as sorting criteria - sorting always goes in alfabetic order.

And when I made additional field in View to show terms weight - I found out that all terms have weight -8.
How I can make term order in my Views display according to their weight?

Thank you.

I've done same setup and working fine. Might be you've missed something. Import the below code into your view.

$view = new view();
$view->name = 'List of Tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tags List';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'List of Tags';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  1 => '1',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tags-list';
$translatables['sdf'] = array(
  t('Master'),
  t('List of Tags'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);


How can I access/arrange elements in the {{ content }}? I am relatively new to Drupal and have just successfully pulled out a field value and used it to display a custom icon on the page.

Coming from a HTML/CSS only kind of world, I am finding it hard to understand how to do simple things, such as take variables I've created and insert them within the {{ content }} area.

In my specific application, I have a page that NOW looks like this:

Custom Icon 3, Custom Icon 4, Custom Icon 5

{{ content starts here }}

Node Title

Node Subtitle

Custom Icon 1, Custom Icon 2, Custom Icon 3

Image

(page continues)

{{ content ends here }}

What I'd like to do is have the Custom Icons all in a nice line together beneath the Subtitle, but since the 3, 4, and 5 were generated by code, they're outside the {{ content }} block.  Icons 1, 2, and 3 are created by hiding the text value (which is either there or not) and displaying a background image...a totally different method that doesn't work for 4, 5, and 6 because in those cases the value isn't binary, it's got several different values.

I'm not married to any specific method to accomplish this but am curious about how I can "best" make these all line up nicely together, one after another, in that order 1, 2, 3, 4, 5, 6.

I believe it's relatively easy to do it like this:

1, 2, 3, 4, 5, 6

Node Title

Node Subtitle

Image...etc.

But that's not really what I'd like to do.  This is how I'd like it:

Node Title

Node Subtitle

1, 2, 3, 4, 5, 6

Image...etc.

This would be relatively easy to do with CSS if I had better access to the inside of the {{ content }} and could make a div, assign it a class, place it in the "4" position, and style it to show as with 1, 2, and 3.  But I don't see how to actually accomplish that when the variables are OUTSIDE that immutable {{ content }} block.

Any help to better understand this process? Even if it is to say that I did everything bass-ackward and should simply make these icon fields images and upload the right image into the field each time. I have a site with a large amount of content on it but not so large I couldn't redo this Content Type from scratch the right way. It just seems so strange to me that something so easy to accomplish with a little PHP has been so difficult to get right in this case.

I've done CONTENT with
Drupal for years, but this is the first time I've been delving deeper into the development side.  Most of the documentation assumes a level of D7 knowledge that I don't have, and the explanations are aimed at people who have been developing D7 sites and need to know the differences, rather than at someone coming in fresh. Or instructions are for D7 entirely.

You don't have to use {{ content }} only - this is a variable made up of all the renderable elements in the entity being rendered.

For instance, if you have 4 fields, Field A, Field B, Field C, Field D, you can dictate how/where they are output in the entity template like so, by rendering individually:

  {{ content.field_a }}
  {{ content.field_b }}

{{ content.field_c }}

{{ content.field_d }}

The most common thing most people will encounter in theming will be the theming of fields and entities (like node).

If you wanted the markup within the field, you'd create/edit the appropriate field-- template in your theme and move it there. Lets say you wanted to move the h4 into the Field C template:

field--field-c.html.twig:

{% for item in items %}

{{ item.content }}

{% endfor %}

Now anytime that field is rendered, it is wrapped with an h4 (per value, if it is a multivalue field - check field.html.twig for more info).

Then, back in the node template you remove the h4:

{{ content.field_c }}

The h4 is still in the page, it's just in the field template now. You can break it down any number of ways that is suitable for you.

Let's say you did a mytheme_node_preprocess in your themes mytheme.theme file and created some new variables for the node template. Now that you know how to break down the content variable, you can intersperse custom variables with that:

{{ title }}

{{ content.field_subtitle }}

{{ custom_var }}

{{ content.field_a }}

{{ custom_var_2 }}

{{ content.field_b }}

and so on.

Here is a real example from a project of mine to demonstrate a little further:

node--collection.html.twig

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'hl__full-template__page-content',
    'hl__full-template__page-content--full',
    'hl__collection-details'
  ]
%}

  {{ title_prefix }}{{ title_suffix }}

  {% if node.field_featured_image %}

      {{ content.field_featured_image }}

  {% endif %}

    {{ content.body }}

Accessing These Materials

        {{ content.field_how_to_use }}

      {% if view_records %}

          {{ view_records }}

      {% endif %}

Contact

              {% if node.field_contact_person.target_id %}
                {{ content.field_contact_person }}
              {% else %}
                {% include '@mytheme/misc/freeform--contact.html.twig' %}
              {% endif %}

      {% if node.field_call_to_action.target_id %}
        {{ content.field_call_to_action }}
      {% endif %}

  {% if node.field_related_collections.target_id or node.field_related_how_tos.target_id %}

  {% endif %}

  {% if node.field_related_collections.target_id %}

Related Collections

          {{ content.field_related_collections }}

        {% if node.field_see_all_collections %}

            {{ content.field_see_all_collections }}

        {% endif %}

  {% endif %}

  {% if node.field_related_how_tos.target_id %}

          {{ content.field_related_how_tos }}

  {% endif %}

The more you try things, the more you are going to learn. You cannot do any PHP in Twig templates, which is why that has to be deferred to preprocess functions in the theme file, custom field formatters etc that tell Drupal what to do with the data you are about to output.

edit: the {% if node.field_name.value %} lines are simply checking in the node object that the field has an actual value before we output markup and render the field for it. node and content are two separate things.


How to alter HTML generated for $messages? I'm building a theme from scratch using Bootstrap 3. I really don't like the HTML being generated for Drupal's $messages. I know I could change the look by using CSS. But I want more control than that, I want to generate different HTML based on type of message (warning, error, etc). I've custom classes & custom images & other custom elements to be used for these messages. I want complete control over the messages. What should I do?

You just need to override the theme function...

theme_status_messages($variables)

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_status_messages/7

function YOURTHEME_status_messages($variables) {
// code goes here...
}


How to make view source code in single line Is there any way to show rendered HTML in single line when you view source it in Drupal?

You may see in some websites like facebook.com. So, when you view source the entire HTML will be in single line, so that people can not read easily (though they can use firebug to investigate).

A couple modules you might find interesting.

https://www.drupal.org/project/minify

https://www.drupal.org/project/minihtml


EntityQuery PHP issue when assigning the query to a variable I am very confused about this behavior of EntityQuery, or maybe I am just missing something basic about PHP.
Here is the query I am working with:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
return $entity_query_points1;

This is fine.
But if this query returns no results, I wanted to immediately execute another query.  So I made a switch statement and wrote code like this:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query->count()->execute();
if ($count >= 1) {
  return $entity_query_points1;
}

This fails with a WSOD (I am using this code with the JSON:API Resources module):
TypeError: Argument 2 passed to Drupal\jsonapi_resources\Resource\EntityQueryResourceBase::loadResourceObjectsByEntityIds() must be of the type array, string given, called in /app/web/modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php on line 97 in Drupal\jsonapi_resources\Resource\EntityQueryResourceBase->loadResourceObjectsByEntityIds() (line 125 of modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php).

If I use the following code, it works (query resolved correctly, no WSOD):
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query->count()->execute();
if ($count >= 1) {
  $entity_query_score1 = \Drupal::entityQuery($entity_type_id)
    ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
    ->condition($entity_type->getKey('uid'), $uid)
    ->condition('field_int_points', 1, '=');
  return $entity_query_points1;
}

But... why?  I executed the count on $entity_query, but I have to redefine $entity_query_score1 to return the query as expected.  I know having to redefine the query means I have screwed up somehow, but I don't know what my mistake is.

Objects work differently than regular variables in PHP. They are "assigned by reference", generally speaking. The Objects and References page in the PHP manual goes into some detail about this. Basically, your = is not working as you expect. $entity_query and $entity_query_points1 are "the same object".
As noted by @baikho in the comments, you'll need to use clone to achieve what you're trying to do.
$entity_query = clone $entity_query_points1;


Cannot modify language field in node form using hook_form_alter in drupal 7 I tried adding a description for the language field in a node form using hook_form_alter:

$form['language']['#description'] = t('Description');

The changes are not accepted, the language field stays as it is the description is not added. As far as i can tell this is not a problem with the hook, because changes to other fields work fine, only the language field does not change.
Any ideas what i'm doing wrong.

Your code doesn't work because the node edit/create form sets $form['language'] using the following code. (See node_form().)

  // Basic node information.
  // These elements are just values so they are not even sent to the client.
  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

It's then the Locale module that changes the form field in locale_form_node_form_alter() using the following code.

  if (isset($form['#node']->type) && locale_multilingual_node_type($form['#node']->type)) {
    $form['language'] = array(
      '#type' => 'select',
      '#title' => t('Language'),
      '#default_value' => (isset($form['#node']->language) ? $form['#node']->language : ''),
      '#options' => array(LANGUAGE_NONE => t('Language neutral')) + locale_language_list('name'),
    );
  }
  // Node type without language selector: assign the default for new nodes
  elseif (!isset($form['#node']->nid)) {
    $default = language_default();
    $form['language'] = array(
      '#type' => 'value',
      '#value' => $default->language,
    );
  }

If your module is executed before the Locale module, its changes to the language form field are not retained, as the Locale module set $form['language'] to a different array.

In order for your code to work, you need to change the weight of your module, or implement hook_module_implements_alter() to alter the order hooks are executed.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move mymodule_form_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

This code changes also the order in which hook_form_FORM_ID_alter(), and hook_form_BASE_FORM_ID_alter() are executed.


Why does the Multifield module not show an "Add" option? After downloading the Multifield module, I enabled it from the module section.

After that I went to Structure -> Multifields, to create a new Multifield. But there is no "Add" button, as shown in this image:

Any suggestions about what I'm missing?

First you must add a Multifield field to a Content Type. For this go to:

admin/structure/types/manage/YOUR_CONTENT_TYPE/fields

And if you go to:

admin/structure/multifield

You will see your Multifield field and you will be able to "Add" (Manage subfields) the subfields


Allow multiple taxonomy term values on term listing page Is it possible to return results of multiple taxonomy terms on the taxonomy/term/%tid page?

For example, taxonomy/term/203+221 or taxonomy/term/203/221 should display all nodes with either one of those two terms.

I've found the path taxonomy/term/203+221 (which will yield the nodes tagged with either 203 OR 221) is possible by making a slight change to the Contextual Filter of the taxonomy/term/%tid view (which you should have enabled in Structure > Views > Taxonomy Term.

Expand the Advanced section of the view configuration, click on the first Contextual filter "Content: Has taxonomy term ID (with depth)".

You will see a checkbox that allows multiple values, which is checked by default.

However, to get this working I had to scroll further down to the "Specify validation criteria" section and change the "Filter value type" to "Terms separated by a , or +".

Now you should be able to use multiple term IDs in your URL, combined with a "+", to see all nodes tagged with any of the IDs in the list. You can test out various URL arguments using the Views Auto preview:


Views Exposed filter Multiple times on a Page Or Different id for views exposed filter if added one more time I added a views exposed filter to block and I want to show the block multiple times on the dashboard page each can have different choices. Can it possible without adding any other display?

Or Can it be possible to change the make the id unique for each occurrences of same exposed filter?

My Actual Need is :

I am using Homebox module for creating a Dashboard for user. I created a view with block display so user can add it in their Dashboard multiple times. I added the Exposed filter of taxonomy terms and I entered the choices of user in my custom table. Now user can add same block with different choices. My questions is how to manage different choices with blocks,because exposed filter have same form id on each occurrences.

While adding a filter there is a dropdown at the top as 'For', by default 'All displays' are selected, by selecting the specific block that particular filter will be displayed on selected block only. Please try and let me know if it worked.


Drupal 8 multilingual node edit I have a multilingual setup, and the content translation works well and smooth.

But when I try to edit a node on the other language - I have the same link from the content admin menu, which renders the default language form. I.e. I have /node/21/edit both for En and De versions.

For the test I've try to alter the node object on the form build step (couldn't found a correct hook, so just try it in the FormController::getContentResult() ) - no luck:

$translated = $form_object->getEntity()->getTranslation('de');
$form_object->setEntity($translated);

form object states the active language as 'de', but the rendered form still has en version fields.

Also the form has native language switcher (Languages), which in my mind should do language switching, but for me it shows only English and does nothing.

The entity passed in the $form_object is simply ignored, as the whole $form_object thing - it is used only to determine the form id. You may add entity to the form_state, but with the original drupal form generation it is ignored too.

To set the node edit translation you need to set $form_state->set('langcode', $langcode);

The full thing emulating drupal's node edit form looks like so:

public function customEdit($type = 'node', $id, $langcode) {
    $request = \Drupal::request();
    $entity = Node::load($id);
    $form_object = \Drupal::entityManager()->getFormObject('node', 'edit')->setEntity($entity);

    // Add the form and form_state to trick the getArguments method of the
    // controller resolver.
    $form_state = new FormState();
    $request->attributes->set('form', array());
    $request->attributes->set('form_state', $form_state);

    $args = \Drupal::service('controller_resolver')->getArguments($request, array($form_object, 'buildForm'));

    $request->attributes->remove('form');
    $request->attributes->remove('form_state');

    // Remove $form and $form_state from the arguments, and re-index them.
    unset($args[0], $args[1]);
    $form_state->addBuildInfo('args', array_values($args));

    $form_state->set('langcode', $langcode);

    $render_array = \Drupal::service('form_builder')->buildForm($form_object, $form_state);

    return $render_array;
  }

The answer is actual for the Drupal 8 beta 2, I'm sure the ability to edit different language node versions would be fixed before release.


Can you do anything about the div soup? All the sites I have seen that build on drupal looks like it's hit by div soup. There are so many unused divs produced by the content and some templates I have looked on contribute more by adding even more terrible markup.

I know most people with some knowledge about drupal know about this issue. For instance, here is a dump from drupal.org:

So why does Drupal need all these divs? Is there any rational behind them or is it just a flawed design?

Is there anything that could be done with this issue or are there some plans to improve on all these divs? Maybe a module that remove the divs that are not required and append the class statements so that markup will look better?

Are there some modules or solution that tries to address this annoying issue?

This is the result of a flexible content management that tries to be everything to everyone. Adding more divs upon request would be difficult, so it provides everything anyone will ever need.

Every template can be overridden as you see fit. For an example of a theme that really clears out a lot of cruft, see Mothership.


Which image editor can be used within Drupal for creating flowcharts? I am looking for an image editor within Drupal. Particularly, I need something that will help me create flowcharts and save them directly.

The idea is to avoid using an offline image editor, to make the site more user-friendly.

Any pointers?

Try Image Editor module

  integrates several popular online image editing services into Drupal:

There are integrations with quite a few popular online image editing services.


How can I always have the node title display on top of a background image? With Drupal 8, the page title is available through a block now. We have several content types where we have an Image field (field_image) and we constantly have to write templates per content type to place the title on top of the image.

It would be nice if we could use the view modes of each content type or some module to do this. Basically, something that does "take the field image, set it as a background, and place the title on top."

Is there a better way to do this programmatically as we cannot find any other way to do this?

There is several ways to solve this

1 make your own module

to do what you described

2 add theme templates

for each content type as you described

3 Use background_image module

The module is available for Drupal 8 promises to do just this (I meant to use it but have not actually)

According to the the project description provides a way to insert token values

  Token - Provides a way to view which tokens are available to use when
  adding overlay text for a background image.

So you can probably use it with a field token to accomplish what you need