Why isn't this functionality in submitForm firing? I'm in the process of writing a module. The module works very well. In the module, I generate a form which consists of one submit button, and in the .module file, I'm calling that form and the submitForm works too. I was asked to move that button into a block, so I did. submitForm still works, but the main functionality doesn't. How come?

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
* Generate button.
*/
class myModuleForm extends FormBase {

  /**
  * {@inheritdoc}.
  */
  public function getFormId() {
    return 'my_module_form';
  }

  /**
  * {@inheritdoc}.
  */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['my_module_btn'] = [
      '#type' => 'submit',
      '#value' => 'Do something'        ];
    return $form;
  }

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

  /**
  * {@inheritdoc}.
  */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $mpdf = new \Mpdf\Mpdf(['tempDir' => 'sites/default/files/tmp', 'default_font' => 'roboto', 'margin_left' => 6, 'margin_top' => 6, 'margin_right' => 6, 'margin_bottom' => 11]);
    ...
    ...
    ...
    $mpdf->Output($title."-".date("Ymd-His").".pdf", 'D');
  }
}

I googled the Mpdf library and it supports a string output. So you can use the string output to build a response and return it via $form_state:

use Symfony\Component\HttpFoundation\Response;

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $content = '%PDF-1.3...';
    $headers = [
      'Content-Type' => 'application/pdf',
    ];
    $response = new Response($content, 200, $headers);
    $form_state->setResponse($response);
  }


Menu list links of different languages of a Localized Menu are shown in all languages? I have a menu which is set to Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.

The in the menu I have several links in english and spanish languages.

In the frontend regardless the language I select all links of the menu are shown. ie: if I select english the spanish links are also shown.

What am I missing here?

I'm assuming you already have the i18n Menu Translation sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there you can select the translation mode you want, e.g. Translate and Localize (from your question it seems you also did that already).

With what's above you should be in pretty good shape to complete the finishing touch: when editing a menu link, there should be a new link Translate to actually translate the menu entry. After you entered a translation for the "original" (eg English) menu item in another language (eg Spanish), Drupal will ensure that whenever you switch to another language, the corresponding menu item will be switched also (to the matching language).

Should you have some other menu item in your original menu in that "other" language, you can safely delete that menu item. After you delete such item, that'll be 1 menu item less that is shown "in both languages" (as in your question). Repeat the above (= translate menu item and delete original duplicate item) for each of your duplicate (in both languages) menu items.

Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

translations of blocks, which requires the Block Languages (i18n_block) submodule to be enabled.
translations of taxonomies, which requires the Taxonomy Translation (i18n_taxonomy) submodule to be enabled.


Looking to change the header from a color to an image I am using the NewsCenter theme for my Drupal site, and we have had a new logo/banner designed for our website that I want to implement -- but it's not as simple as just uploading it and replacing the old logo.

This is the header of our site as it stands currently:

This is what I want to get to:

Also, with the final option, I still need to have users be able to click in the banner and get directed 'Home' -- I presume that to do this I would still upload a logo.png, but that it would just be a large transparent rectangle.

Thanks!

Add this CSS:

<style>
  #header {
    background: url('critic-banner-image.png');
  }
  #logo {
    margin: 0 15px 5px 15px;
  }
</style>

Add this background image
(use better ones that your client provides)

Replace your old logo with this:

(use better ones that your client provides)


Feeds: Is it possible to set a unique field other than the title field? I'm trying to create a feed importer that uses a unique ID that is NOT necessarily in the title field of the content type. For example, were I using the feeds importer to import a list of contacts, I'd like to have the unique ID be the phone number, yet I would prefer that the content title be the name of the contact rather than the phone number, for organization and aesthetic purposes. Is this possible? As of now, it seems I am limited to enabling only the title field as unique.

I realize I could simply put the contact name into the title field and set that as unique, but this is less prudent, as contacts may have identical names and similarly with my data, the duplicity of titles and/or misspellings is/are inevitable. Any help would be appreciated!

Thanks!

For most of my Feeds, I import the Node ID and make that unique.


Node with many product prices I have a node which needs to contain a list of product prices in the following format:

Node Title
Node Body

Product 1 URL - Product 1 Price
Product 2 URL - Product 2 Price
Product 3 URL - Product 3 Price
Product 4 URL - Product 4 Price

I'm not sure how that list of URL's and prices should be stored in Drupal so that it can be given a relationship with a specific node and displayed within the node.

Do i use taxonomy or make each url/price pair its own node?

You should use entity references for this. The end result will be that when you view a parent node, the products show up in a block (or panel pane).

Set up a parent node content type and add an entity reference field to the products content type.
When you create products, reference the parent node.
Create a block view and add a contextual filter for content: referenced (or maybe referencing). your entity reference field. ?
In that contextual filter's settings, click provide default: content id from url ?
Add fields for the products content type and maybe additional filters as needed.

When you place the block in a region, the products will show up if they reference that node.


Views 2 Conditional Filter How can I apply a conditional fitler to a view (using views 2)?

For example:
I have a view which displays the teasers for several different node types using a filter on Node:Type in [Blog entry, Forum topic, User profile]

This works well for showing all nodes of those types, but suppose I only want to show a user's profile if it has a picture as well (and all of the other types).

clone a display for the "filtered (must have picture)" view.
Add a relationship on the picture field and make it required. This will limit the display of content to that which has a picture field populated.

Now you can use a link in the headers to jump back and forth or provide another means.


Admin Landing Page - How to create? Ok, I know there is a tutorial out there somewhere for this, I used it once before. Now, no matter how I search, I can't find it. Basically, I want to create this:

In other words, an admin landing page with sub menu items.

I have Panels and Page Manager installed and can create the admin page to the point where it shows on the path, but the sub-menu items don't appear. Instead I get this:

I've cleared the caches, made sure that sub-menu item is under this page, made sure that all the proper permissions are set . . . You know all the stuff that good Drupal developers are supposed to do.

So my two questions are this:

What am I doing wrong?
Can any one give me the step by step for creating what's on the first image with my own custom menu items? Or at least point me in the direction of some tutorials?

Thank you in advance for any help you can provide.

The reliable way to add and see menu options on admin pages is through [PHP] code, using hook_menu(). Be sure each URL is prefixed with admin/... (for example, admin/sub-section/page-1, admin/sub-section/page-2).

Here's a quick snippet paraphrased from the hook_menu() Drupal API docs:

  function mymodule_menu() {
    $items['admin/sub-section/page-1'] = array(
      'page callback' => 'mymodule_page1_view',
    );
    return $items;
  }

  function mymodule_page1_view() {
    // ...
  }

I haven't tried tricking the admin screen by adding custom links with "admin/*" at the front, which may or may not work - but the code option will definitely work, I've used that hook more than a thousand times.


How to integrate with the jQuery Mobile framework? I saw that Wordpress integrates a special plugin to transform Wordpress themes in mobile themes with an integration of the jQuery Mobile framework.

Is it possible to make for Drupal 7? Exist a module that can change or integrate with jQuery Mobile?

There are currently people working on an integration of jQuery Mobile and Drupal.

Take a look at the jQuery Mobile module and the jQM Theme.  They are both currently only in dev, but I don't think there is much else out there yet.  If you prefer you could always do the integration yourself and use the basic Mobile theme.

The creators of this module and theme also have a video from Drupalcon Chicago that was very interesting: Drupal on the go with jQuery Mobile


Controlling the display format of a rss feed I am using drupal 6. I have created an RSS feed to display the nodes of a certain type (set in the filter). This type of content has many different fields, but I only want to display some of them. Is this possible? At the moment I am very new to Drupal, and I am only working in the front end view.

To fix this issue, do I need to go deeper and mess with the PHP code somewhere?


Is there a way to get the max size of a varchar textfield? I have an entity with a textfield created using the core Fields feature that looks like this when I inspect the type of the field table in the database varchar(40).

I want to be able to determine max size of the string that can go into this field programmatically.  I.e. I want do know if there is a function I can call with suitable parameters, and it would return 40.

A Drupal API function would be the preferred answer, but a could live with a PHP function if this is not available in the Drupal API.

I was reminded in a comment (now deleted) that I previously had answered a very similar question.

However, that answer relies on the field in question being part of a schema.

