How do I programmatically change the admin theme? How do I define a different administration theme for a user and administration role in Drupal 8?

I have looked at the context module for Drupal 8. There is a problem with the context condition and the reaction theme related items are all based on the front-end themes. I need the same but for the back-end themes.

My code is the same as the context reaction code for Theme.php. I just changed the submitConfiguration().

 /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration['admin'] = $form_state->getValue('theme');
    $configuration += $this->getConfiguration();
      \Drupal::configFactory()
          ->getEditable('system.theme')
          ->set('admin', $form_state->getValue('theme'))
          ->save();
    $this->setConfiguration($configuration);
  }

I defined the following in the context configuration.

Condition => Role:User

Reaction => Admin Theme: Customtheme
Condition => Role: Administrator

Reaction => Admin Theme: Seven

Is this possible? Are there other methods for achieving this goal?

As the context module is still in alpha I would try a solution in custom code by extending the class AdminNegotiator:

src/Theme/CustomAdminNegotiator.php

<?php

namespace Drupal\mymodule\Theme;

use Drupal\user\Theme\AdminNegotiator;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAdminNegotiator extends AdminNegotiator {

  public function determineActiveTheme(RouteMatchInterface $route_match) {
    if (in_array('custom_role', $this->user->getRoles())) {
      return 'custom_admin_theme';
    }
  }

}

and register this service class in mymodule.services.yml tagged as theme negotiator with a priority higher than the default admin negotiator (-40):

services:
  theme.negotiator.admin_theme.custom:
    class: Drupal\mymodule\Theme\CustomAdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -39 }

The applies() method is kept the same as in AdminNegotiator, so that only users with the correct permission have access to this theme and this only applies for admin routes.


Call to undefined function t() in an Unit test I'm trying to test a method from the dev version of the Allow a content type only once (Only One) module that have a t() call inside:

<?php

namespace Drupal\onlyone\Utility;

class InternalFunctions {

  public static function getLanguageLabel($language) {
    switch ($language) {
      case 'und':
      case '':
        // If the language is empty then is Undetermined.
        return t('Not specified');

      case 'zxx':
        return t('Not applicable');

      default:
        return ucfirst($language);
    }
  }

}

With the following Unit test:

<?php

namespace Drupal\Tests\onlyone\Unit;

use Drupal\onlyone\Utility\InternalFunctions;
use Drupal\Tests\UnitTestCase;

class InternalFunctionsTest extends UnitTestCase {

  public function testGetLanguageLabel($language_code, $expected) {
    $this->assertEquals($expected, InternalFunctions::getLanguageLabel($language_code));
  }

  public function providerGetLanguageLabel() {
    $tests[] = ['', 'Not specified'];
    $tests[] = ['und', 'Not specified'];
    $tests[] = ['zxx', 'Not applicable'];
    $tests[] = ['es', 'Es'];
    $tests[] = ['en', 'En'];

    return $tests;
  }
}

and when I run the test I receive these errors:

1) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #0 ('', 'Not specified')
Error: Call to undefined function Drupal\onlyone\Utility\t()

/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/src/Utility/InternalFunctions.php:26
/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/tests/src/Unit/InternalFunctionsTest.php:30

2) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #1 ('und', 'Not specified')
Error: Call to undefined function Drupal\onlyone\Utility\t()

/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/src/Utility/InternalFunctions.php:26
/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/tests/src/Unit/InternalFunctionsTest.php:30

3) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #2 ('zxx', 'Not applicable')
Error: Call to undefined function Drupal\onlyone\Utility\t()

But the t() function is always defined inside Drupal. If I remove the t() calls inside the method the test works fine.

I found in Unit testing more complicated Drupal classes that:

  ... global functions do not exist in the testing environment.

And a method to made this works, but I find that this is complicate things just to use a test and method with the t() function inside.

So, there is not a simple method to test a class method that have a t() call inside?

You should not be using t() inside classes. The string translation trait should be included instead (if it is not already part of a parent class). Then you will use:

$this->t()

Then you can use the answer I provided here as to how to do unit tests with string translation trait: How to unit test a class which uses a trait?


Use the same image 2 times in image styles A tricky question regarding image styles.

I need to do a thumbnail with 2 layers:

background: a cropped picture with a blur effect.
foreground: overlay with the same picture and scale effect.

If you have some hints, or you know how to do it programmatically in a custom ImageEffect plugin I would appreciate any help.

This is an example how the image should look like:

I have solved the task currently without a custom image style. Only custom code:

/**
   * Applies an image effects blur, scale and crop.
   *
   * The result is am image with 2 layers:
   *   - background: a cropped picture with a blur effect.
   *   - foreground: overlay with the same image and scale effect.
   *
   * @param int $width
   *   Result image width.
   * @param int $height
   *   Result image height.
   * @param int $radius
   *   Result image blur radius.
   */
  public function blurScaleAndCrop($width, $height, $radius) {
    $image = $this->getImageFactory()->get($this->path);
    if (!$image->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }

    // Create the background image.
    $image->scaleAndCrop($width, $height);
    /** @var \Drupal\system\Plugin\ImageToolkit\GDToolkit $toolkit */
    $toolkit = $image->getToolkit();
    $resource = $toolkit->getResource();
    // Apply blur.
    if ($radius) {
      for ($i = 0; $i < $radius; $i++) {
        imagefilter($resource, IMG_FILTER_GAUSSIAN_BLUR);
      }
    }
    $image->apply('gaussian-blur', ['radius' => $radius]);

    // Create the foreground image.
    $foreground = $this->getImageFactory()->get($this->path);
    if (!$foreground->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }
    $foreground->scale($width, $height);

    // Merge the 2 image layers.
    $dst_im = $image->getToolkit()->getResource();
    $src_im = $foreground->getToolkit()->getResource();
    $f_width = $foreground->getWidth();
    $f_height = $foreground->getHeight();
    $x = ($width - $f_width) / 2;
    $y = ($height - $f_height) / 2;
    imagecopy($dst_im, $src_im, $x, $y, 0, 0, $f_width, $f_height);
    $image->save();
  }


The Calendar module doesn't recognize fields I created a content type "events", with a date field and other normal settings.

I am trying to use the Calendar module to create a calendar on my Drupal site, but I am facing an issue.
When I try to edit the basic calendar, and change its argument from date:node (node updated time), then in the list of date_fields it does not show the field that I had created above. It only shows the following fields:

Node: Last comment time
Node: Post date
Node: Updated date
User: Created date
User: Last access
User: Last login

I have tried this again and again by recreating my content type, or by disabling/enabling the Calendar module, but it does not seem to work. I am using Date 7.2.x and Calendar 7.2.x.

I installed Calendar 7.x-2.x-dev, Date 7.x-2.x-dev, and Views 7.x-3.x-dev; then I created a "Test" content type to which I added a date field ("Start date").

When I edited the Calendar view, and added a new argument for the view (view arguments are called "contextual filters," in Views 7.x-3.x-dev), I followed the following steps:

I filtered out the list of arguments to show only the ones defined from the Date module; between the two argument types, I selected "Date: Date (node)."
On the settings page that Views shows after I selected the argument type, I selected the date field I added to my content type.

If you select "Date: Date (users)," then you will see all the date fields that are associated with users, as in the following screenshot.

Still, the field I added to my content type is visible in the list of fields shown in the settings page for the view argument.

The issue you are seeing is probably caused by compatibily problems between Date, and Views. I would try using Views 7.x-3.x-dev.


How to add 3 text boxes for a phone number field? I want to add 3 text boxes for a phone number field. The phone number format should be xxx xxx xxxx.

I need to show 3 text boxes and stored values into single field.

How can I do this?

You can use Masked Input to format a field. It won't give you three text boxes. But it can solve your problem by formatting the text box like below,


Term parent in node.tpl.php I have an Entity taxonomy Reference field in my content type.

I need to print parent of the term linked to my node in node.tpl.php (link to that term). How can I do it?

Thanks for your help.

Ok, I figured it out. This is my code:

<?php
    $term = field_get_items('node', $node, 'field_taxonomy_term');
    $parent = current(taxonomy_get_parents($field[0]['target_id']));
    print l($parent->name, 'taxonomy/term/'. $parent->tid);
?>


Making landing pages with taxonomy I'm trying to make about 100 landing pages using taxonomy.

I'm trying to stick to Drupal 8 core features as much as possible.

I created two taxonomy vocabularies, Places and Main keyword.

Now, what I want to do is create landing pages that consist of:

1 place + 1 keyword

Places

London
Paris
Berlin

Main keywords

Apples
Oranges

Combinations (each of these is a landing page using tokens from both keywords in Views blocks [perhaps attached by Layout Builder] to make the page)

London + Apples
London + Oranges
Paris + Apples
Paris + Oranges
etc.

What module(s) should I use to link taxonomy terms from two different vocabularies together like this (preferably, in an automatic way so the relevant pages are automatically generated when I add a new term in either vocabulary)?

I have been experimenting with Views and Layout Builder but I haven't come up with a solution yet.

What I tried

I used the Views "taxonomy term page" view to override the taxonomy term pages; this lets me do what I want for a single term in a single vocabulary, but I want to use two terms in combination from two different categories.

How I'm doing this now

Create a new content type, Landing Page.
Add two fields, an entity reference to Places and an entity reference to Main keywords.
Use Views blocks/Layout Builder to rewrite the HTML of the content type to show the text you want with the relevant keywords substituted in.
When you add a new term to either vocabulary, you have to create all the possible combinations manually by adding Landing Page content.