This new question is about fields that has been created using the core Fields feature.  (I.e. using drupal_get_schema() will not fly.

There's no single function that will extract the value for you, but field_info_field() will get you an array that contains the data:

$info = field_info_field('field_foo');
if (isset($info['columns']['value']['length'])) {
  // Do something with $info['columns']['value']['length']
}

It it's a core text field, value will always be the name of the column you need to check. For other field types it may differ.


Import legacy site URLs via url_alias table I have a long table of legacy site URLs (Drupal 6 site) and the new URLs they should redirect to on the new site (Drupal 8). The list is too long to make this an .htaccess fix, and too irregular for an easy rule.

I tried simply inserting the rows into the url_alias table and have found that they don't work unless I find them in the URL Aliases admin page, edit them and save them. I guess this means that the redirects are stored somewhere else as well as that table. Clearing the cache manually didn't seem to help.

I can't think of a way to do what I need with the various path / redirect modules I've found so far (though I'm really open to trying) and most of the code samples out there are D6 or D7. Is there a way (as a one-off) that I can get Drupal to re-read the entire url_alias table and make them proper redirects? Or is there another way to get all the redirects in place? Any help much appreciated!

For storing aliases use Drupal\Core\Path\AliasStorage:

\Drupal::service('path.alias_storage')->save($source, $alias, $langcode);

But it should be no problem, if you inserted the rows by hand. Check, if all source paths and aliases have a leading '/'. And that langcode is set to a language like 'en' or 'und' for undefined.

Then clear the cache. It is enough to invalidate the cache tag 'route_match':

drush ev '\Drupal\Core\Cache\Cache::invalidateTags(['route_match'])'


How do I manipulate a variable's property in Twig? I want to add classes to a link render element that's a property of the {{content}} variable in my template.

I can do this:

{% set link = content.my_link %}
{% set link = link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}

But I don't seem to be able to manipulate content.my_link directly. Why can't I do this:

{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ content.my_link }}

{% doesn't render, and merge doesn't operate by reference. With those two things in mind, this:

{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}

does nothing, except to waste CPU cycles; you're not rendering, nor saving, the result of the merge.

There are various ways to solve, this is probably the simplest:

{% set link = content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}


Unchecking a boolean field on form render I have a content type that has a boolean field (checkbox) that editors need to always re-check on saving a new revision, if they want the value to still be true. Otherwise, it would be saved as false.

I'm using a hook_form_node_form_alter to modify the $form before the page is shown to the Editor.

public function my_module_form_node_form_alter(&$form, &$form_state, &$form_id)
{
   $form['field_my_boolean_field']['#value'] = 0;
}

I've tried something similar to the above and have also tried #checked and #default_value in place of #value but nothing seems to work. The checkbox always renders checked (as it is saved in the database). How can I uncheck this boolean field when the form is rendered? Note that I do not want to change the actual value of the field for this node, just make it unchecked in the UI when the form for this content is shown.

You can use hook_ENTITY_TYPE_prepare_form() to change entity values before the entity form is built:

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for Nodes.
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() != 'my_content_type') {
    return;
  }
  if ($operation == 'edit') {
    $node->field_my_boolean_field->value = 0;
  }
}

This changes the value of the field for this node, but only temporary as long as the user doesn't submit the form.


Adding 'lang' attribute to language links in template.php I am not a Drupal developer, but still I would like to know how to make the links in a language switcher HTML5 valid. It seems these links lack an attribute 'lang' (with as value the abbrevation of the language). How would I do that in template.php?

I found the solution:

function MYTHEME_links__locale_block(&$vars) {

  foreach($vars['links'] as $language => $langInfo) {
    $name = $langInfo['language']->native;
    $lang = $langInfo['language']->language;
    $vars['links'][$language]['title'] = $name;
    $vars['links'][$language]['attributes']['xml:lang'] = $lang;
    $vars['links'][$language]['attributes']['lang'] = $lang;
    $vars['links'][$language]['html'] = TRUE;
  }
  $content = theme_links($vars);
 return $content;
}


What happens after module upgrade if you modify the default views I want to modify a view supplied by a module. What happens to the view when I upgrade the module? Does it overwrite my changes? If it doesn't and the views in the upgraded version of the module has changed, how do I get the new version?

It should not necessarily change your view, views shipped with modules are usually kept in code, if you change that view, you override it and have it in the database, as long as this overridden view is in your database and a module update does not drop these changes on purpose you should be good to go.

But, always do a backup and test on a local/ different environment than live.

If it does indeed change stuff, you will have to clone the current view and maybe even mimic custom views hooks that are added by that module for that view.

btw. it's worth reading the commit messages since the latest release and or changelogs, if you can read code it's worth looking into the module.install file, and looking at the module_update_n hooks, there you can see if anything major might get dropped as well.


Using custom test helpers in your test cases I'm trying to write test cases for my custom module and in order to speed things along for current and future testing I defined a garbage class that can spit out random data. However the testing module cannot seem to locate my Garbage class. After some debugging I realize that Drupal looks in the registry table to find the class and while my class is defined in the default registry table, simpletest creates it's own custom registry table to run tests which doesn't contain my class or it's location. Is there any way around this or some way to force simpletest to make an exact duplicate of the registry table?

Notes:

The garbage class is located in a separate file (Garbage.php)
Yes I do have 'files[] = Garbage.php' in my .info file.
While I could just move the garbage functions into test case itself, I may need to reuse it for other tests later on so having it in a separate class is ideal.

Garbage class

    class Garbage {
        public static function getGarbageString(int $i = 1) {
            $return = array();
            for ($j = 0; $j < $i; $j++) {
                $return[$j] = self::_getRandomString();
            }

            return $i == 1 ? $return[0] : $return;
        }

        private static function _getRandomChar() {
            return chr(mt_rand(33,126));
        }

        private static function _getRandomString() {
            $length = mt_rand(1, 255);
            $return = '';
            for ($i = 0; $i < $length; $i++) {
                $return .= self::_getRandomChar();
            }

            return $return;
        }
    }

Located in .module file

    function getRecord($recordName) {
        return $records[$recordName];
    }

Located in RecordTestCases which extends DrupalWebTestCase

    public function testGetRecord() {
        $badData = Garbage::getGarbageString();
        $this->assertNull(getRecord($badData), 'Testing get record with bad data');
    }

If getRecord() and testGetRecord() are methods of the Garbage class, then you have a misplaced } bracket.

Alternately, testGetRecord() will have no idea what to do with $this, since it's not part of a class definition. It would need to be a method of a subclass of DrupalUnitTest, or DrupalWebTest. As-is, PHP will choke on it.


How to publish content based on a Date field in custom content type in Drupal 7? I have a Date field in a custom content type in Drupal 7. I would want to control the publishing of the content instance based on that particular Date. I want the job of the Scheduler module but have it as a field in my content type and access it accordingly. Is there a way to do it using triggers or Rules? Any thoughts on this would be really useful.

There is a patch to make the Scheduler "Publish On" date render itself as a field: http://drupal.org/node/1203958

This presents a new Checkbox called "Show Scheduling options in vertical tabs", which you can uncheck to display as a field.  Then you give it some weight so it shows up where you want it to.

It's been working for me in production for a month or so.

EDIT: Here's a better way to make this happen with both Scheduler and Rules.

Create a Rule, "After saving new content"
Add a condition of "Content is of type"
Add an "Execute PHP" action with this:

$node->publish_on = strtotime("[node:field-datefield-here]");
scheduler_node_insert($node)
Create a Rule, "After updating existing content"
Add a condition of "Content is of type"
Add an "Execute PHP" action with this:

$node->publish_on = strtotime("[node:field-datefield-here]");
scheduler_node_update($node);


EntityFieldQuery vs Db_select() Why should I use EntityFieldQuery when I can do the same work with Db_select() to fetch the value.

It would be better if someone can provide an example, not only a link.

I think that the main reason prefering EntityFieldQuery over db_select is that you don't have to know about the lower-level structure, in other words: how stuff is stored in the database. This improves loose coupling.


Problem with mobile redirection login I've implemented this mobile redirection logic but for the past 10 days I've been getting weird behavior(with www version, mobile data is shown sometimes).

Here is Mobile Theme return logic

Also I find different behavior if I uncomment "return 'bartik' in the last line below.

  function mobile_detect_custom_theme() {

        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0)
        {
            return 'mobile_theme';
        }

//return 'bartik'; //IF I uncomment it I find different behavior
    }

In Hook_book I've setup this redirection logic:

//wantdesktop is set if user has specifically selected Desktop version
if (@$_COOKIE['wantdesktop'] == 'true') {
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0) {

            $url = "http://www.example.com/" . $_SERVER['REQUEST_URI'];

            header('Location: ' . $url, TRUE, 302);
            exit(0);
        }

        return;
    }

//wantmobile is set if user has specifically selected mobile version
      if (@$_COOKIE['wantmobile'] == 'true') {
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") != 0) {

            $url = "http://m.example.com/" . $_SERVER['REQUEST_URI'];

            header('Location: ' . $url, TRUE, 302);

            exit(0);
        }

        return;
    }

//BROWSER DETECTION LOGIC HERE which fills $browser['ismobiledevice'] with true/false

    if ( $browser['ismobiledevice'] == 'true') {
        //check the current domain
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") != 0) { //not a mobile url
            $url = "http://m.example.com/" . $_SERVER['REQUEST_URI'];
            header('Location: ' . $url, TRUE, 302);
            exit(0);

        }
    } else { //desktop
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0) { //is a mobile url

            $url = "http://www.example.com/" . $_SERVER['REQUEST_URI'];
            header('Location: ' . $url, TRUE, 302);
            exit(0);

        }
    }

What is wrong with this logic?

May I suggest an alternative approach of using the Themekey module. It was built to solve the exact issue you are facing:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

  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

The important thing to note about Themekey, is that the module works well with the external caching as well. Do check out its documentation for more.


Migrating into Double field I am migrating a CSV into D8 node type which has a double field. The CSV has the following structure:

I am trying to migrate the year, from the header, into the first double-field subfield (as a label) and the population data for each country (Afganistan, in the example above) into the second double-field subfield.

The double-field has the following interface (the data in this example was entered manually):