How to show/hide textfield according to the change in drop down using jquery? $(".form-select").change(function () {
  if (this.value == "1") {
    $('.form-item-example').stop(true,true).show(700);
  }
  else{
    $('.form-item-example').stop(true,true).hide(700);
  }
});

This is what i have used in my js file but it is hiding the text fields when any of the drop down in the form is changed, I'm having 3 drop downs in the form.

I have done something similar using conditional fields module which is an interface for the States API or you can use States API if you are comfortable writing custom code.


How do I programmatically set the preferred language for a user? I would like to update the preferred_langcode of a user as soon as he changes the language in a language switcher block.

I'm already aware of the getPreferredLangcode method mentioned in https://api.drupal.org/api/drupal/core!modules!user!src!Entity!User.php/function/User%3A%3AgetPreferredLangcode/8.6.x and looking for a setPreferredLangcode method, if one exists.

If not, what other options do I have?

Seems D8 doesn't have a setPreferredLangcode method yet. So, the preferred approach IMHO would be to use the default set method of D8 Entity API as below
$user = \Drupal\user\Entity\User::load('uid');
$user->set('preferred_langcode', 'en or whatever langcode we want');
$user->save();


How can I extend the webform #states conditions to save a custom set of conditions for webform fields? I need to store sets of conditions on the webform field level (these would then be evaluated according to the field's submitted values within a custom submit callback).
I would like these conditions to be editable on the webform field level just like #states conditions that honour the field type for value ranges, set values, boolean etc:

No new custom state is necessarily needed here as this new type of condition would not be related to interacting fields. I'm merely looking for a way to expand webforms and add a custom field to each element that will allow adding (on the UI) sets of conditions based on its value(s). These sets would be part of the field's properties and accessible in a validation / submit callback.

There's a hook for that: hook_webform_element_configuration_form_alter(), webform_example_element_properties.module provides a simple example too.


How do I hide text format options in node view with in place editing? I am using drupal 7 version with in place editing module editablefields
I was able to hide the text format options in edit mode with simplify module  but in node view mode are still there.

Please, do you have any module or custom module with hooks that I could use or do?
!

You can find multiple questions/answers to this problem in this site... One of the most recommeded approach is using hook_form_alter hook: example:

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

  // dpm($form);
  // dpm($form_id);

  if($form_id == 'MY_NODE_FORM_ID') {
    $form['#after_build'][] = 'custom_my_node_form_after_build';
  }
}

function custom_my_node_form_after_build($form) {
  // dpm($form);
  // Find the right field's format option with dpm() function

  $form['MY_FIELD']['und']['0']['format']['#access'] = FALSE;
  return $form;
}


fivestar module get count I am interested in getting the average count for a node.
Currently I am able to show the nodes rating with:

$fivestar = field_view_field('node', $node, 'field_cg_rating', 'basic');
render($fivestar);

But I just want to get the count instead of the entire html showing the vote. Just a numerical value.

Is there an easy way of doing this?

You can calc it with formula which is used by Fivestar on theme layer: http://drupalcode.org/project/fivestar.git/blob/refs/heads/7.x-2.x:/includes/fivestar.theme.inc#l132

$fivestar = field_view_field('node', $node, 'field_cg_rating');
$stars = 5; // Stars count from your field instance settings. Settings can be loaded with field_info_instance() if needed.
$rating = round(($fivestar['#items'][0]['average']/100) * $stars, 1);


Can I use Emoji as icon in navigation bar? Emoji icons are 4byte UTF8 characters, the characters are not accepted in PDO, it would show errors like this question: How can I remove emoji from all user input?

Instead, I used menu_icons plugin to prepend icons as picture before the navigation text, it uses picture background in CSS, but by using this method the text and picture will be overlapped.

If emoji is not an option, is there another way to prepend an icon before navigation text?

If emoji is an option, please help me bypass the PDO exception.

Thanks.

Can't help with the PDO exception, but .. Have you looked at IconAPI ? It has a sub module for use with menu items which doesn't cause overlapping as you described.

You can then use Fontello as an icon provider and create a font set from the emoticons there, or import your own emoji icons into Fontello and download them as a font set.


Join table query in hook_views_query_alter not selecting field from joined table I have the following query

SELECT
    node.nid AS nid,
    node.created AS node_created,
    'node' AS field_data_field_gm_tanknummer_node_entity_type,
    'node' AS field_data_field_gm_naam_node_entity_type,
    'node' AS field_data_field_gm_adres_node_entity_type,
    'node' AS field_data_field_gm_postcode_node_entity_type,
    'node' AS field_data_field_gm_jaar_node_entity_type,
    'node' AS field_data_field_gm_bedrijf_levensduur_node_entity_type,
    'node' AS field_data_field_gm_bedrijf_antibiotica_node_entity_type,
    'gemiddelde_waarden:page' AS view_name
FROM
    {node} node
left JOIN
    {field_data_field_gm_tanknummer} field_data_field_gm_tanknummer
ON
    node.nid = field_data_field_gm_tanknummer.entity_id
WHERE
    (( (node.status = :db_condition_placeholder_0)
AND
    (node.type IN (:db_condition_placeholder_1))
AND
    (field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value IN (:db_condition_placeholder_2)) ))
ORDER BY
    node_created DESC LIMIT 10 OFFSET 0

where I join the table field_data_field_gm_tanknummer.

I want to select the field field_data_field_gm_tanknummer_value from that table but the query cannot find this field.

This is my function

function misc_views_query_alter(&$view, &$query) {
  if ($view->name == 'gemiddelde_waarden') {

    //create the join
    $join = new views_join();
    $join->table = 'field_data_field_gm_tanknummer';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    //add the join the the view query
    $view->query->add_relationship('field_data_field_gm_tanknummer',$join,'node');

    $query->where[1]['conditions'][2]['field'] = 'field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value';
    $query->where[1]['conditions'][2]['value'] = array(
      0 => _misc_tanknummers()
    );
    $query->where[1]['conditions'][2]['operator'] = 'IN';
  }
}

Is there something wrong with the join?

There a typo in your SQL query: instead of

field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value

you need to specfiy:

field_data_field_gm_tanknummer.field_gm_tanknummer_value


How to set permission to ALWAYS be full on for administrator? I'm looking for a module that will give the administrator permission on ABSOLUTELY everything.

Not only to retroactively give all permissions after having installed modules in the past. But also for every new module installed.

By default giving the Administrator permission to do EVERYTHING.

I have tried:

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

But still a lot of configuration and clicking..

Isn't there a way to click on a sigle box and set everything to ON in one shot for administrator?

I'm the only one touching the website, no collaborators, EVER ;)

Did you try to set Administrator role /admin/config/people/accounts?


Multilingual pages links showing node instead of URL alias My web has 2 languages, English and Malay. The language selection is by session of ?lang=en or ?lang=ms.

English is the default language and it is working fine. All internal links are using the correct URL aliases. The problem arises when switching to Malay language. All links became node/(some-number).

For example:
About Us Page
all using about-us as URL Alias

In English
www.example.com/about-us

In Malay
www.example.com/node/2

Even when I type out the URL www.example.com/about-us?lang=ms it doesn't work. It will still show the English language.

Add translation in Malay language for about-us node and add alias to it. When node hasn't translation to Malay language, it will be without alias when You change lng


Send the email when specific node is created In one of my module, i have created a checkbox on user account page. If user has checked that checkbox at that time an email is sent to all the user when any specific node is created. Lets say when any article node is created then all the users who has checked the checkbox will be notified by the email when node is posted.

Now for the scenario given below:

Lets say if my site has 1000 users who has checked the checkbox/
Simultaneously 10 users are creating the node.
When only 10 users are creating the node simultaneously 1000 * 10 = 10000 emails will be sent at time.
I am not sure whether site will able to handle it or not.

So i want the suggestion that is there any way to queue email and send them after certain intervals like 1000 mails after an hour, 1000 after second hour 1000 after 3rd hour and so on. Or any other nice solution.

I've never used it but the Queue Mail module purports to do exactly that:

Queues email sending from your site so that instead of being sent immediately it is sent on cron.
Useful for high traffic sites that can send a lot of emails on individual page requests.

It has the unusual properties of being both actively maintained, and bug report free at this time - so looks quite promising


Rule fails to send email to billing address I'm trying to create notification emails which are sent when the checkout has been completed. (Drupal Commerce module)

I added a rule to send the email to site owner. It works.
I created a new rule to send email to to the customer's billing address. I Used [commerce-order:mail] replacement pattern as suggested, but unfortunately the email fails to arrive.

What could cause this problem? I even considered add new data selectors, but couldn't find anything fitting to add.

As per one of the comments below this question (which kept showing up as a question with no answers):

It seems that for the email field an additional field was added to customer profile form. Thus obviously it couldn't be accessed.
A solution which works is to continue using the "Account information" checkout pane instead.

Credits: Gugols


Modules or install profile for scholarly peer review Are there any modules or installation profiles available to create a peer-review system, such as used by academic journals and conferences? I've found lots of discussions on Drupal.org but no actively maintained modules.

Update: here is an example of a commercial system showing the kinds of features I'm looking for.

Depending on what you would like to do, there are two potential approaches.

On the simple end, you have fields on content types that only certain roles can edit.  For example, you can have a field called vetted and two roles, author and expert.  When an author makes a new node, vetted would get set to some default value, like not verified.  Your expert users can then read and review the nodes, and sets the vetted field as appropriate, say verified or needs further review.

One the more complex end, you can use workflow.  Two modules that do this are Workflow and Workbench.  With this, you can set up just about any editorial review process that you want.  Both can also be combined with Drupal actions to occur on state transitions.  Just keep in mind that workflow can be a pain to set up, and often there are real work scenarios that don't always work into rigid workflow rules.

As for existing systems, Open Atrium may potentially fit the bill.  It is more designed for team collaboration, but based on what clients have said, it may work for something more conference oriented.


D7 Views: Hide field if empty after being rewritten In a node type, I have three fields: (1) methods, (2) geography, (3) keywords.
On node view, I have a views block showing these values. However, I want all of the content to appear as single field with a label. This was easy to achieve:
(a) exclude methods and geography from display, (2) rewrite keywords to display the content of methods and geography.

This works like a charm as long as any of the three fields is not empty. However, if all three fields are empty, the block still displays the label (Keywords).

How should I setup the view to hide the label if there is no data in any field?

I've been playing around with all sorts of combinations of the hide options, besides "Hide when empty" and "Hide rewriting when empty" it seems like I would need an option "Hide IF rewrite is empty".

More details reagarding the view:

Format: Unformatted list

Show: Fields

Fields

Methods: no label, exclude from display
Geography: no label, exclude from display
Keywords: label "Keywords", rewrite results: [keywords][methods][geography]

Go to your view and Click on Keywords to configure the field.
Go to No results behavior and check Hide if empty

That's it. I've tested it and it's working fine. Let me know if you stuck anywhere.


When a user has forgotten their password, how to let them set a new one? A user has forgotten her password, so she uses the 'forgotten password' function. She receives an email with one-time login, and proceeds to edit her profile to set a new password.

But that form requires the old password in order to reset password. A catch 22 situation?

Same problem here. My site had an action set to direct to the homepage on login. This helped me a lot to identify it. My solution was to disable the action an set a destination parameter by GET in my template to redirect user to the homepage on login. "/user?destination=/"


Services 3 and session authentication I am creating a titanium mobile app that consumes and uses Drupal Services. I'm able to create a node but the user is always anonymous. I've tried setting the request headers so that the Authentication is basic.

authstr = 'Basic ' +Titanium.Utils.base64encode('admin'+':'+'password');
xhr.setRequestHeader('Authorization', authstr);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify(params));

For some reasons it still gives me;

  Code=3 "Authentication needed"

What is the best way to troubleshoot this? Is it even possible to use sessions in this manner?

Thank you very much for your help. I finally manage to autenticate and retrieve files from my rpc server. Here is my syntax in case anyone needs it.

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);

EDIT: AFTER SERVICES 3.5 you should do:

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);


Views Default Contextual Filter I want to create a view that will allow the user to pass a filter value using the URL, but if the filter is missing, assign a default value.  The view's path is set to results. I created a view page and added a contextual filter that uses the URL to retrieve the value results/somevalue.  Some value will filter the view based on it's value.  What I can't figure out is if the user browses to the default page, results, how do I set a default value?

I tried creating a second page based on the first, using the same path. When I did this, users could not browse to results/somevalue.

I would suggest a small trick with contextual filters.

After adding a filter:

You could simply select and fill the 'Provide default value' field.
Here you have many options to mention the default value. The one which should work for you is: "Raw value from URL"

Alternative:

Set 'WHEN THE FILTER VALUE IS NOT AVAILABLE' to (Display contents of "No results found")
Select 'Allow multiple values' option at the bottom (by clicking on more)
Now you should pass two filter with the URL

Your default filter
Filter which user will add to url.

So your default url should always include the default parameter (filter).
Once this is done, when there is no value for the user's filter view should filter the results based on the default filter.


How to configure drush command-specific archive-dump --tar-options in a site alias The following command does exactly what I want — It dumps an archive, excluding all of the files and directories that I don't want:

$ drush archive-dump --tar-options="--exclude=.git --exclude=*.psd --exclude=sites/default/files/styles/ --exclude=sites/default/files/private/backup_migrate/manual/"

Can anyone show me how to set these extra command-specific archive-dump tar-options inside a site-alias array in aliases.drushrc.php?

I've tried every variation I can think of, but I can't seem to get the syntax right.

Update Here is a gist with my full test setup including verbose output and -debug info.

It should be like this - Edit: I've just confirmed that the following works as expected with Drush 6.3:

$aliases['example.com'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com/public_html',
  'command-specific' => array (
    'archive-dump' => array (
      'tar-options' => '--exclude=directory1 --exclude=sites/all/modules --exclude=*.txt',
    ),
  ),
);

I did notice that %files didn't work (Warning: sprintf(): Too few arguments exec.inc:138).


Show popup in access denied page I want to show a popup for access denied page. Is there any module available for this? I know I can create a custom module for this but I want to know if there is any module available for this.

Popup module allow you to display the access denied page in popup box.

  The popup suite allows builders to popup tooltip-like text, nodes,
  blocks, menus, forms, views and php-generated content.

or

Better Messages intends to let you control where and how you want to see your Drupal messages! Combine different animations and override

  Enable or disable popup messages at specific pages.


Use drush to sync core &/or modules directory only I've just discovered the wonderful world of drush aliases, and I'd like to use drush to keep a dev site in sync with the live site (and visa versa). So far I've figured out that the following command does it pretty well for a site in the sites/ folder:

drush rsync @mysite.com.live @mysite.com.dev

I'd like to be able to sync modules and core the same way. Is there a way to do that with drush?

To sync contrib:

drush rsync @mysite.com.live:%modules @mysite.com.dev:%modules

%modules will be rewritten to sites/all/modules.

Drush does not have a path alias for the core modules folder, but you could do this:

[REDACTED]

The answer I gave before only sync'ed the core modules folder; what you really want is all of core, minus any sites or contrib modules.  To do that, use the following rsync command:

drush rsync @mysite.com.live @mysite.com.dev --exclude="sites/*"

To sync core and contrib together:

drush rsync @mysite.com.live @mysite.com.dev --include="sites/all" --exclude="sites/*"

Add '-s' prior to the rsync to run in simulated mode (i.e. drush -s rsync ...); if you do this, Drush will print out the rsync command that it would run for those parameters without actually executing it.

Update:

Yes, the rsync command shown in the question will sync the entire Drupal root.  If you want to sync only the sites folder for one particular Drupal site, you could try this:

drush rsync @mysite.com.live:%site @mysite.com.dev:%site

At this point, you might be tempted to chain together all of the commands shown above, and drop it into a script to sync everything that one site needs to run. If that's your intention, you might want to try the following variant, which rsync's everything except the other multisites:

drush --exclude-other-sites rsync @mysite.com.live @mysite.com.dev

Again, run with -s to see what it's going to do with that command.


Execute complex SQL queries I need to execute these SQL instructions.

CREATE TABLE superstatistics_counter LIKE node_counter;
INSERT superstatistics_counter SELECT * FROM node_counter;

When I run the query, it runs. I expect the node_counter table to get a big table with about 100000 rows.
This is what I have tried:

With hook_schema() I have created the superstatistics_counter table
With this code I tried to copy data from the node_counter table

$sql = "SELECT * FROM `node_counter`";
$data = db_query($sql)->fetchAll();
foreach ($data as $dataObject) {
  $dataArray = array($dataObject->nid, $dataObject->totalcount, $dataObject->daycount, $dataObject->timestamp);
  $query = \Drupal::database()->insert('superstatistics_counter');
  $query->fields([
    'nid',
    'totalcount',
    'daycount',
    'timestamp'
  ]);
  $query->values($dataArray);
  $query->execute();
}

It caused the following error:

  Maximum execution time of 120 seconds exceeded

So it is very slow.

When I executed it in phpMyAdmin, it output the following.

  MySQL returned an empty result set (i.e. zero rows). (Query took 0.1401 seconds.)
  CREATE TABLE superstatistics_counter LIKE node_counter

  100000 rows inserted. (Query took 0.9567 seconds.)
      INSERT superstatistics_counter SELECT * FROM node_counter

Is there a way to just execute this query in Drupal, without using db_query() and \Drupal::database()->insert()? Can it be done on MySQL side?

The db_query function  isn't just for select queries, it will execute anything.

Just use that instead of the loop, the performance will be miles better:

db_query('INSERT INTO superstatistics_counter SELECT * FROM node_counter');


Custom feed tamper plugin to convert an image GUID into a URI I have a feed importer for image files, which stores a column in my source csv as the GUID of the final files in Drupal.

I also have another importer for, say, articles. In the articles csv, there is an "image key" column, that corresponds to the image GUIDs mentioned above.

I'm working on a custom feeds tamper plugin that can convert the GUIDs to the image URIs that have already been imported by the first importer, but I'm completely lost on how to retrieve the images in the code.

So, the question is: how do I convert an previously imported image file GUID into the actual image's URI?

I came up with a solution, simply using a DB query to get what I want. Here is the callback for the tamper module. Hopefully someone will find a better solution, if it's possible.

function myfeedsmodule_tamper_imagekey_callback($result, $item_key, $element_key, &$field, $settings) {
  $field = trim($field);
  if ($field == 'NULL') {
      $field = NULL;
      return;
  }
  $result = db_select('feeds_item', 'f')
          ->fields('f', array('entity_id'))
          ->condition('guid', $field, '=')
          ->condition('entity_type', 'file', '=')
          ->condition('id', 'my_image_importer', '=')
          ->execute()
          ->fetchField();
  if (!$result) {
      $field = NULL;
      return;
  }
  $entities = entity_load('file', array($result));
  if (!$entities) {
      $field = NULL;
      return;
  }
  $image = current($entities);
  $field = $image->uri;
}