And, this is how the data is represented in the node as seen via Devel:

I have tried a variety of things in my migration yaml code but I have not been able to migrate either the year nor population data. My code is below:

.
.
.
process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count_first:
    0:
      plugin: get
      source:
        - 1960
.
.
.
------- also - tried -----------
.
.
.
process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count:
    first:
      0:
        plugin: get
        source:
          - 1960
.
.
.

I would appreciate some help.

Ran into exactly the same issue, here is my solution. In my case for field 'first' I have a select list of contact types in field 'second' it is a plain text field. For one of the source fields I am converting a taxonomy term to a plain text so there is a service injected to do a lookup up from the source database. The migration config looks like this for the fields I want to convert:

  field_phoned:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_office
      source: field_phoned
  field_mobile_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_mobile
      source: field_mobile_number
  field_skype_contact:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: skype
      source: field_skype_contact
  field_whatsapp_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: whatsapp
      source: field_whatsapp_number
  field_location_taxonomy:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: location
      source: field_location_taxonomy

The process plugin 'add_contact_info_field':

<?php

namespace Drupal\custom_migrate_tools\Plugin\migrate\process;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\custom_migrate_tools\TermLookupInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'AddParagraphBody' migrate process plugin.
 *
 * @MigrateProcessPlugin(
 *  id = "add_contact_info_field"
 * )
 */
class AddContactInfoField extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Lookup source term service.
   *
   * @var \Drupal\custom_migrate_tools\TermLookupInterface
   */
  protected $termLookup;

  /**
   * The migration.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * TaxonomyLookup constructor.
   *
   * @param array $configuration
   * @param $pluginId
   * @param $pluginDefinition
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   * @param \Drupal\custom_migrate_tools\TermLookupInterface $termLookup
   */
  public function __construct(array $configuration,
                              $pluginId, $pluginDefinition,
                              MigrationInterface $migration,
                              TermLookupInterface $termLookup) {
    parent::__construct($configuration, $pluginId, $pluginDefinition);
    $this->migration = $migration;
    $this->termLookup = $termLookup;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $pluginId,
      $pluginDefinition,
      $migration,
      $container->get('custom_migrate_tools.term_lookup')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $contact_info = [];
    if ($label = $this->configuration['target_label']) {
      $contact_info[0]['first'] = $label;
    }
    else {
      $contact_info[0]['first'] = $label;
    }

    if ($destination_property == 'field_location_taxonomy') {
      $contact_info[0]['second'] = $this->termLookup->getTermName($value['target_id'])->name;
    }
    else {
      $contact_info[0]['second'] = $value['value'];
    }

    if ($targetField = $this->configuration['target_field']) {
      if ($field_contact_info = $row->getDestinationProperty($targetField)) {
        array_push($field_contact_info, reset($contact_info));
      }
      else {
        $field_contact_info = $contact_info;
      }
      $row->setDestinationProperty($targetField, $field_contact_info);
    }
    return $value;
  }

}


Calendar & subscriptions modules Is it possible for anonymos users to subscribe to calendar events created using the Calendar module? If so, how would I go about achieving this?

Yes its possible for anonymos users to subscribe to calendar events created using the Calendar module.


What would be the alternative to fix "Access forbidden 404" on my test site while using basic_authentication module for rest resource? Background:
I had http authentication enabled by htaccess on my test site. I had created REST resource using Drupal 8 core REST web services modules and views. When i used authentication as basic_auth than on Test site  got access forbidden 404 for each page request. Uninstall basic_authentication make it work but i want basic_authentication should work for my test site. What would be the better alternative for this?

Thanks

You can send in the user and password parameters with your API call.

user:password@http://site-url.tld

this way you can still communicate with the app whilst keeping it behind basic auth


When a module has a composer dependency, should it be automatically installed when the module is installed? Trying to resolve a debate - if a drupal site that is configured correctly installs a module with a composer dependency, should I expect the composer dependency to be installed automatically during the install?

The other person thinks that modules with composer dependencies have to be installed through command line to work, I think that if things were configured correctly it should happen on its own.

Does someone know how it should work?

If you install the module with composer, yes, dependencies will be fetched. If you download the tar and put it in the site, it will not.


How do I add a link to a menu from a module in Drupal 6? I'm creating a drop down menu with nice menus, but I'm having a problem programatically adding a link to the menu from modules. I have defined the menu in the Administration section under Site Building > Menus and can get it to work fine if I add a link manually, but I can't get any links from modules to show up. Here is my code from module_menu():

  $items['node/%node/jobs'] = array(
    'title' => 'Jobs',
    'page callback' => 'job_applications_form',
    'page arguments' => array(1, 'node'),
    'access callback' => 'job_applications_user_access',
    'access arguments' => array('site_owner', 1),
    'menu_name' => 'menu-dealer-menu',
    'type' => MENU_NORMAL_ITEM,
  );

The menu's name is menu-dealer-menu. I am using Drupal 6, and upgrading to 7 is not an option right now, and won't be for the next couple of months.

You are using a wildcard in the path node/%node/jobs. If you want Drupal to show a menu link, you have to tell it how to figure out the %node argument. You can do it with a function named node_to_arg.

The function name, actually, is [wildcard]_to_arg. I suggest you change the wildcard to something different, since there are several menu paths with %node in it. If you relied on node_load to return you a node object, you can just call it from [wildcard]_load.

There is documentation on [wildcard]_to_arg and you can see how user_uid_optional_to_arg implements it for the user/%user_uid_optional path.


How to import git commit from development to testing in Aegir So, I have established Aegir to take care of my sites workflow.

Now I made changes to my development site, used git to load the commit to development site. How do I import the latest commits to Staging or Production ?

With the Hosting site Git module you can create a git pull task from the hostmaster frontend.

  This module extends Aegir with the option to do a 'git pull' in a site directory.


Dependency injection on module.install How do I leverage dependency injection for drupal 8 when invoking my module.install->hook_install() mehtod?

Or do I have to use \Drupal:: method at this point?

Yes, for procedural code in hooks you have to use the static service container wrapper \Drupal. Either to get a service or to use one of the predefined static functions. See for example:

shortcut.install

/**
 * Implements hook_install().
 */
function shortcut_install() {
  // Theme settings are not configuration entities and cannot depend on modules
  // so to set a module-specific setting, we need to set it with logic.
  if (\Drupal::service('theme_handler')->themeExists('seven')) {
    \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
  }
}


Migrate users and retain passwords I'm transferring 10K users from Drupal 7 to Drupal 8. I want to retain passwords. What I'm trying is

Dump user records from Drupal 7 as a CSV file
Dump hashed passwords from MySQL as a CSV file
Load user records and hashed passwords into a custom program
In the program, add hashed passwords to the correct user records (match by UID)
Manipulate user records (consolidate duplicates, combine fields, and more)
output fixed-up user records (including password hash) to a CSV file
use this CSV file as input to a custom Drupal 8 module to create users

All of this is easy except creating users in Drupal 8 with their Drupal 7 passwords.

I have tried simply

$values = array
[
  'name' => 'test',
  'mail' => 'test@test.com',
  'roles' => [],
  'pass' => $hashed_drupal_7_password,
  'status' => 1,
];
$account = entity_create('user', $values);
$account->save();

but of course Drupal 8 assumes the pass value is the textual password and rehashes it.

Is there a way to get the already-hashed password into the user account, either during creation or after it is created? If I get them in, will they still work? As you can tell by reading, I'm a neophyte when it comes to passwords, encryption, etc. I've read many posts and articles, but don't recognize an answer to this question.

As @No Sssweat recommend, the D8 Migrate Modules is good way. With your way, you have to add property pre_hashed for field pass.

$values = [
  'name' => 'test',
  'mail' => 'test@test.com',
  'roles' => [],
  'pass' => [
    'value' => $hashed_drupal_7_password,
    'pre_hashed' => TRUE,
  ],
  'status' => 1,
];
$account = entity_create('user', $values);
$account->save();

You can find this property in FieldType Password


Change the actual file for Logins I have a site and I'd like to customize the login page. I'm using a customized version of the Stark Theme and I'd like to know if there is any way to change the actual file behind the login form so it looks a bit more uniform with the rest of the site. So without creating a new file and redirecting.

Any help?

You can try iTweak Login module to customize the login page. This module have so many settings to customize login form page as well as login block.

You can also try FreshLogin module. It will provide a complete different template.It  can customize as you want.


How to resolve Integrity constraint violation: 1062 Duplicate entry on node_access? So I am looking all over and have yet to find out how to remedy this table issue.

Rules is the likely culprit because the violation occurs when creating a new node (with Workflow) and trying to have it move forward to a state called publish. It fails with PDO Integrity Constraint Violation 1062.

Now the problem is that NO new nodes can be created without error, by any user. How can I fix this? The error message references a node ID that doesn't exist in any table rows, I guess because the node was never actually saved.

I have adjusted Rules so this doesn't happen again on new nodes, but I need to get that error off without losing data.

The error message is the following one:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry "694-7-workflow_access" for key "PRIMARY": INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES ....

This is weird because I have completely truncated the table, deleted and added it back, and tried to build a new copy of the DB all without success. I can't for the life of me find the primary key duplicate in ANY table. These nodes, node revisions, or node access records simply don't exist for nid 694 (or anything above 660 really).