Can I use Pathauto with additional url values? Is it possible to use pathauto url aliases and still use additional url parameters?

For example, I use pathauto for polls to map "node/123" to "poll/title-of-my-poll".
The poll results are at "node/123/results" but using "poll/title-of-my-poll/results" doesn't work.

The Sub-pathauto module is for exactly that purpose.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.

  For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


How to programmatically assign user roles I am assigning a role to user by this code:

$user = user_load($user->uid);
$role = user_role_load_by_name("10-dis");
$user->roles = $user->roles + array($role->rid => $role->name);
user_save($user);

I need to replace this role with a new role, means I need to change user role according to some condition. How can I programmatically reassign user role?

Drupal core user.module provides a simple function to add/remove roles to/from a user. See user_multiple_role_edit().

$uid = 12345; // The user ID of the account you want to change.
$role_id = 4; // The numeric role ID you want to add.
$role_id_rm = 3; // The numeric role ID you want to remove.

user_multiple_role_edit(array($uid), 'add_role', $role_id);
user_multiple_role_edit(array($uid), 'remove_role', $role_id_rm);


How to calculate result from fields inserted? I'm new to Drupal. Can anyone advice me on what's the method of collecting data information from inserted results?

For example, suppose I have book content type, when I insert data into its fields I want a page to show results of the following:

How many book has been inserted? (eg. 5 books)
How many magazine? (eg. 2 magazine)
How many references?(eg. 1 reference)
How many novels? (eg. 2 novels)
How many guide book? (eg. 0 guide)

I've been trying to figure this out through and my last option which is to code the result myself(the hard way).

Such page can be creating using various approaches, as further explained below.
Using Views and Views Calc
Use the Views module, together with the Views_Calc module. Here is a quote about Views_Calc (from its project page):

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).
You can also create custom dynamic fields that can be used in any view using SQL snippets like CONCAT('field_first_name', ' ', 'field_last_name') or DATE_FORMAT(node.created, '%m/%%d/%Y'). The custom fields are set up in admin/settings/views_calc.

Refer to the question about How can I show average votes of fivestar nodes? for some screenprints about how to use this module.
Using Forena
If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Forena module. Here is an excerpt about that from its Community documentation:

Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc.
Disclosure: I'm a co-maintainer of Views_Calc and Forena,
I hope this does not violate the site's policy on self-promotion.


Drupal Commerce: How to validate payment method settings? The code add settings for commerce_mymodule (for example) commerce payment module. Can I validate 'mymodule_deadline' variable and how?

/**
 * Payment method callback: settings form.
 */
function commerce_mymodule_settings_form($settings = NULL) {
  $settings = (array) $settings + array(
    'mymodule_min' => '',
    'mymodule_secret' => '',
    'site_mode' => 'DEMO_MODE'
  );

  $form = array();

  $form['mymodule_deadline'] = array(
    '#type' => 'textfield',
    '#title' => t('Order payment deadline'),
    '#description' => t('Deadline for payment - default 7 days (max. 30 days).'),
    '#default_value' => $settings['mymodule_deadline'],
  );

  return $form;
}

I found a solution - because it is a FORM I using the FORMAPI. More accurate hook_form_alter() to add my custom validation handler and next is trivial. Code:

/**
 * Implements hook_form_alter()
 */
function commerce_mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rules_ui_edit_element') {
    if ($form_state['element_settings']['payment_method']['method_id'] == 'commerce_mypaymentmethod') {
      $form['#validate'][] = 'commerce_mypaymentmethod_settings_validate';
    }
  }
}

and validation function

function commerce_mymodule_settings_validate(&$form, &$form_state) {
  $deadline = (int) $form_state['values']['parameter']['payment_method']['settings']['payment_method']['settings']['mymodule_deadline'];

  if ($deadline < 1 || $deadline > 30) {
    form_set_error('', t('Enter only digit positive value between 1 -30 (days) in Order payment deadline. @value', array('@value' => $deadline)));
  }
}


Commerce cart allowing quantity than In stock I don't know on how to validate the quantity, meaning if user add the quantity more than In stock, it should not allow the user to add more quantity than In stock(quantity available), I think it can be achieved in rules, but Im not sure to do that any pointer would be helpful!

commerce stock module check the quantity and prevent add max than stock,also if the stock be 0 it change add to cart button to out of stock.

Also if you want to implement it by yourself you can do it with rules


How to Apply Panelizer on already created nodes of a particular node type? I've got a content type Article
with created nodes of that content type

Then I decided I want to use Panelizer, but i discovered I have to manually modify each node to apply panelizer

-I enabled the "Node template" display in the Pages admin (admin/structure/pages).
 - I have tried Display Suite, but I want to use Panelizer

Its like the node will have its own Panelizer isolated from global Panelizer settings.

The module's lead maintainer, merlinofchaos, responded to this on drupal.org; in short, it's only possible if using the IPE, there's an option to make the changes global i.e. affect the default configuration, otherwise the changes have to be made via the entity's Panelizer tab, e.g. admin/structure/types/page/panelizer.


How do I show an image in a Drupal 7 module? I'm creating a module and need to add some images to the admin part of it. I've created an images folder in my module folder but I'm not sure how to get the exact path to the images to echo them in my module.

The following code example presents how to get the full path to an image-test.jpg image included in a simpletest module.

$image = theme('image', array('path' => drupal_get_path('module', 'simpletest') . '/image-test.jpg'));


How to implement a multi-themed site? I will soon start building a new reasonably large site, that will be presented to the end-user as several different sites. Different domains will map to different sections within the site, and will also have different themes.

How should I implement the "multi-theme"?

I'll be posting some ideas of my own, which I would love some feedback on, but would also very much like to hear other suggestions.

I use the Themekey module.  This allows me to give each area a distinct look without even touching any code.  It also integrates with the Print, Revisioning, Organic Groups, and other major modules out-of-the-box.

Some of the things this module enables you to do (from the module page):

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server


How to uninstall the Service links module? I had a hard time with the Service links module (version 7.x-2.1) in Drupal 7. All the harder that links showed for some articles and not others. So while testing and trying to figure out how to configure, it took some time before I realized there were some issues in it.

Anyway, icons are poors, and I replaced it by the Easy Social module, which is quite fine for me and such a pleasure to configure as it is so easy and understandable.

The issue I have now is to remove the Service links module: I could disable it, and it remains listed as part of the modules (actually there is quite a bunch of modules in Service links). But then when I go to the uninstall tab, it does not show up.

I tried the module widgets on top of Service links to see if I could better configure the display of the links, but it didn't help. And I can't remove it either. My install is quite new and clean.

Any suggestions about how to uninstall the Service links module?

As far as I can see, Service Links 7.x-2.1 does not create tables of its own and the uninstall hook only deletes some configuration variables.

If you can't see the module in the uninstall tabs then you have probably deleted the module's folder before uninstalling. If this is the case, you can restore the module's folder and then uninstall the module (no need to enable it again).

Or you can run DELETE FROM variable WHERE name LIKE 'service_links_%' to your database.


Why does drupal_http_request return a 400? I am having issues sending a POST via my module.
In my browser's REST client I get a 200 with
POST https://mydomain.com
username=myuser&password=password1

So I know that the service is working fine.
I tried to replicate this call in my Drupal module with
$url = "https://mydomain.com";
$data = array(
    'username' => 'myuser',
    'password' => 'password1',
);

$data = http_build_query($data, '', '&');
$options = array(
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($url, $options);

The response I get is a 400. according to this I am not constructing the request correctly.
Question: How should I change my code in order to get a 200?
Note: I am using Drupal 7.
Thanks.

It's probably that you are missing the Content-Type header, as detailed here. For Drupal 7, this should look like this:

<?php
$response = drupal_http_request(
 'http://www.example.com',
 array('headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
 'method' => 'POST',
 'data' => 'param1=value1&param2=value2'));
?>


how to hide articles page from home page in drupal I have added article page in my project and made Views for that, but articles page also display on the front page. How to hide article from home page?

you have to untick "Promoted to front page " on structure / content types / your content types / publishing options, for every content type you have.


Show and hide form element based on values of other form elements $form['bookpage'] should be hidden at first. Then should be shown based on user selected value in $form['student'].

But somehow, before user selects anything, upon loading the option list, it already triggers the $form['student']'s ajax function and shows the $form['bookpage'].

Why is this so?

P.S. _lms_user_get_students will return following array:

  array('0'=>'----', 'all'=>'All', '2456'=>'Student A', '2462'=>'Student
  B')

 $form['student'] = array(
        '#type' => 'select',
        '#title' => t('Student'),
        '#options' => (!isset($form_state['values']['book']) || $form_state['values']['book']==NULL)?array('0'=>'----'):_lms_user_get_students($form_state['values']['class']),
        '#prefix' => "
",
        '#suffix' => "
",
        '#id' => 'select-student',
        '#ajax' => array(
            'callback' => 'ajax_student_select_callback',
            'event' => 'change',
            'wrapper' => 'statistic_table_div',
            'method' => 'replace',
            'effect' => 'fade'
       ),
   );

  $form['bookpage_toggle'] = array(
        '#type' => 'hidden',
        '#value' => 'off'
  );
$form['bookpage'] = array(
            '#type' => 'select',
            '#title' => t('Page'),
            '#options' => (!isset($form_state['values']['book']) || $form_state['values']['book']==NULL)?array('0'=>'----'):_lms_user_get_bookpages($form_state['values']['book']),
            '#prefix' => "
",
            '#suffix' => "
",
            //'#disabled' => TRUE,

            '#states' => array(
                'visible' => array(
                    ':input[name="bookpage_toggle"]' => array('value' => 'on'),
                ),
                'invisible' => array(
                    ':input[name="bookpage_toggle"]' => array('value' => 'off'),
                ),
            )
       );

    function ajax_student_select_callback($form, &$form_state) {

        //show page drop
        if($form['student']['#value'] == 'all') $form['bookpage_toggle']['#value'] = "on";
}

Why the in-between form element? You can use the states API to check for a value in a select as well. Just check the student form element and it's value all.

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      ':input[name="student"]' => array('value' => 'all'),
      // Use multiple lines here for an AND condition. eg:
      // ':input[name="other-field"]' => array('value' => 'all'),
    ),
  )
);