So far I have traced it to Workflow's use of hook_node_access_records(). If I comment out module_invoke('node_' . $op, $node) the nodes will submit, so it is definitely the access table/process causing the problem. Workflow returns a $grants array just fine.

For posterity, I did not figure out the line of code that were  causing this but the issue is that node_save was being called twice on a new node, which DID create a legitimate duplicate key, but then it would also delete the offending row. This drives the developer bonkers.

It has something to do with Workflow (probably), and I am not particularly proud of this but you can remedy by making one small change to node.module:

/* ADDED SPR */
$delete = true; //$op == 'update';
/* END ADDED SPR */

Top and bottom lines are for easy searching of code tweaks for upgrades.


how to delete a context I have created a sample context just for testing its work, and now it appears on every page because I have used a block in my context. I want to remove the sample context. I have searched in Drupal docs but nothing useful there. Any ideas how to solve it.

You do it the same place where you add and edit contexts, the contexts admin page located at admin/structure/context. Context defined in code can't be deleted, but can instead be disabled.


User preprocess not working I'm trying to pass a variable to an user template, here is my code:

function template-name_preprocess_user(&$variables) {
  $variables['foo'] = 'foo';
}

It doesn't work. I tried adding these line in the core User module preprocess and it works!

Template hooks like template_preprocess_user() are implemented by custom module/theme by replacing template with [MODULE_NAME/THEME_NAME]. So, for example, if your theme short name is bartik, then the function name will be bartik_preprocess_user() which will be implemented in the bartik.theme file.

function [MODULE/THEME_NAME]_preprocess_user(&$variables) {
  $variables['foo'] = 'foo';
}


Taxonomy Term showing strange text Having taxonamy term issues - as glossary terms showing with text below the text  saying "There is currently no content classified with this term."

does anyone know how to remove or hide the statement mentioned?

Drupal 7

override default with the "taxonomy/term/%" views

or

function THEME_preprocess_page(&$vars) {
  if(isset($vars['page']['content']['system_main']['no_content'])) {
    unset($vars['page']['content']['system_main']['no_content']);
  }
}


Show default image when no uploaded image I have a view with a thumbnail of the image uploaded by user. I would like to setup a default image which appears in place of thumbnail in case the user did not upload any image. Is that possible? Any advice appreciated.

This can be done when you edit the content type > your image field > fieldsettings. There you can upload a default image. This image should show up in views.


Creating a view with a dynamic link from taxonomy term Trying to create a view block with a list of five links

Event Details (dynamic)
Cause (dyanmic)
Sponsors (statis)
Volunteer (static)
Register (static)

Dynamic url will look like this:

/events/golf-tournament/[year]/[taxonomy-term]/event-details

/events/golf-tournament/[year]/[taxonomy-term]/cause

I am not able to format the taxonomy term to use it in the url

Taxonomy term prints as: The William Dennis Memorial Golf Tournament (with capitals and spaces)

View looks like this:

** Solution **
*  Not sure if this is the 'right' way *

Added contextual filter for: Content: has taxonomy term ID

But it doesn't appear to use the taxonomy term....so really I providing a value from the url

Then I messed around with tokens, first trying [token_taxonomy_term] <--- not actual token; %1 and !1 <---- all of these exist in the available Replacement Patterns

Here is the rewrite I used to rewrite the url for 'cause'

Cause

In the contextual filters you may have to add the Context: Has taxonomy term ID filter.  You can set the Specify validation criteria settings.  The validator option is usually Taxonomy Term, but other validator options are available. Make sure to choose Term Name converted to Term ID, as this is what is needed to be passed for to the url.  Also check the Transform dashes in URL to spaces in term name filter values checkbox underneath.
Choose your action to take if the filter value does not validate dropdown.


Rendering a field in a custom print template I'm using the Printer, email and PDF versions module to render a custom print page in Drupal 7. I'd like to theme the fields individually and have worked that out to the point of using nasty php in my custom template itself.

So, I have a content type called ecard and following the module's documentation, I'm using print--node--ecard.tpl.php (based on the modules's core print.tpl.php file) for my custom print template. That works fine but the usual ways of rendering individual fields like in a node template don't.

I can do this within print--node--ecard.tpl.php to render an indivdual field called field_ecard_logo:

<?php
$ecard_logo = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
print render($ecard_logo);
?>

... works but kind of nasty. I'd rather put all the logic in my theme's template.php and simply print a variable I've created. Looking at what preprocess functions the Print module uses, I see preprocess_print and preprocess_node. So I tried this in template.php:

  function MYTHEME_preprocess_print($vars) {
      $node = $vars['node'];
      $vars['ecard_logo'] = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
    }

and then in print--node--ecard.tpl.php, I simply do:

<?php print $ecard_logo; ?>

but that does not work. I tried different incarnations of all this but no joy so at this point I'm stumped.

After a few days of working on this, it ended up being pretty trivial to accomplish this so I'll answer my own question for those who need help in the future. I had most of the solution working but in my custom print template, the key was to have:

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

NOT:

<?php print $ecard_logo; ?>

So the full function in template.php is:

/**
  * Renders the content of the print page using the theme api.
  */
function usfig_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];
// Compartmentalize only for ecard content type.
if($vars['node']->type == 'ecard') {

// Create a var and render using field_view_value, we don't need anything special for this, otherwise use field_get_items for data parts.
$vars['ecard_logo'] = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
}

}

... and then in my custom print template I do:

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

and it works!

Extra credit:

You can create and render an image style with field_view_value as well like so in your theme's template.php file:

 $vars['ecard_image'] = field_view_value('node', $node, 'field_my_image', $node->field_my_image[$node->language][0], array(
      'type' => 'image',
      'settings' => array(
      'image_style' => 'my_custom_image_style',
      'image_link' => 'none',
      ),
      ));

Then just render the variable in your custom template file!  What's the advantage to all this? It allows for ultra minimalist markup and precise themeing where layout and exactness are crucial. It cuts way down on the "divitis" that drupal tends to have.


how to exclude PHPUnit based functional tests from runnning? I am trying to run only unit test for my custom module.

./vendor/bin/phpunit -c ./web/core ./web/modules/custom/testing_example --testsuite=unit .
But I keep getting the following error:

There were 2 errors:

1) Drupal\Tests\testing_example\Kernel\ExampleFixtureManagementTest::testNodeCreation
Exception: There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh. See https://www.drupal.org/node/2116263#skipped-tests for more information.

I only want to run PhpUnit tests and not functional/browser tests.

Since those tests are grouped by namespace/directory, you can just pass the respective path to phpunit, simply add tests/src/Unit to your existing path.


Add a "class selection" field to content item via CCK? I have a single content type (webform) that I want to display in two or three different styles on my site. For instance, I may want to have some of the webform's CCK fields floated to the right on one webform page, and have them floated to the left on another. There will be many unique webform content items on the site, so individual CSS per-page styling would not work well, and I am looking for a point-and-click solution.

I was hoping that there would be a way for me to add a CCK field (or something similar) to the Webform content item that would allow me (or another admin user) to simply choose "style 1", "style 2", or "style 3" from a drop-down menu, and that style would be added to that Webform's page  or div classes, allowing that form to be stylized according to one of three pre-created style sets.

Is this possible with an existing module? Any other ways in which I can go about accomplishing this?

Thanks!

// This code will add a class to the node based on a field in that node
function THEME_preprocess_node(&$vars) {
$node = $vars['node'];
$output = '';

switch($node->type) {
  case 'advertisement':

  // Set class based on editor color selection; code duplicated for clarity.
  $field = field_get_items('node', $node, 'field_background_color');
  if($field) {
    $theme = field_view_value('node', $node, 'field_background_color', $field[0]);
    $term_name = $theme['#title'];
    $term_name = str_replace(' ', '-', $term_name);
    $css_name = strtolower($term_name);
    $vars['classes_array'][] = $css_name;
  }
  break;
  }
}


How to provide email notifications to admins for *all* comments? My site admins are asking to receive email notifications automatically whenever a comment is posted on any content on the entire site. I already have comment_notify enabled, but that only allows them to get emails for comments posted on their content, or on posts they have subscribed to. They want to get those emails for all content by default.

I have also seen the "Notifications via e-mail comparison" page, but none of the module descriptions say they have this feature.

Am I stuck with having to implement a Rules based solution? Or am I missing something?

I see that you've already found the Comment Notifications comparison page over at Drupal.org - but also that you say you have not found the module you're looking for there.

However, from the description of your requirements, it sounds like the Notify module is pretty close.

Since it uses a digest format and depends on cron, it will not give your site admins instant notifications of new content, but otherwise, it matches your description.  Most important, It will send out notifications about all new comments, all new nodes, or both.

Disclosure: I am a co-maintainer.


How to import content to Drupal 8 site by inserting it directly in the database? As I was not able to find any working way of importing content from csv, I decided to export it to .csv from the old site (database) and import it then into the Drupal 8 database. However, after I updated tables node, node__body and node_field_data I was not able to access the content overview page anymore.

Turned out that I also had to update node_revision table, so all I have done was:

node (D7) -> node (D8)

select nid,vid, 'article', UUID(), language
from node
where type = 'story'