This way you can remove the AJAX callback, and the bookpage_toggle element.

If you want to support multiple conditions, you can wrap the jQuery selectors in another array  to function as an OR:

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

Finally if you want exclusive OR (XOR) you can do it like this to toggle on one of the elements, but never both of them:

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

See this comment for AND, OR and XOR and a combination of those.


How to implement this event tracking to google analytics module I need to implement this event

setTimeout('pageTracker._trackEvent(\'NoBounce\',\'NoBounce\',\'Over 30 seconds\')',30000);

with the Google Analytics event tracking module, I do not understand how to proceed and create this event, The event is useful for count a bounced visitor only if the visitor leaves before 30 secons, I need to add that event, any help would be appreciated. Thanks

The GA Event Tracking module is designed to react to a number of different binded JS events. You're limited by what DOM events that jQuery can bind to. As such, there is no settimeout event.

One solution that comes to mind is adding some custom JS to the standard GA module. Go to configuration page under the Custom Javascript Code in the Advanced Settings fieldset. There you can add what custom JS needed to trigger your setTimeout GA event.


MigrateSQLMap with multiple same-name source keys? I'm using migrate module 7.x-2.5 with a MySQL source database. My records are defined by the intersection of two tables, so I need two keys in my $source_key parameter to MigrateSQLMap(). I've done this before, no problem. But in this case, the columns have the same name, both "id". Because the column name is used as the key in the $source_key  array, the second "id" would replace the first "id".

I tried defining an alias for one of the columns with addExpression() and using the alias (type_id) as one of the keys. This correctly registers multiple source keys and shows the correct record count on drush ms, but fails on drush mi with a SQL error: "Column not found: 1054 Unknown column 'type_id' in 'on clause'".

In the short term, I can just create a new column in one of the tables and duplicate the "id" values, but I'd like to know if there's a way to do this entirely in migrate code without altering the source database.

I'm not aware of a solution without altering the source database -- although there are in my opinion clean ways of altering the source DB; and it's not a ton of code:

In either your migration module hook_install() function or a pre/post Import hook call (https://drupal.org/node/1343112) simply using a custom db_query() such as:

db_query("CREATE TABLE foo LIKE other_table; INSERT INTO foo FROM (intersection query); ALTER TABLE foo (change id to type_id);");

You can drop/recreate the table as apart of a pre/post import call.

You just have to get the SQL right and it's all of 3 SQL statements, and 1 or 2 Drupal hook functions to make it all repeatable using Migrations.


SMTP settings not being used I've been working on a existing drupal site I got from a client, and have been running into some problems when I try to change the smtp settings. The SMTP module was already installed, but when I change the settings in SMTP Authentication Support and send a test mail, it works, but it still keeps using settings from somewhere else (I presume). I've checked the config files for settings, but I can't seem to find anything. All cache has been turned off. I'm not an expert on drupal by any means, so is there some other place I should be looking or do I need to change some other settings?

Refer to the answer to How to configure webform with smtp , which includes:

  If you have SMTP module installed in your drupal site than you would have to configure the SMTP settings (/admin/config/system/smtp) for sending the email ...

It also includes an example for configuring SMTP.


How to use Rules send an email with a list of nodes that fill certain conditions? I would like to send an email everyday that has a list of nodes that are filtered by certain conditions. I think the Rules module would be a good place to start.

Real Example:

Content Type named "Issue".
Field inside Issue that connects a user as Responsible Party for the issue.
Field inside Issue that defines it as either "Active" or "Resolved".
Email a list to the responsible party of their Issues that have a "Active" status.

If this can be done with Rules, what event do you have it react to? I would guess the core functionality of it would be put in a component that rescheduled itself every 24 hours. Then the action of the component would be "Send Mail". How would it grab the list of nodes that fulfill the conditions?

When you want to run a rule periodically, use the event Cron maintenance tasks are performed.

This will trigger your rule whenever cron runs.

See the cron documentation on drupal.org for more information on cron and its configuration.

Because this action doesn't specifically involve nodes, the next problem is loading the nodes you want to act on.

How you do that depends on which nodes you want to load the nodes. Examples are (there are likely also other ways):

The Load a list of entity objects from a VBO View action that is provided by the Views Bulk Operations module. This was you can set up a view that lists the nodes you want to target and load the nodes from that list.
The Fetch entity by property action. This could be used to fetch all content of a given content type.

When you have a list of entities you can loop add a loop to your actions to loop through the list and perform actions on each entity.

If you need to check perform conditions as you are looping through (like checking the value of a field on the entities) you can use the Conditional Rules module to add if blocks.


Select selection exposed filter using XML Views Backend I'm using the Views XML Backend to pull in data from a URL.

I'd like the user to be able to optionally be able to select a value for a single field and display the record for that selection. For example, if the XML had information for different offices, I'd like to show the user the records for all of the offices, but allow them to pick a specific office from the list to see only the record for that office. The URL can take a query string or POST parameter with the search terms, but I'm fine with letting the search be done by Drupal.

How do I achieve this in a way that leverages Drupal's capabilities, as opposed to doing the filtering in jQuery?

I already have the view created, but I only see exposed filter options I saw were XML: Numeric, XML: Text, and Global: Combine fields filter.  What I'm looking for is something like XML: Pick a Value.

The Views XML has no idea of the data in your XML. Have you seen this tutorial video from the project page for Views XML Backend.

http://screencast.com/t/mnfEHRT7

They create a simple exposed filter for 1 xml "field" in the view that is searchable by a text filter. This is the simplest form of what you want. Using the exact same type of filter you could:

use hook_views_preview and change text field to a select list with options. You would build the options for the list by re-processing your XML file and using xpath queries to find the possible values you want in your select list. You'd likely want to cache these results to a drupal cache table.
you could also attempt to create your own Views Filter that does this; but thats harder too.


Print a view within another view Here is my situation,

I have a view-1 which will list the node titles based on Content: Taxonomy term CONTEXTUAL FILTERS
View-2 which will list all the taxonomy terms (of a vocabulary) with node count.

Now how do I print the view-1 as a custom field within view-2.

The reason I am trying to do this is, I am trying to construct a UI which will display the nodes on click on taxonomy terms with count.

I tried using below code to print view-1 as a custom PHP field on view-2, but it did not work for me.

    print views_embed_view('view-1','block_1', $row->tid);

$row->tid is the term ID argument I am trying to pass

The module Views Field View may work for you. It's worth to try.

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

OR

You can even create two displays in a view - one is Page and the other is Attachment.
For your case, view-2 would be Page and view-1 would be Attachment.

You can select various settings in the attachment view such as Attach to, Contextual filter, etc.

Check this answer about an attachment view. I had a book Drupal 6 Attachment Views, but could not find a book for D7.


Drupal 7 Views - Date Filter Cannot See Year I am trying to create a view with exposed filters for a date field with a start date and required end date.

However, I cannot see the year for the date when I created the filter. I can only see the day and the month. I am using Views 7.x-3.11. I also have both the Date module and Date Views module installed and enabled.

Does anyone know how I can have the year show up in the filter option? I have searched and searched for a solution, but I have not found anything yet.

To anyone who may be curious, I discovered the issue that was causing the year not to show. @75thTrombone put me on the right track.

After digging through the date popup module, I found that the views filter defaults to the Short date type format, which for my site had been set to M j (e.g. Jan 28). Once I added the year back to the Short date type format, the filter worked as expected.

It may be possible to configure which date type is used in the views filter, but I did not see a way to do that. The date popup module is using variable_get('date_format_short', 'm/d/Y - H:i'). I will also update the module and see if that allows for a custom configuration.


User order views does not display orders for user despite permission The user order views' access permission is "View own orders of any type". I have given this permission to authenticated users yet the user sees only this message "You have not placed any orders with us yet.". What am I missing?

You've most likely edited the View to include a new relationship - perhaps from line items to products - that adds an access check to the View's results that the user doesn't pass. If this is the case, open your View's "Advanced" fieldset, edit the "Query settings", and check the box to "Disable SQL rewriting".


Display block based on main content type with view I have created a view in a block, to display some related information to the current content type being displayed into the block. More precisely, I want to display the block only for book pages.

What I did is to add a contextual filter based on content type.
For "WHEN THE FILTER VALUE IS NOT AVAILABLE", I provide a default value for "PHP contextual filter code" as follows

$node = node_load(arg(1));
return $node->type;

For "WHEN THE FILTER VALUE IS AVAILABLE", I use "Specify validation criteria" for content types with "book page".

I tried this but it didn't work. I think because I am using aliases in the url, it does not work.

What am I missing?

P.S: My final goal is actually to extract the group audience from the current book page and display the admins of that group into the block.

In your case you don't need to provide any default value with PHP code.

Remove your contextual filter and add new one: Content: nid.

"WHEN THE FILTER VALUE IS NOT AVAILABLE"

Provide default value -> content ID from URL

"When the filter value IS available or a default is provided"

Specify validation criteria

Validator -> Content -> book


Are 'safe_value' values generated dynamically from the 'value' value? I'm changing the content of an HTML field using entity_metadata_wrapper, and I see 3 values, like value, format, and safe_value.

My question is if I have to also edit safe_value or it will be generated dynamically. Thanks

PS: I edited and saved only value then in next load, the other were empty. I went to the node and clicked Save and the safe value was regenerated. Maybe I should call a hook after editing value?
Currently I'm using the check_markup function to generate the safe_value from the modified value

Yes. safe_value is derived from value; safe_value contains the results of _text_sanitize() after it applies all the filters you've set on your text field.

It isn't set after a node save; it's set on a field load; the field module loads it via hook_field_load() with its text_field_load() invocation.


How do I redirect users after they submit a form? How do I redirect users after they submit a form? I tried the following code, but it doesn't work. It says the route doesn't exist.

public  function submitForm(array &$form, FormStateInterface $form_state){
   $url = Url::fromRoute('/mon-profil/obtenir_document'); // == /node/1
   $form_state->setRedirectUrl($url);
}

You're getting that error because fromRoute() takes the route name as the argument, not a literal path.

Assuming you know the node id you want to redirect to:

$url = Url::fromRoute('entity.node.canonical', array('node' => $node_id));

You don't ever want to redirect to internal paths like that (in your question) because they are subject to change.


How do I know when a render array will be processed properly? I'm still getting to grips with render arrays and there similarity to FAPI arrays is a point of confusion. I'm customizing a node form using hook_form_alter and I wanted to insert some custom markup in place of a field.

I have inserted a table render array as a child of a the field FAPI container array and much to my surprise the table was rendered. What's going on here?

How do I know when a render array will be processed properly?

See Render Arrays in Drupal 7

  Note: While render arrays and arrays used by the Form API share
  elements, properties and structure, many properties on form elements
  only have meaning for the Form API, not for the Render API. Form API
  arrays are transformed into Render arrays by drupal_get_form.

Because form arrays are converted to render arrays before they are rendered if you add a render array to the form array it will be also rendered when the whole form-array-converted-to-render-array is processed.

As the quoted text says you have to keep in mind that form arrays are not directly renderable, they have to be converted first to a render array. During this conversion, render array attached to the form array are bypassed because they are already a render array.


Restricting view of content to one role I know how to change edit and create permissions of a content type to one role.

But what i need is that a user that has the role 'consultant' is the only one that can see the content that was created of the type 'consultant info'.

I can only find a way to watch "own published content" but that isnt enough because their are multiple consult accounts that need to see each-others content.

Ive already looked at modules like content_Access but they also don't provide this.

Sorry missunderstood your questtion, I think ->

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

is what you are looking for.


Rules condition for comment status Sometimes, when a user post a comment, it not published immediately; this can be for several reasons (e.g. spam suspect, anonymous user). I want to use the Rules module to send an email to users that flagged the node for new comments, but only when the comment is published. I cannot find any condition in the Rules module that allows me to check if the comment is published or not.

Perhaps someone has a way to accomplish this.

What you need is a rule that is fired when the comment is first published and that seems very straight forward to me. If you need any further help on that, please let us know.


Adding content type to the class of each views row I have a view that has a filter to only pull results from 2 content types.  I would like each views entry to have a class that shows the content type of the node.  How can I do it?

You can add that into the views fields template for the row or you can add a node type field to your view, and make sure it's first or before the field you want to add the class to, and disable its display.    Then, you can go to the field you want to add the type class to, select rewrite output, and use the contents of this first field as a replacement value in the class of the wrapper element.

Just rereading, the above just wraps a field in your row.  To put that class in the row's html, you could edit up views-view-fields.tpl.php for your specific view and add a div wrapper yourself with that information in it (grab it all out of the $row variable provided).  Keep the node type field in there but have it not displayed.

So, for example, if your view is named foo, you could create a views-view-fields--foo.tpl.php with this in it:

<div class="<?php print $row->node_type; ?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

where, if I am cutting and pasting right today, the only thing I've added is the opening div and closing div.  This then wraps your whole row in your own div with class of nodetype.

You can find all of these templates in the views style information area (make sure your views code matches mine).  Just save them in or under your theme directory.

ADDITION:

If you want to have the class in
 instead of adding another
 inside it, you can copy views-view-unformatted.tpl.php to one appropriately named for your view and grab the information needed for the node-type out of the $view variable there.  You could also use a views_preprocess() function to do it, although for stuff like this I like seeing it in the template, but that's just me.  The function should be mythemeormodulename_preprocess_views_view_unformatted(&$vars) and you can add or modify any of the vars you want, once again, since $view is present, all the information about the view is as well.  For ideas, check out the views code in sites/all/modules/views/theme/theme.inc, or where ever module code is stored on your machine.


unwanted cache_page flush for no reason On my drupal 6 site, from time to time, for no obvious reason, all caches gets cleared. Native caching is enabled (normal caching mode, minimum lifetime 1 day). Cron is not setup to run automaticaly. No rules are created regarding flushing of cache. In meantime I do not do any website manipulation like editing content, editing taxonomy or installing new modules.
What I can see in recent log entries is that users keep logging in and out, users make orders (ubercart 6) and several not found errors probably caused by bots.
What can trigger such automatic/unwanted cache clearing, what logs should I check or how to fix that? Thank you.

you could place a watchdog('cache_clear_backtrace', print_r(debug_backtrace(),1); in that cache_clear_all() function to see from the log why/ where that happens.


Load .js only if block is loaded Yes, something like that. If block and it's content are loaded in the page (so I guess detect by ID or something) it would load the .js, but if block is not loaded, it wouldn't load the .js.

I need this, because now each time when the block is not loaded, it still always loads the .js from theme in every page no matter what and that code interacts for some reason with other javascript elements like flexslider and it disables it for some reason and etc. Which is bad.

So it should load the .js only when the block is rendered/printed.

Depends on what type of block your need the js for. If it's a custom block you created in a module, you can just tack drupal_add_js into the block definition function.

If your trying to add it to a block was created by someone else's module, or drupal created (IE, you didn't create it with a module), you could create a simple module that uses hook_block_view, which is fired whenever a block is loaded. You should be able to check from there if that is the block you want, then use drupal_add_js to load your js from that module.


How to add a custom link to login form block with hook_form_alter How to add a link with custom path to my login block with hook_form_alter. I 've created a custom module but i dont know what to add to my hook_form_alter function.

In Drupal 7 you can use #markup attribute, as suggested by MOLOT

/**
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $form['link'] = array('#markup' => l(t('Link text'),'node'));
      break;
  }
}

Note:

hook_form_alter
Forms API reference


How can an entity reference field be displayed as a select list that shows the selected entity? The Problem

I have a couple of entity reference fields that references a hierarchy of nodes. For the sake of simplicity let's use just the top level example Video Game -> Video Game Release

So when I look at the video game "Assassin's Creed 2" I see two releases "Assassin's Creed 2" and "Assassin's Creed Ezio Trilogy".

Background info that isn't necessarily important to the question:

  ! The reason for the entity reference is on "Assassin's Creed Brotherhood" I would also have two releases "Assassin's Creed Brotherhood" and "Assassin's Creed Ezio Trilogy".

  Assassin's Creed 2 (Node: game, ID: 1)

  Assassin's Creed 2 (Node: release, ID: 2)
  Assassin's Creed Ezio Trilogy (Node: release, ID: 3)

  Assassin's Creed Brotherhood (Node: game, ID: 4)

  Assassin's Creed Brotherhood (node: release, ID: 5)
  Assassin's Creed Ezio Trilogy (Node: release, ID: 3)

When I view the node "Assasin's Creed 2" I'm currently seeing both releases one after the other. I styled these using display suite and they look fine. However I want to display only one of them at a time with a tab, select list, or something of the like to allow me to switch between them.

My thoughts

I was unable to find a module that could perform this but I feel one may exist.
I could use a simple jquery tab ajax but wasn't sure if their was already a drupal way to do this.
Perhaps I could use exposed views and a views embed field to show all the referenced nodes but then the performance would suffer significantly.

The question

How do I display an entity reference field as tabbed or select list content? Preferably without the performance drop of an embedded view.

You have 2 relatively simple options without creating your own module and field display code (in a module).

use Views to generate the select lists you want. You can do this for example with a ctools dropdown or jumpto displays. While you're using a view you can always set Views to cache the results of your view so its not cumbersome after the 1st page load for all other visitors. You can even define views and attach them to your node if you want with field_views_field module.
Use Display Suite on your site and create a Custom Field in DS for any fields you want custom output for, like your select list. Then in the PHP area of the custom field you can access the currently loaded $entity fields and generate whatever HTML you want for your field output. You would then hide the default field display of your field, and show your custom DS created field for your content type.

I'm about to do (2) above with a slideshow content type where per-slide the content editor can select the text foreground and background color using the field_color module which would best match an uploaded image to the Node. Then in DS I will make a custom "slide_text" dyanamic field that examines the color values and basically outputs:

<?php
// This is pseudocode and untested.
$wrapper = entity_metadata_wrapper('node' $entity);
$text_color = $wrapper->field_foreground_color->value();
$bg_color = $wrapper->field_background_color->value();
$text = $wrapper->field_slide_text->value();
echo <<<EOFHTML
<span class="ds-slide-content-field"
      style="color: $text_color;
             background-color: $bg_color">
    $text
</span">
EOFHTML;
?>


CKEditor 4.2 and Media Module, Has anyone gotten this to work? Been trying to create a working mix of these modules and only seem to succeed if CKEDitor is using version 4.0.3 or lower.

Any insight here would be huge. Thanks!

CKEditor 4.1 introduced a feature called Advanced Content Filter. It might be stripping some code. You can test if it's the cause by adding this code your ckeditor/config.js file:

CKEDITOR.config.allowedContent = true

Granted, you shouldn't just leave it true, but it will give you an idea if that's the problem.


Cannot redeclare libraries_drush_command() After issuing the following command in the base drupal folder (/var/www/html)

$ drush status

I get the following response.

PHP Fatal error:  Cannot redeclare libraries_drush_command() (previously declared in /var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in /var/www/html/sites/all/modules/libraries/libraries.drush.inc on line 25
Drush command terminated abnormally due to an unrecoverable error.                                                                 [error]
Error: Cannot redeclare libraries_drush_command() (previously declared in
/var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in
/var/www/html/sites/all/modules/libraries/libraries.drush.inc, line 25

This is a new server install using RHEL 6.4 (Santiago) and drush 6.0 installed through pear.

Where I might begin to fix this?

Removing /var/www/html/sites/all/modules/libraries/libraries.drush.inc cleared things up. I bungled things up somewhere. IRC #drupal-commons confirmed Clive's note above.


How to update field values of a content type's nodes when when viewing a particular content type page I'd essentially like to alter the values of a specific custom field of a few of nodes before they're displayed in a view on the 'page' of a specific content type.

The content type is that will be displayed is a park. When a park is viewed, one of the blocks shown is a view that fetches and shows several nodes that are also 'parks'.

This park content type has a field called proximity. I'd like to change the value of proximity (based on a mathematical formula) for all parks before the view is processed, so that I can use proximity in the view.

From what I understand so far, I should use a park_preprocess function, which calls some sort of hook to change the proximity values. Is this correct, and how would I do it?

hook_node_view() will be used in this scenario.

function hook_node_view($node, $view_mode, $langcode) {
  if($node->type == 'park' && $view_mode == 'full')
   {
    /* change the value of proximity here after applying your formula.
      * Here you have complete node array, so you alter the result easily here.
    */

   }
 }