field_data_body (D7) -> node_body (D8)

select 'article', null, entity_id, revision_id, language, 0, body_value, body_summary, 'basic_html'
from field_data_body
where bundle = 'story'

node (D7) -> node_field_data (D8)

select nid, vid, 'article', language, status, title, uid, created, changed, promote, sticky, 1, 1
from node
where type='story'

node (D7) -> node_revision (D8)

select nid, vid, language, created, uid, null, 1
from node
where type='story'

node (D7) -> node_field_revision (D8)

select nid, vid, language, status, title, uid, created, changed, promote, sticky, null, language
from node
where type='story'

Of course, these are just simple queries for just one particular article type without any additional fields, but the point was to show which tables need to be updated to at least get the content in the Drupal 8. Other (field) tables will require more sophisticated SQL exports.


Passing a custom variable from preprocess view to a template file I am preprocessing a view in order to create a custom variable and then pass it to a view template file.

I have added the following code to the template.php file:

function mycustomtheme_preprocess_views_view(&$vars) {
    $view = $vars['view'];

    $currentpath = current_path();
    $path_alias = drupal_lookup_path('alias',$currentpath);

    // define the custom variable
    $vars['mycustomvariable'] = '';

    if ($view->name == 'mycustomviewname') {

        foreach($view->result as $key => $result) {
            $tid = $result->tid; // get the taxonomy term's ID
            $termpath = drupal_get_path_alias('taxonomy/term/' . $tid); // term's path
            // if the current path is same to the one of the term
            if ($termpath == $path_alias) {
                // give a value to the custom variable
                $vars['mycustomvariable'] = 'blablabla';
            }
        }
    }
}

Then in the views-view-list--mycustomviewname--block_1.tpl.php file, I try to print the variable like this:

<?php print $mycustomvariable; ?>

But I am getting the error:

  Notice: Undefined variable: mycustomvariable in include() (line 18 of
  views-view-list--mycustomviewname--block_1.tpl.php)

I have spent a considerable amount of time on this issue and used dpm and print_r to print out variables, arrays and objects but I cannot seem to find solution to this issue.

Any help would be appreciated. Thank you in advance.

I'm not fully sure what I'm going to tell you is completely true, it is just my experience of how Views works.

From what I know, Every preprocess function has access to a specific output template file. As an example variables of template_preprocess_views_view_fields are available in views-view-fields--AnyThingElse.tpl.php template file, so the domain access of variables of template_preprocess_views_view_fields is views-view-fields--AnyThingElse.tpl.php.

In Theme Information there are three levels of output styles:

Display output
Style output
Row style output

The views-view-list--mycustomviewname--block_1.tpl.php is a TPL file in the second level (Style output) but I guess the mycustomtheme_preprocess_views_view domain of access of its variables is in the first level (Display output) TPL files.

To make sure, select one of the TPL files from Display output and check if the variable is set in there.


Configuration management sync vs active vs staging The documentation on config management talks about a CONFIG_SYNC_DIRECTORY setting, but then there is also mention of CONFIG_ACTIVE_DIRECTORY and CONFIG_STAGING_DIRECTORY setting throughout comments both on d.o and in stack overflow.

What are these two different setups about?

This has changed, before Drupal beta 14 it was active/staging now it is sync. These are the settings in settings.php:

Drupal 8 beta 14:
$config_directories['active'] = 'sites/default/files/config_HASH/active';
$config_directories['staging'] = 'sites/default/files/config_HASH/staging';

Drupal 8 rc1:
$config_directories['sync'] = 'sites/default/files/config_HASH/sync';


when a button_field is presses, how do I access the node that owns the button? I have a button (button_field) on a content type which is rendered by a view.  The view will display a list of items and each will have a clickable button.  When the user clicks a button, I need write a rule that will set a node reference (attached to the use) to the node that was clicked.  the button_field provides several rules for detecting button clicks, but I have yet to find a rule action or rule token that gives me access to the fields on the 'node that was clicked'  How do I gain access to that node?

Edit =============

Link added.  I am using the actions that came with the module (no additional code added.) I was hoping when I used the 'button pressed' action, rules would give me accesses to entity:... so that I could use the fields on the entity (the one with the button that was pressed.)  However, this data option is not available.  Honestly, I could use flags to do this, but I thought that a flag was a bit more functionality than I needed.

I was trying to do something similar. It looks like as you can have button_field on any entity, you need to DEFINE what entity has button_field in your rules. It worked for me thinking like that.

What I mean is in your rules’ conditions section after checking ‘Clicked button comparison’ with your_button_field_name if you check ‘Entity is of type’ Node and ‘Content is of type’ Your_content_type, then all of the fields of your content type including nid will be available in Actions section under entity. Check out Using Button Field


How to combine taxonomy terms? I use Taxonomy with Contextual Filter, so I can categorize content (nodes), associating taxonomy terms to each content, and filter them in a View.

I can have a node and 2 different vocabularies, lets say A = {1,2,3} and B={a,b,c}. I can, by default in Drupal usual behaviour, associate a node with multiple values of A and B, lets say that node Nid has associated 1,2 and a,b.

What I need, if it is at all possible, is to have paired associations, i.e., not only 1,2 and a,b separatedly, but in combination. Let's say
{1,a} and {2,b} and the contextual filter or equivalent, if looking for {1,a} will return the node, but if looking for {1,b} it will return nothing. Of course, {1,all} would have to return the node.

Is there such a module or behaviour in Drupal 7 ?

Note: the problem does not lie with the search or filter part. The very basic problem is how to assign a combined value to the node, in the very first place. Later I will face the problem of looking for or filtering for that data. But I don't know how to merge both taxonomy fields into one, so the node is assigned to {1,a} and not to "1" and "a" separatedly.

Do you always need to search on multiple terms at the same time? And how do you want to search, via an exposed filter or with query parameters?

In both cases you need to add references to the vocabularies A and B.

If you want to search through an exposed filter, you can add the term name fields (with relation to the references) to the normal filter and just expose them. I'm not sure, but I think there is a way to combine this with global text search.

If you want to work with query parameters you need contextual filters. Just add a term name for both vocabularies and let them match the value of the query parameters. You can specify what results must be shown if the parameter value is 'all' for example.

I don't think you need the or operator because you mentioned you want to match on both terms at the same time. However, if you want to match on multiple combinations you might want to check this module. I haven't tested it myself, but it really saves you some time if it works. The or operator is not native in contextual filters.

Good luck! Contextual filters and references can be a real pain in the ...


How to display a page of a taxonomy term differently from the default view? I activated the "Taxonomy term" view to customize the time display. I want to display some terms from another differently. How to do this ?

I have cloned my view "Taxonomy term" and applied to it a criterion of filtering by type of content displaying only my "sujet". Then I customized its display.

The problem, when the cloned view is enabled, all terms show a blank page.

Maybe you should check Taxonomy Views Integrator

  The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice


How to set validation error for specific subfield of the paragraph type? I've got paragraphs type with two fields which I've added as a field into my vocabulary.

I've added validation function (#validate) into $form using hook_form_FORM_ID_alter where I'm validating values of these fields, however when I'm using the machine name of the paragraph field, all widgets are highlighted. My aim is to highlight only the one which fails.

The structure of that paragraph field (field_sor_rule) is like:

// var_dump($form_state->getValue('field_sor_rule'));
array (size=3)
  0 =>
    array (size=3)
      'subform' =>
        array (size=2)
          'field_sor_rule' =>
            array (size=5)
              0 =>
                array (size=2)
                  'value' => string '1' (length=1)
                  '_weight' => string '0' (length=1)

I've tried already referencing it as:

$form_state->setErrorByName("field_sor_rule[0][subform][field_sor_rule][0]",
  t('Please enter a valid value!'));

and:

$form_state->setErrorByName("field_sor_rule_0_subform_field_sor_rule_0]",
  t('Please enter a valid value!'));

but without success.

What would be a valid syntax?