Body field data disappeared EDIT: Looks like I accidentally changed number of values for this field to 1 - it should be Unlimited. It's working now, thanks everyone.

I don't know what I did but I noticed that all (except the first one) body field data in all the nodes disappeared - they're not even available in editor.

All the data is still in DB (in field_data_body table) but it's not showing on website.

I have no idea how to fix this, has anyone had the same problem?

See permission for this field.

In the admin section: /admin/people/permissions


How do I load taxonomy terms? I want to load taxonomy terms by tid, but I didn't found how. Only how to load taxonomy by name, but now I have term id and I need to get value of fields.

I call this on public function build() for custom block.

My code:

$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('menu');
foreach ($terms as $term) {
    //var_dump($term->tid);
}

in Single Manner

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(TID);
    $value = $term->FIELD_MACHINENAME->value;

Example : load title and language of term id =2

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2);
    $title = $term->name->value;
    langcode = $term->langcode->value;

And for load Multiple as you wanted

  $terms = $entityManager->getStorage('taxonomy_term')->loadMultiple($terms);
  foreach ($terms as $term) {
      var_dump($term->tid->value); //return tid of term
   var_dump($term->name->value); //return title of term
  }


Retrieving jsonp data with callback function I need to call a service to retrieve the available values for a select in a form I am creating. Therefore, I need to do this in the .module file and load the options with an array of items that I received from the service.

I retrieve that results but due to it having a callback function, I cannot seem to iterate through the data to retrieve only certain values from the data.

I have the following.

$request = drupal_http_request('http://[local]/TemplateManager/GetRenderingStrategies?Wizard=false&callback=jsonCallback');

I get back this.

jsonCallback([
{
    "HTMLRenderingStrategyId": 1,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "19223fcf-45c2-452b-aac6-ba357169ff26",
    "Name": "DEFAULT",
    "FormTemplateView": "/Templates/Default/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/Default/css/Base.css",
    "CrossSellTemplateView": null,
    "CrossSellMaxProgramsToDisplay": null
},
{
    "HTMLRenderingStrategyId": 2,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "2ea1ecb7-0281-4361-87ee-d4cfe12c9b0c",
    "Name": "EMD",
    "FormTemplateView": "/Templates/EMD/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/EMD/css/Base.css",
    "CrossSellTemplateView": null,
    "CrossSellMaxProgramsToDisplay": null
},
{
    "HTMLRenderingStrategyId": 3,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "e2d7ed2e-7ed7-4d2e-aecb-0a589c7ad338",
    "Name": "ELEARNERS",
    "FormTemplateView": "/Templates/eLearners/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/eLearners/css/Base.css",
    "CrossSellTemplateView": "/Templates/eLearners/CrossSellTemplate.cshtml",
    "CrossSellMaxProgramsToDisplay": 10
}]);

What is my next step to pull out only the "Name" from the result set?

I am at a loss here. I tried looking for the answer and it seems all the jsonp calls are done in javascript/jQuery and that doesn't really suit me.

If you feel I am doing this incorrectly, please let me know. I have never worked with jsonp or json and Drupal for that matter.

You can create a custom function called jsonp_decode with one argument to convert JSONP format to JSON format and return decoded JSON

function jsonp_decode($jsonp) {
  $jsonp = preg_replace('/^.*?\(/', "", $jsonp);
  $jsonp = preg_replace('/\);\s*$/', "", $jsonp);
  return drupal_json_decode($jsonp);
}

Then you can pull the "Name" from the result set as the following code:

$request = drupal_http_request('http://[local]/TemplateManager/GetRenderingStrategies?Wizard=false&callback=jsonCallback');

$names = array();

$items = jsonp_decode($request);

foreach($items as $item) {
  $names[] = $item['Name'];
}

var_dump($names);


Adding an operation to Content Types I'm working on a module. I've added a tab to each Content Type in hook_menu using something like:

$items['admin/structure/types/manage/%/stuff'] = array(
    'title' => 'Manage stuff',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stuff_content_type_stuff_form', 4),
    'access arguments' => array('administer content types'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100
);

The tab appears fine when I visit admin/structure/types/manage/article/edit, for example. However, when I view admin/structure/types to view the list of content types, I'd like to see "Manage stuff" listed as a link in the "operations" column alongside "Manage fields" and "Manage display".

Is this possible? Can someone please provide a way to do this?

The admin/structure/types page is created via the hook_menu() in the node module:

$items['admin/structure/types'] = array(
  'title' => 'Content types',
  'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  'page callback' => 'node_overview_types',
  'access arguments' => array('administer content types'),
  'file' => 'content_types.inc',
);

which shows that the page is generated by the node_overview_types function in content_types.inc:

/**
 * Displays the content type admin overview page.
 */
function node_overview_types() {
  $types = node_type_get_types();
  $names = node_type_get_names();
  $field_ui = module_exists('field_ui');
  $header = array(t('Name'), array('data' => t('Operations'), 'colspan' => $field_ui ? '4' : '2'));
  $rows = array();

  foreach ($names as $key => $name) {
    $type = $types[$key];
    if (node_hook($type->type, 'form')) {
      $type_url_str = str_replace('_', '-', $type->type);
      $row = array(theme('node_admin_overview', array('name' => $name, 'type' => $type)));
      // Set the edit column.
      $row[] = array('data' => l(t('edit'), 'admin/structure/types/manage/' . $type_url_str));

      if ($field_ui) {
        // Manage fields.
        $row[] = array('data' => l(t('manage fields'), 'admin/structure/types/manage/' . $type_url_str . '/fields'));

        // Display fields.
        $row[] = array('data' => l(t('manage display'), 'admin/structure/types/manage/' . $type_url_str . '/display'));
      }

      // Set the delete column.
      if ($type->custom) {
        $row[] = array('data' => l(t('delete'), 'admin/structure/types/manage/' . $type_url_str . '/delete'));
      }
      else {
        $row[] = array('data' => '');
      }

      $rows[] = $row;
    }
  }

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add'))),
  );

  return $build;
}

So, one way I can see to do this would be to in your module, do a hook_menu_alter() and point the page callback to a function in your module and just add to the core one's functionality, eg, something like this:

function YOURMODULE_menu_alter(&$items) {

  $items['admin/structure/types']['page callback']='YOURMODULE_node_overview_types';
  unset($items['admin/structure/types']['file']); // or point it to YOURMODULE_pages.inc if need be

}

and then basically just copy the code from node_overview_types() into YOURMODULE_node_overview_types() and then put in your functionality, eg, change the colspan to 5 or 3 and add in the l() to your menu item.