In the docs page for setErrorByName() we can read:

  string $name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on foo or foo][bar][baz. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

We should also note the following code how it's parsed:

public function setErrorByName($name, $message = '') {
  // ...
      foreach ($limit_validation_errors as $section) {
        // Exploding by '][' reconstructs the element's #parents. If the
        // reconstructed #parents begin with the same keys as the specified
        // section, then the element's values are within the part of
        // $form_state->getValues() that the clicked button requires to be
        // valid, so errors for this element must be recorded. As the exploded
        // array will all be strings, we need to cast every value of the
        // section array to string.
        if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {

So the mentioned element should have the following syntax:

$form_state->setErrorByName("field_sor_rule][0][subform][field_sor_rule][0",
  t('Please enter a valid value!'));


Taxonomy fields in node default display using display suite I have a content type called "product" and a taxonomy called "producer".
On each product, I can select a producer.
The producer has some fields I need: "country", "area", "district".

I need to display those 3 fields from the producer on the product default display.
How can I do that?

Some things I tried that don't work:

Created a view pane with a contextual filter for term id, then selected the argument input to be "From context" and selected the producer field from the product.
Created a dynamic field in ds and selected the view pane and selected "No being viewd" as the argument.

In Manage display of Product content type, select Rendered taxonomy term for term reference producer, then create taxonoy-term--producer.tpl.php to change style of the taxonomy.


best location for features related theming customizations The following is a simplified scenario of an organizational problem I'm facing.

I have a site with a single features module which handles all my content types. My features module is called foo and my zen subtheme is called bar.

One of my content types (e.g event) needs a special class on it so I have 2 options.

Add the class via the foo.module:

function foo_preprocess_node(&$vars) {

  if ('event'==$vars['type']) {
    $vars['classes_array'][] = "extra-class";
  }

}

or add the class via the template.php of bar theme:

function bar_preprocess_node(&$vars) {

  if ('event'==$vars['type']) {
    $vars['classes_array'][] = "extra-class";
  }

}

Which one of the two is the best location for this theme related customization? Without the feature there will be no event content type. So it feels like placing the code in the feature module file together with the content types is the best place.

On the other hand this css class is theme related so it also feels correct to place it in the template.php.

This is just my opinion...

The HTML class itself is not related to the theme, it's related to the module defining the element on which it's placed (if it is a feature specific class name as @barraponto points out in the comments).

The styling for elements with that class is the theme's responsibility.

I would suggest that your code would be more appropriate inside the feature module. If it's not, imagine what will happen if you change themes...you'll lose the class that was on that element, meaning it can no longer be targeted for styling.


Views 3, contextual filter on language - allow for multiple languages So for this site I'm building I need to be able to do the following.

When user views the site in English show all English articles
When the user views the site in Dutch, show all Dutch articles - but also the untranslated English ones
When the user views the site in German, show all German articles - but also the untranslated English ones.

The contextual filter, 'Content translation: Language' only allows to put in one value. That is either a language specified, or all.

But in my case it would be required to be able to set for instance "en+nl" or "en+de". Like one can do with taxonomy 'Has Taxonomy', I would like something like 'Has Language'.

I solved this task like so:

For "When the filter value is not available",  select option "Provide default value".
then use "PHP Code" as the value for "Type"
the actual PHP code I added is as shown in the screenshot below:


Unpublish content problem on update I use the Content Approval module for queue for approval content. If users add article, there's no problem as it is unpublished then . I'm admin i publish this content later. But, then when user update the published content it isn't unpublished again. How can I do this?

If you're using the Rules module, here's a simple rules export for the purpose.

Event: node_presave
Condition: authenticated user
Action: unpublish node

You could change the role condition to suit your site user config.

e.g: Add the role condition "Adminstrator" and click the "Negate" checkbox for "NOT Administrator role" condition.

You could also, for example, add a Rules action to show a message under "System > Show a message on the site" after unpublishing the node.

Exported Rule:

{ "rules_unpublish_updated_content" : {
    "LABEL" : "Unpublish updated content",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } },
          "operation" : "OR"
        }
      }
    ],
    "DO" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

You can import the Rule at:

/admin/config/workflow/rules/reaction/import


500 error: Output filter: Response body too large I recently copied a drupal 7 site from my development server to my production server. Everything on the site seems to be working as expected, except for when I log in as the admin user and try to access admin/modules. When I go there I get a 500 "Internal Server Error" page. In the server's error log, I get: ModSecurity: Output filter: Response body too large (over limit of 6291456, total not specified). [hostname "(my hostname)"] [uri "/drupal/index.php"] [unique_id "T4JOln8AAAEAAFLlyE4AAAAK"]

(unique_id changes every time I get the error, but the other parts don't.)

Any idea what could be causing this?

ModSecurity is an Apache module (a Web Application Firewall) that protects sites from i.e SQL injectiosn, XSS attacks, prevents php shell execution and so on. You must contact your hoster and let them know because they need to change modsec rules maybe.


Can I create two sites with a single user login? I have two sites with loosely related content. I'd like a user to be able to create an account on one site but have that account be valid on the other site. Also have the ability so that if any changes are made on site 1 to the account, they are reflected in site 2's database. Is this possible?

The mechanism which you are talking about called SSO (Single Sign On). There are modules in Drupal to achieve SSO but it would depend upon your site setup like whether 2nd site is sub-domain of the first or both are sub-domain of some other etc..

In case one of them second level domain then you can use Bakery. I have used it successfully.

I have heard so much about CAS module too though never used it. You can go through the documentation of the module and find out whether it fulfil your need or not.

You can have a look here on comparison between all SSO modules available in Drupal.

Regarding auto update, I am not sure it can be done easily with any of them. You will have to write your own code maybe.


How to redirect from URL with trailing slash to one without We are using the Redirect module 8.x-1.2 with Drupal 8.5.6. When generating URLs, we are finding that a trailing slash is added to the end of the URL, and this is creating a 503 error code.

How would I redirect the anonymous users from the URL with the trailing slash to the one without trailing slash?

Select the Enforce clean and canonical URLs checkbox in  admin/config/search/redirect/settings.

Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing trailing slashes, ensure the language prefix is set and similar clean-up.


Using db_query in Drupal 7 I'm in the process of porting my contrib module from Drupal 6 to Drupal 7, and I'm getting a little stuck with how I should got about using db_query() in Drupal 7. I know it now uses a similar syntax to PDO, but I'm not quite sure how to translate the following line from the Drupal 6 version of the module:

if ($result = db_query('SELECT name FROM {variable} WHERE name LIKE "%%%s%"', 'csm_node_temp_')) {
while ($array = db_fetch_array($result)) {
  $variables[] = $array['name'];
}

}

This code removes all of the variables that my module has added to the variable table; i.e., all variables with names that start with the string "csm_node_temp". How should I rewrite these lines for the Drupal 7 version of my module?

The D7 equivalent would be:

$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');

foreach (db_query($sql, $args) as $result) {
  $names[] = $result->name;
}

Or if you wanted a structured query using db_select():

$variables = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE');

foreach ($variables->execute() as $result) {
  $names[] = $result->name;
}

n.b. the above are the most basic use of either of those functions. With some of the helper methods they get a bit more powerful.

For example, you're just looking for a single column of data from your query. The DB API can handle this with the fetchCol() method. So for the first example you can do:

$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');
$names = db_query($sql, $args)->fetchCol();

and for the second:

$names = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE')
  ->execute()
  ->fetchCol();

In both cases $names will contain an array of the names found by the query. Much easier than looping over the results manually :)


Strange symptoms after Drupal 8 core update I'm new to Drupal 8.

After updating D8 Core to 8.3.2 when I try to access Block Configuration Page, I get this error:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.block.disable" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of core/lib/Drupal/Core/Routing/RouteProvider.php).

Moreover, a new entered view path gives "page not found".

You probably have the 8.x-3.0-alpha2 or an earlier version of the rules module installed.

Updating the rules module to 8.x-3.0-alpha3 or later should fix this issue too.


Adding Quick Tabs Programmatically to a node is not working I'm writing below code in my node--type.tpl.php, but only empty page is loading when i load the node page.Can you please help in knowing my mistake.
What i need to add to display quicktab and its corresponding viewmode content?
my code is:

<?php
 $nid=$node->nid;

$tabs['Home'] = array(
  'title' => t('Home'),
  'type' => 'node',
  'nid' => $nid,
  'viewmode_home' => TRUE,
  'hide_title' => FALSE,
);
$tabs['About'] = array(
  'title' => t('About'),
  'type' => 'node',
  'nid' => $nid,
  'viewmode_about' => TRUE,
  'hide_title' => FALSE,
);

$quicktabs['qtid'] = 111; //given a random number
$quicktabs['tabs'] = $tabs;
$quicktabs['style'] = 'Mac';
$quicktabs['ajax'] = FALSE;
print theme('quicktabs', $quicktabs);
?>

I got this to work using node--typename.tpl.php

$tabs = array(
      array(
        'title' => t('Overview'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_1',
        'args' => $node->nid,
        'weight' => 0,
      ),
      array(
        'title' => t('Dimensions & Weight'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_4',
        'args' => $node->nid,
        'weight' => 1,
      ),
      array(
        'title' => t('Shipping'),
        'type' => 'view',
        'vid' => 'ps3_games',
        'display' => 'default',
        'args' => $node->nid,
        'weight' => 2,
      ),
      array(
        'title' => t('Ratings & Reviews (' . $node->comment_count . ')' ),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_3',
        'args' => $node->nid,
        'weight' => 3,
      ),
    );
    $qtoptions = array(
      'style' => 'Zen',
      'ajax' => FALSE,
    );
    $qtname = 'commerce_product23';
    $quicktabs = quicktabs_build_quicktabs($qtname,$qtoptions,$tabs);
    print drupal_render($quicktabs['content']);

works with views, but if I try to use nodes it does not.

You should try another method.

Create a Quicktab using the Quicktabs UI. Then create a custom module to override the settings/output of the quicktab using the machine name to target a specific quicktab

For Example:

 function mymodule_quicktabs_alter($quicktabs) {
    $nid = $node->nid
        if ($quicktabs->machine_name == 'quick_tab_front_page') {
        $quicktabs->tabs = array(
          0 => array(
        'nid' => $nid,
        'view_mode' => 'full',
        'hide_title' => 1,
        'title' => 'Full',
        'weight' => '-99',
        'type' => 'node',
          ),
          1 => array(
        'nid' => $nid,
        'view_mode' => 'teaser',
        'hide_title' => 1,
        'title' => 'Teaser',
        'weight' => '-99',
        'type' => 'node',
          ),
        );
        $quicktabs->renderer = 'quicktabs';
        $quicktabs->style = 'Arrows';
        $quicktabs->options = array();
        }
        }


How to theme the $item in views-view-grid.tpl.php I'm just beginning to learn theming Drupal 7, and have encountered something I can't seem to find any info on (and my experiments have no effect).

In tao/rubik theme, and in many others there is the  views-view-grid.tpl.php template which arranges the resulting items from a view in a grid design.

Now, at the very end, after splitting into rows and columns there is a print $item which is the section that prints the actual node content/teaser in the grid square. I'm assuming the content is a node, since this is what I set the view block to display, also I set it to display the full content of that single node.

However, no matter what I do, I can't seem to modify the template of this node... how should the template be called? should it be placed somewhere special?

What am I missing?

If you are asking how to theme the display of a node, those templates have names like node.tpl.php, node--NID.tpl.php, node--TYPE.tpl.php, etc.  Lots of information on templates can be found here


How do I set the height and width for images that use a responsive images style? When using the core Image module, the height and width of images are automatically set.  But when I use the Responsive Images module and a Responsive Image style, then no height or width is set.
Users don't like this because it makes the website look janky because images can pop into place and change the layout suddenly. Google doesn't like this because it slows down the page.  When testing with Lighthouse, it gives the following recommendation:

Set an explicit width and height on image elements to reduce layout
shifts and improve CLS. Learn more

There was also an article in Smashing Magazine this year about setting height and width.
How can I do this in the Responsive Image module?

The code for this is actually pretty simple.
There are a few important points.

For this to work, all of the responsive images in a single responsive image style must have the same aspect ratio. They can have different heights and widths, but the aspect ratio must be the same.
You have to set the height and width to be the maximum possible (the height and width of the largest image in the responsive image style).

Assuming your responsive image style has a machine name of hero, here's some example code:
/**
 * Implements hook_preprocess_responsive_image() for MYMODULE.
 *
 * {@inheritDoc}
 */
function MYMODULE_preprocess_responsive_image(&$variables) {
  $style_id = $variables['responsive_image_style_id'];
  if ($style_id === 'hero') {
    // Set the height + width to the aspect ratio for all images.
    // Use the largest possible height + width that may be displayed.
    $variables['img_element']['#attributes']['height'] = 450;
    $variables['img_element']['#attributes']['width'] = 800;
  }
}


Securing only a part of a page I am using login box on all pages. Is there a way to secure only the login box part of the page ?

You can use SSL Certification for securing Login Box which opens the box on https. Add a Login link to your pages and it opens the login box on https.


What is this hook supposed to do? I need to modify the query of one of my views. I've found hook_views_query_alter(), but can't for the life of me figure out what I'm supposed to do with it. According to the API,

  This hook should be placed in MODULENAME.views.inc and it will be
  auto-loaded. MODULENAME.views.inc must be in the directory specified
  by the 'path' key returned by MODULENAME_views_api(), or the same
  directory as the .module file, if 'path' is unspecified.

OK, so I know to put the function with the hook in a views.inc file. But what do I need to put in the actual .module file? I can't seem to find any examples of complete module code that uses this hook to point me in the right direction. Does my module code contain the MODULENAME_views_api() and nothing else?

If your module doesn't need to implement any other hooks, then yep, hook_views_api() is all you need in your .module file.

As long as you provide the right path in hook_views_api(), Views will know where to look and will dynamically include the files when they're needed.

Usually you need to put files[] = mymodule.FILENAME.inc in your module's .info file for the dynamic code registry to pick it up, but from the looks of it that isn't the case for Views.

If you're looking for some code examples for this, take a look at the Administration Views module; it's .module file contains only hook_views_api() as well (and it works), so you can be confident you're doing the right thing.


Drupal Crumbs can't get first "level" to show breadcrumb? I seem to be having a problem with Crumbs and I can't seem to figure it out. I have it setup to show

crumbs.home_title
path
menu.hierarchy.main-menu
*

But it doesn't seem to show anything for the very first level, anything under that shows fine. I can't seem to figure out what is going on. At least it should show the Home title?

As Clive said, this ended up being a configuration issue on my part.

Shortest visible breadcrumb under /admin/structure/crumbs/display was set to 3 levels.


Changing colors per page through drupal interface Using Content type: News, I have created pages NewsItem1, NewsItem2

I would like to have a background and color blue to NewsItem1 page
and set the pink background to NewsItem2 page through Drupal admin. Is that possible?

I am using Drupal 8.5 version. I think themekey module allowed to do this but it is not available for D8. I couldn't find any other easy way to do this. Any suggestions? Thanks in advance.

You will probably have to add a "Background Color" field to the content type with some selections that map to CSS class names.

Then, depending on where you want to add the background (e.g. on the body or on just the main content area), to add a preprocessor function in your theme to add the selected class as a variable that can be used by the twig template.

E.g. for just the main content area, you would use something like:

function bartik_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    if (!$node->color->isEmpty()) {
      $variables['bg-class'] = $node->color->getValue();
    }
  }
}

Copy the page.html.twig file to your theme's templates directory and add the bg-class to the section you want that color.  E.g. class="{{ bg-color }}".


Drupal load form with ajax callback in Bootstrap modal I need to load a form into a 'bootstrap modal dialog' which will submit data via ajax callback to callback function.

The form display properly when the modal dialog is launched:

The menu 'document/share call the function 'modal_share()' that display the modal content

...
content
...

Within this function modal_share(), a form is called for render:

function modal_share($fid) {

$f = drupal_get_form('modal_share_form',$fid);
....
....
echo
 .... ".drupal_render($f) .".....

}

So far so good and the modal is correctly output with the form 'modal_share_form' as per below structure:

function modal_share_form($form,&$form_state,$fid) {
form['share_list'] = array(
  '#type' => 'select',
  '#multiple' => TRUE,
  '#options' => $option ,
  '#title' => t(""),
  '#description' => "",
  '#required' => false,
  '#default_value' => $default

);

$form['share'] = array (
        '#type' => 'button',
        '#value' => " ".t('record')."",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method'=>'html'
        ),

        '#id' => 'modalsharebutton',
);
return $form;
}

Now the problem is the the #ajax function in the button is not rendered by drupal as it should.

the html rendering is:

<button id="modalsharebutton" class="btn btn-primary form-submit" type="button" value="record" name="op">

without the "ajax-processed" class attached

The thing is that if I load the form on a main page ajax function is rendered properly.

So my conclusion is that when building the form for modal, it is not going through the proper ajax build process...

But I can't see the solution.

Thanks for help.

I solved this issue differently by adding '#attribute' with event...

$form['share'] = array(
        '#type' => 'button',
        '#value' => " " . t('Record') . "",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method' => 'html'
        ),

        '#id' => 'modalsharebutton',
        '#attributes' => array('onclick' => "share_submit($fid);"),

);

Thank you.


date time countdown module? trying to create a groupon-deal style 'time left to buy' field, a dynamic countdown field.

Any modules can do this?

The http://drupal.org/project/countdown module does this on a block level, but since all the 'heavy lifting' is done on the client side with javascript, I wouldn't imagine it would be all that difficult to rejigger it to look at an appropriately css'ed field...


How to pass data from a Rules Action to a subsequent Rules Action? How I can add actions in the Rules module in which they have a relationship with each other sequentially.

I mean a 1st Rules Action sequentially passes data to a next Rules Action and in that next Rules Action I can use those passed data from previous data.

I think you can pass data with Variables , in one action set variable(s) and in next action get that variable(s),this have one bug if concurrent event occur data will return mistake values, a solution for this is using unique variable name per user(or action), I get you a clue (maybe you get idea from it)

in Action1
set Php action

 global $user;
 // some job here
 // $result= .....
 variable_set("action1_result-".$user->uid, $result);

in Action2
set Php action

 global $user;
 variable_get("action1_result-".$user->uid);


Migration issue: Drupal markup isn't rendered on CiviCRM pages I've moved a Drupal 6 / CiviCRM 4.3 site to a development server, and I'm getting really strange behavior. When I visit a Drupal page on the copied site, everything renders as expected. However, when I visit a CiviCRM page, the CMS part of the markup is missing from the source. It's almost like every CiviCRM page is being delivered as a snippet.

To be more specific, when I go to /civicrm and view source, I get markup beginning with:

  ...

The opening and closing HTML tags, and all the HTML contained in the Drupal theme are entirely absent. The same appears to be true for every CiviCRM page.

I've tried the following:

reviewing my CiviCRM settings file
reviewing my directory and resource settings
clearing Drupal caches
emptying sites/default/civicrm/templates_c
deleting sites/default/civicrm/ConfigAndLog/Config.IDS.ini
running drush civicrm-update-cfg
checking error logs for Apache, Drupal, and CiviCRM
throwing salt over my left shoulder

Any ideas what might cause such strange behavior? Suggestions for something I might have missed in my migration or a good place to put debugging code to get to the bottom of this?

Ah, I think I've seen this before, did you by chance mess with your CiviCRM settings file?

Double-check your CIVICRM_UF setting, Civi might be tripping up if it thinks the CMS is something other than what it actually is.