NOTE:  Of course, if the node module is ever updated you'll have to keep that in mind and possibly redo this.  So, yes, since a render array is returned, you could instead modify this in any number of hook alters before the page is rendered. If you want to look into this approach, Render Arrays in Drupal 7 is a good place to start.

ADDITION:

For completeness, this is one way you could use a hook_page_alter():

function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $types = array_keys(node_type_get_types());

    $page['content']['system_main']['node_table']['#header'][1]['colspan']++;
    foreach($page['content']['system_main']['node_table']['#rows'] as $type => &$row) {
      $row[]='New menu link goes here for ' . $types[$type];
    }

  }

}

instead of the hook_menu_alter() approach above.  But also, obviously, it too relies on the structure of the array returned by the node module.


Define a Panels visibility rule programatically I'm trying to define a Panels visibility rule (access plugin) programmatically but I'm running into a problem.

My code is below.  This code works as a Selection Rule (on the Access tab), but when I try to add my access plugin as a Visibility Rule (on the Content tab), the plugin is added to the panel pane, but it doesn't show up in the UI under "Visibility rules."  So there's no way to delete it, and the title isn't shown.

I assume I failed to declare something that makes it show up in the Visibility Rules, but I haven't been able to figure out what.  I was following this guide, but my plugin is simpler than the one in the example (no configuration necessary).

<?php
/**
 * @file
 * Plugin to check whether the value matches the proximity query string
 * https://drupal.stackexchange.com/questions/33336/what-are-ctools-plugin-content-type-access-etc-and-how-does-one-create-them/33337#33337
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Check proximity query string"),
  'description' => t('Returns FALSE if the proximity search query string is set'),
  'callback' => 'mymodule_checkproxquerystring_ctools_access_check',
  'settings form' => 'mymodule_checkproxquerystring_ctools_access_settings',
);

/**
 * Settings form for the 'term depth' access plugin.
 */
function mymodule_checkproxquerystring_ctools_access_settings($form, &$form_state, $conf) {
  return $form;
}

/**
 * Check for access.
 */
function mymodule_checkproxquerystring_ctools_access_check($conf, $context) {
  if (isset($_GET['d']) && (is_numeric($_GET['d']))) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

I think probably that is due to the missing 'summary' key from your '$plugin'. A simple access plugin to check if the current page can be defined as :

$plugin = array(
  'title' => t('Front page'),
  'description' => t('Is this the front page.'),
  'callback' => 'ctools_front_ctools_access_check',
  'default' => array('negate' => 0),
  'settings form' => 'ctools_front_ctools_access_settings',
  'summary' => 'ctools_front_ctools_access_summary',
);

/**
 * Settings form for the 'by parent term' access plugin
 */
function ctools_front_ctools_access_settings($form, &$form_state, $conf) {
  // No additional configuration necessary.
  return $form;
}

/**
 * Check for access.
 */
function ctools_front_ctools_access_check($conf, $context) {
  if (drupal_is_front_page()) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a summary description based upon the checked terms.
 */
function ctools_front_ctools_access_summary($conf, $context) {
  return t('The front page');
}

The canonical reference of this could be found in the access plugins defined in the ctools module itself.


Unsubscribed from Simplenews Newsletter is there a way to find how many users unsubscribed from my Simplenews newsletter at my Drupal-7 website? And, if yes, can I detect from which particular newsletter did the user unsubscribe from?

You can click admin/people/simplenews and check on status column.
OR
you can use following code to get the data

  // fetching from the database.
  $query = db_select('simplenews_subscriber', 'ss');
  $query->innerJoin('simplenews_subscription', 'si', 'si.snid = ss.snid');
  $query->fields('ss', array('mail'))
    ->condition('ss.activated', $condition_active)
    ->condition('si.status', $condition_subscribed)
    ->condition('si.newsletter_id', $newsletters)
    ->distinct();
  $data = $query->execute()->fetchAll();

where si.status is a flag indicating whether the user is subscribed (1) or unsubscribed (0)

and $newsletters is a Array of newsletter ids to filter on


Need clarification for "use this hook and some code" type of answers Whenever the answer to a Drupal question, either here or on blogs and other articles, is to use a hook and then some example code is provided, what are the assumed steps from beginning to end for implementing this answer? These are likely left out to avoid redundancy but it's difficult to piece together the underlying, assumed foundation and skills.

Where does the given example code from many such answers to questions go? Is this essentially what building a module is? The concept of a hook is easy to understand and explained well here but how to use a specific hook to alter some piece of core to achieve something isn't clear.

For example, if the question is, "how do I change the text of such and such button" and the answer is "use hook hook_such_and_such_blahdy_blah" what does this actually mean?

Real world example: This blog about how to theme the comment block is great. But what is the author really saying to do when he says to just override the hook by copying the code from the API page and then alter the hook.

Resources I've checked out but don't mean anything without the missing foundation:

https://api.drupal.org/api/drupal
https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules

TL;DR version: Most hooks_something() go inside your custom module's
  .module, but not always. You can put alter hooks in your theme's
  template.php file for D7 or in .theme in D8.

There are several assumptions packed into those answers, and yeah they can be hard for people getting used to Drupal. Here are some assumptions cooked into those answers.

First, they assume you know have the tools and knowledge to write code for your project. Often people give those kinds of answers when asked a question where someone was looking for a module that already does what they are asking. Some of that is the nature of the community, and some of that is the nature of sites like this one.

Second, they assume you have a module or theme for custom code already started (or know how to start one).  Lots of Drupal projects will have a module that is just there to provide a few needed hooks to handle an edge case.

Third, they assume you know when to use a module vs a theme for adding the hook. Some hooks really need to be in a module, some should be in a module, and some should be in a theme. But in the end that's is often use case specific (or in the case of agencies done to be consistent with seven sites already supported by the same team).  Rarely do people give guidance which is the right choice.

Fourth, for some hooks they are assuming you know how to figure out how to get it called. Some Drupal 7 hooks (e.g. views) have a different pattern where you declare you have the hooks in your main .module file and then you define the hooks in their own file.

See also: Is it possible to define hook functions in template.php instead of the module?


How to get group ids by ids of elements of group content? I use the Group module and I have created several groups and assigned several nodes as content of these groups.

For example, I know id of some node. How can I figure out which groups contain this node ?  That is, how to get group ids by nid, if this node is a content of these groups ? And I don't want to use SQL for it. Are there methods of classes for it ?

The way Group module maintainer recommended:

use Drupal\group\Entity\GroupContent;

function getGroupIdsByEntity($entity) {
  $group_ids = [];

  $group_contents = GroupContent::loadByEntity($entity);
  foreach ($group_contents as $group_content) {
    $group_ids[] = $group_content->getGroup()->id();
  }

  return $group_ids;
}


How to have a popup calendar in a date view exposed filter? I am setting up a view, with the Authored on filter exposed. When selecting the box, there isn't any popup calendar.

Doesn't Drupal 8 come with a calendar popup in core? How can I turn this on for exposed filters with date?

This can be done with the Better Exposed Filters module.

Enable the module, set it as the exposed form handler under Advanced -> Exposed form style, on the BEF settings page dialog set the filter display option to "jQuery UI Datepicker". Save everything and you should be good to go.

Note that changing from the default date format may require you to implement hook_better_exposed_filters_display_options_alter.


User Stats Total Nodes, Comments, Flags Is it possible to create a view be that a page or block that shows the following.

-Total number of nodes user has created.
-Total number of comments (all comment types) user has posted.
-Total of how many times this user nodes or comments have beed Flaged as HELPFUL. (flag module is used for this)

All this using the path /user/%user/stats

Which means contextual filter user ID value will be provided from url path 2.

I am stuck with the three bullet points above. Or how to calculate the totals for each.

You can use Views Aggregation to count the number of results for your specific cases.

Count number of nodes authored by a user

Since your results (to be counted) are nodes it makes sense to create Content type Views:

Create Content Views with Page Display and Filter out the node types you want to count later.
Add node Title field or Node ID under Fields to test you have the correct list of content. Add Author ID or Name to test the Contextual filter later.
Set Path to user/%user/stats, set Menu Tab so it displays under Drupal tabs on user pages
Add a Contextual filter Author UID (provide default value; User ID from URL) and test by entering user ID number into the Preview, make sure you see all the nodes created by the author with that UID
Under Fields make sure you only have ONE node field (if you have both NID and Title, remove Title). You can keep the Author fields, for testing if nothing else. We'll use one unique node field to count them aggregated. If we add another node field it will force Views results to show one node per Views row, which will make counting impossible
Remove Sorting criteria - they mess up Aggregation!
Turn on Aggregation
Edit the NID Field Aggregation setting to Count or Count DISTINCT (if you don't have duplicates in your Views results Count will do)

You now have Views counting the results! If you enter user UID into Preview you will see the number of their nodes in the NID field (adjust the NID field label accordingly).

If you enter all into Preview you will see a list of all Authors (from that nodes list, if you kept that Field) and the number of the nodes they created.

If you visit a user page you should see the stats tab added to Drupal tabs. Adjust the Permissions for the Views Page to limit who can see it.

Count number of comments authored by a user

Repeat the above procedure to count comments, only start with Commment Views Type, set a different Path user/%user/stats-comment and Menu tab

Count flags

To count how many of the listed nodes are flagged you'll need a Relationship to that information, then you'll be able to list a Field with the Flag status and use Aggregation to count them, similar to the above.

There are answers/articles on how to set up Flag Relationship in Views to display various information.