For Drupal 6 you want CIVICRM_UF = 'Drupal6'


How do I dynamically fill a textfield with #ajax? As the title states, I'm wondering how I dynamically fill a textfield using an AJAX callback from a "select" form field.

I'm trying to test a select form with a number of options that, when changed, populates the textfield with data. I've tried setting the textfield's "#default_value", but it doesn't seem to work. Setting "#value" does work and I do get the information to show up in the textfield but this presents another problem. When I try to go to the next step and have a button save the data, the textfield's value remains what I set it to and doesn't change. What I mean is that when I select an option in the select form, the textfield gets populated correctly but if I change the textfield and hit save, the $form_state value is still what I set it to not what I changed it to. Is what I'm trying to do even possible?

$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper'
    )
);

$profile = isset($form_state['values']['profiles']) ?
             _get_profile_info($form_state['values']['profiles']) : NULL;

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => 'Profile Name',
    '#value' => $profile == NULL ? '' : $profile[0]->{'name'}
);

$form['profile_save'] = array(
    '#type' => 'submit',
    '#value' => t('Save Profile'),
    '#submit' => array(
        'save_profile'
    )
);

I'm saving the value of my textfield from the $form_state into a file for testing right now.

function save_profile($form, &$form_state){
    $fh = fopen('C:\out.txt', 'w+');
    fwrite($fh, $form_state['values']['profile_name']);
}

function profile_callback($form, &$form_state){
    return $form['profile_name'];
}

After messing with this for a while, I discovered that I needed to unset the textfield. Once I did this default_value started to work with ajax, below is the final code I had.

unset($form_state['input']['profile_name']);

$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper',
    ),
);

$profile = isset($form_state['values']['profiles']) ? _get_profile_info($form_state['values']['profiles']) : NULL;

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => 'Profile Name',
    '#default_value' => $profile == NULL ? '' : $profile[0]->{'name'},
);


Search API Views Indexed Node Filter by Author Role I have Search API installed, and have indexed all of my nodes.

The nodes all have a different Author, and the Authors have roles "Free user", and "Business User".

I only want the nodes belonging to Business Users showing up in search.

I created a view, the search works perfectly on indexed fields, but I cannot filter by Author:Role

I have added a relationship of Indexed Node: Author, but still no filter available.

Anyone know how I can achieve this?

You need to index the author's roles so that Search API can query that field.

Visit the fields configuration page for your node index (probably admin/config/search/search_api/index/default_node_index/fields if you're using the default node index).  At the bottom of the list of fields you'll see a fieldgroup called "add related fields".  Expand that, choose author, click "add fields".

When the page reloads your big list of fields will now contain a bunch of new Author-related fields including Author » User roles.  Check the box next to that one, choose how you want it indexed (integer or string are probably the only ones you'd care to use for this purpose), save your changes, and re-index your content.

I've found that with these sorts of changes I need to clear my cache twice in order for the proper data to be registered with Views and for the appropriate filters to appear in my Views.


hook_menu() wildcard problem I can't get the wildcard from a hook_menu to pass it to a callback function

Here is what I have:

function spin_menu() {
    $items = array();

    $items['spin/login/%'] = array(
        'title' => 'SPIN',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
        'page callback' => 'spin_check_access'
    );

    return $items;
}

function spin_check_access($type = '') {
    echo $type; // type is never the %
}

Is it correct? I need the $type to be replaced with the wildcard's value.

You have two options:

function spin_menu() {
  $items = array();

  $items['spin/login'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
  );

  $items['spin/login/%'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
    'page arguments' => array(2),
  );

  return $items;
}

Hook menu will not send any wildcard params to the callback function, but it will send params not defined in the url. So in the first example if you go to spin/login type will be '' and spin/login/foo type will be foo. For the second example spin/login will return 404 and for spin/login/foo type will be foo.


Display in node custom field profile I created a custom field in the users profiles.

I need to display in node.tpl.php, this field for the author of the node.

I tried :

<?php
print $node_author = user_load($node->uid);
print ($node_author->field_custom);
?>

But i have an error :

Recoverable fatal error : Object of class stdClass could not be converted to string

Do you know where I'm wrong?
And, is it the best way of proceeding?

Try with print render($node_author->field_custom);

Or you can try as well:

insert at the top of you node.tpl.php

<?php
global $user;
$node_author = user_load($user->uid);
$yourvariable = $node_author->field_custom;
?>

Where you want print the field insert:

<?php print $yourvariable['und'][0]['value'];?>


How to prepopulate a term reference field with multiple values on a new form? I seem to struggle with a problem which has already been answered. I have a 'review' form on which there is a field that I want to prepopulate. It is a term reference field and I want it to be prepopulated with taxonomy values from another node. I have looked at this issue without success. Any help would be greatly appreciated.

function my_module_form_alter(&$form, &$form_state, $form_id) {
      $nodeid=$_GET['id'];
      $node=node_load($nodeid);
      if ($form_id == 'review_node_form') {
        $form['field_revactivities']['und'][0]['value']['#default_value'] = $node->field_ad_tags['und'][0]['tid'];
      }
}

I know that '$node->field_ad_tags['und'][0]['tid']' returns the number of the term, but I am not sure how to get the value into the new field.

Also, if there are multiple terms for the field, should I populate the field for each term by incrementing [0], then ['1'], etc...?

Answering my own question:
1) First aspect is to feed the data correctly to the term reference field. The magic formula I found is:

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

where $bidule is a the string of taxonomy term (not its taxonomy id).

2) If there are multiple elements in the field_ad_tags, then I had to create a loop to place them all one after the other in a string. It was important to have the exact wording of each taxonomy term for the field to recognise which tag it is and to separate them with a comma. Here is my final code:

$bidule = '';
$i=0;
foreach ($node->field_ad_tags['und'] as $truc => $value) {
        drupal_set_message('<pre>$truc '. print_r($value, TRUE) .'</pre>');
        $term = taxonomy_term_load($node->field_ad_tags['und'][$i]['tid']);
        $name = $term->name;
        $bidule= $bidule.','.$name;
        $i++;
}
$bidule=substr($bidule, 1); // Remove the first character ','

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);


Create a View of Group Posts Who's Group has a Specific Tax Term? Hi i hope someone can help me get my head about this. I dont know if im just having a blonde moment though.

I have tax terms added to my 'groups' (blog, betting, diary etc) I was wanting to create a view showing just posts in Groups that have the term 'blog' attached to the Group. The posts in Groups tagged with 'blog' do not have the term 'blog' in the posts so thus they will not show in any views i create. I hope im making sense here as i think im just confusing the issue.

I think i would need some sort of Relationship to create the View Ill try explain again. I only have one Group content type 'Groups'. Each group has a term (blog, betting etc) I want to...bah im just saying the same thing again arent i?...How can i show just my 'Group Posts' whos parent Group is tagged with 'betting' in a view?

In addition to your view configuration, you need to set up a group node relationship and filter out group nodes by taxonomy term. This should do it for you:

Add relationship: Organic groups: Group node (post)
Require this relationship: checked

Add filter: Taxonomy: Term
Vocabulary: Your Vocabulary
Selection type: Dropdown
Relationship: Group node (post)
Operator: Is one of
Select terms from vocabulary Your Vocabulary: blog


How to get image with image style path to a twig template I had created a field called tv_adbackground on the settings filed to be a ble to uplaod a background image.

The upload works great!

How to get the path of the file or the image style medium or thumbinal in to a twig template like this?

...

It can be done with the help of two additional modules.

Twig Field Value - to get the path to the image and
Twig Tweak - to get the image style version of an image.

Then in your Twig template you would use something like this to get the image style path:

{{ content.field_image.entity.uri.value | image_style('medium') }}

where field_image is the name of the image field.

If you use something like the Media module then your images come from a referenced entity. In that case you could use

{{ file_url(content.field_referenced_entity | field_target_entity.field_image.entity.uri.value | image_style('medium')) }}

and field_referenced_entity would be the media/entity reference field and field_image the name of the image field on the referenced entity. Notice that in the second case the whole path is wrapped in file_url().


Inheritance value from the exposed filter I've got content-type with two double-valued fields field_price1 and field_price2. There are interior names. I've also got page view (its machine name is search) displaying contents. I've got search with some filters. I decided to create one exposed filter connected with field_price1 field with between operator. Second filter isn't exposed and it is connected with field_price2 field.

I want to display content in the view only if its field_price1 or field_price2 is between values given by user in the search. So that, filter for field_price2 field has to inherit the value from the first exposed filter. I created custom module named customSearch with code posted below in customSearch.module file.

function customSearch_views_pre_view(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

Unforntunately, I've got errors.

  Notice: Undefined property: view::$exposed_input in
  customSearch_views_pre_view() in line
  $filters['field_price2_value']['value']['min'] =
  $view->exposed_input['field_price1_value']['min'];

  Notice: Undefined property: view::$exposed_input in
  customSearch_views_pre_view() in line
  `$filters['field_price2_value']['value']['max'] =
  $view->exposed_input['field_price1_value']['max'];

Could someone help me, please?

Try replacing

function customSearch_views_pre_view(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

with

function customSearch_views_pre_execute(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

And then clear your cache.