How to pass variable from WidgetBase to .module In Drupal 8 my module looks like this.

<?php

function signature_field_theme() {

  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => array(
      'sign_src' => NULL,
      'text_area_id' => NULL,
      ),
  ];
  return $theme;
}

function signature_field_page_attachments_alter(&$page) {
  $page['#attached']['drupalSettings']['signature_field']['sign']['id'] = 'id';
}

My SignatureWidget.php file looks like this...

<?php

namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    //$element['#suffix'] = \Drupal::service('renderer')->renderPlain($sign_thumb);

    return array('value' => $element);
  }

}

How can I pass $text_area_id from the widget to the module in order to use it as a variable in function signature_field_page_attachments_alter

Just incase someone stumbles upon this and struggles to follow the thread above this is how to pass the variable.

$element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

Here is the full widget code.

<?php

namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

    return array('value' => $element);
  }

}

It is then available in your JS as follows.

var canvasId = drupalSettings.signature_field.sign.id;
            console.log(canvasId);


Exposed filter (by terms), only to show terms related to this content type I'm using the Vocabulary 'Tags' in multiple content types.

I have a view showing 'Content Type A', and I want to have an exposed filter showing only the 'Tags' used in 'Content Type A', not every content type.

Any ideas on how this can be achieved would be greatly appreciated, thanks!

You can use hook_form_alter to alter the exposed form:

<?php
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'form_views_exposed_form') {
    drupal_set_message("Form ID is : " . $form_id);
  }
}
?>

Just write some code that fetches all the used categories in content type A and compare those with the categories in the dropdown. Then, unset the categories that aren't used.

You can do this by building an array that has the same structure as the options in the drop down and then use array_intersect to get all the values that are shared over your custom build array and the options in the dropdown.


Multilingual redirects don't work from node url Drupal 7, node translation method being used. Having an issue with translated content url aliases right now. Aliases work, language prefixes in urls work, but using the node/# url does not redirect to the node's alias if not in the default language. English is set to the default language.

Example:

English version: node/1 if being viewed goes to its alias, /alias.

French version: node/2 if being viewed does NOT go to its alias, /fr/french-alias, node is viewed correctly at node/2. If you view /fr/french-alias you see the node correctly as well. So you can view the French version of the node two ways when I really want only /fr/french-alias to work and if you go to node/2, I want it to redirect to its alias.

It's like the site is having the issue of applying the language prefix in the url to redirect with. How do I correct this?

tl;dr: The Global Redirect module with the option Language Path Checking enabled may allow you to enforce redirects for all users.

Node translation can be quite mindboggling. Aliases are stored per language, but that language is determined by the current path language.

With English being your site's default language, if you visit /node/2 instead of /fr/node/2 Drupal will look up the English alias for node/2. Likewise if you visit /fr/node/1, you won't get redirected since Drupal is looking up the French alias (which does not exist).

The Translation Redirect module (part of the Internationalization project) solves this, but with one gotcha:

  Note that, by design, translation redirection does not work for the homepage or for authenticated users.

(Link added by me.)

As irritating as this may sound at first: Redirecting editors to a node's language prefix brings with it a host of problems that aren't obvious at first, but can render parts of the backend unusable.

Depending on your translation workflow you may want to consider using the Entity Translation module instead.


Disable form or block cache for anonymous users? I have two forms in Drupal 8 that I am prepopulating values with if a value exists in the query string.

$keywords = Xss::filter($this->requestStack->getCurrentRequest()->get('keywords'));

$form['keywords'] = [
      '#type' => 'textfield',
      '#maxlength' => 128,
      '#size' => 64,
      '#default_value' => Unicode::strlen($keywords) ? $keywords : '',
      '#prefix' => '
',
      '#suffix' => '
',
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => Unicode::strlen($keywords) ? $keywords : t('Search Site'),
      ]
    ];

Works great for authenticated users, but for anonymous users, they are always seeing the last term entered, despite the query string having nothing in the URL. Even if I close the browser and come back, the term is still in the input field. I assume it gets cached.

The form is being attached as a twig variable to a block containing other content:

/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }

  // inject main nav search form to block template for main_nav only
  if ($variables['elements']['#id'] == 'main_nav') {
    $variables['main_nav_search_form'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule_search_forms\Form\MainNavSearchForm');
  }
}

Is there a way to change this so that does not happen? Any cache tag I could use?

What you need need to do, is not to use a cache tag but a cache context. In your specific scenario you want to use url.query_args:keywords. In code that would look like this

$form['keywords'] = [
   '#cache' => ['contexts' => ['url.query_args:keywords']],
   ...
];

For reference.

Cache tags are used to invalidate cache. Like if a cache element is tagged with node:1 and node with nid 1 is updated, then all cache containing node:1 cache tag is invalidated (other tags are also invalidated).

Cache contexts are used if cached element exists in multiple variations based on something like the query arg. What happens is that multiple cache entries are created and they will all be invalidated based on the same logic (cache tags).


Change  class on one specific menu? I'd like to change the  class from "menu" on one specific menu I have showing up as a block on about 3 pages in a Drupal 7 site. I've been researching but can't seem to figure out the best way to go about doing this.

You can do this with theme_menu_tree() hook in your theme's template.php file.
Or with a more specific version of theme_mene_tree() hook like MYTHEME_menu_tree__MYMENU().

function MYTHEME_menu_tree__MYMENU(&$variables) {
    return '
' . $variables['tree'] . '
';
}

See more here https://gist.github.com/gagarine/3201854

UPDATE:

if menu machine name have hyphne like main-menu then change hyphen to underscore, like MYTHEME_menu_tree__main_menu()


how to give relative path in drupal for setting an image Hi all,
      iam trying to set image here in a module .The image is in the same module folder. but iam not able to get the image path

This is the error which iam getting ..cleary states no path

  How to get a relative path in module to display images?

Try this code.

$path = drupal_get_path('module', 'myModule') . 'image/projectsetup.jpg';

now set src = '$path' into your .module file where you set image src.


Page not found with new content I just create a new content type and add a couple of nodes but I get 'The requested page could not be found.' message with anonymous users, apparently the nodes of this new content type require admin permissions, I've been searching on user management and enable access content but for this particular content type still need admin permission, any idea?

I believe this is a caching issue.

'The requested page could not be found.' is not the same as 'You are not authorized to access this page.'

Because you can see the page as the admin account but not as an anonymous user, I believe you can fix this issue by flushing your Drupal caches.

The admin account doesn't show cached content by default but the anonymous users do.

There are several ways to Clear Drupal's Cache but the simplest is likely to go to admin/config/development/performance.

If you use drush, simply run 'drush cc all'


Add variables in custom input template In D8 I created a custom input twig file (based on input.html.twig) :

{{ icon }}

<input{{ attributes }} />{{ children }}

Then I created a new entry in hook_theme() :

function my_module_theme() {
 return [
   'input_custom' => [
     'render element' => 'form',
     'variables' => [
       'icon' => NULL,
     ],
     'template' => 'input-custom',
   ],
 ];
}

Then I'm loaded the template in my form element :

$form['my_field'] = [
        '#type' => 'textfield',
        '#theme' => 'input_custom',
        '#icon' => 'my_icon',
        '#title' => $this->t('My title'),
      ];

My custom variable is sent to the template but I lost all html attributes on the input. If I remove variables from my_module_theme() all html attributes are back, but I'm losing my custom variable.

How can I send custom variables in custom input template ?

Declare a #theme starting with the base hook of the input element and a double underscore:

  $form['my_field'] = [
    '#type' => 'textfield',
    '#theme' => 'input__custom',
    '#icon' => 'my_icon',
    '#title' => $this->t('My title'),
  ];

Prepare additional variables in a preprocess hook:

function mytheme/mymodule_preprocess_input(&$variables) {
  if ($variables['theme_hook_original'] == 'input__custom') {
    $variables['icon'] = $variables['element']['#icon'];
  }
}

Then you can use the added variables in the input template:

{{ icon }}


Individual CCK Imagefield promote-to-front At the moment, my view creates a gallery of images by fetching all images across multiple node types. What I need is a way to indicate which images should be used in the gallery. So, instead of my view simply displaying all images, I want the client to indicate which image they want to "promote" to the gallery.

Can anyone help please?

Here is another option, that will work for sure.  May need to do a bit of reconfiguring with your current imagefields.

Download latest version of CCK 3.x.
Install multigroups module (currently this module is stable)

On the selected content type:

Add on/off checkbox featured field (set limit to 1)
Add Image field (set limit to 1)
Encapsulate theses 2 fields in a multigroup (set limit to unlimited)
Create view that will filter on featured field


AJAX added fields don't hide I have a altered registration form with a check box that when checked adds few fields. The fields are wrapped in a specific div.

The callback function of check box is supposed to hide the dive when the check box is unchecked.

The adding works well but the unchecking doesn't. If I uncheck the checkbox the added fields remain there as nothing has happened. Checking it again doesn't change anything.

The weird thing is that the div is there (at least Firefox inspector sees it) and the callback function is probably fired as well (the POST is send).

I have even tried to debug it using dsm() but it doesn't show any message (no idea why).

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

  $form['fm_first_in_firm'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show form.'),
    '#ajax' => array(
      'callback' => '_fm_ajax_new_firm_form',
      'wrapper' => 'firm-reg-container-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['firm_registration_container'] = array(
    '#type' => 'hidden',
    '#attributes' => array('id' => array('firm-reg-container-div')),
  );
}

function _fm_ajax_new_firm_form($form, &$form_state) {
  if ($form['fm_first_in_firm']['#value'] == 1) {
    dsm('tst1');

    ...

    $firm_form = drupal_get_form('fm_firm_node_form', $node);

    $form_wrapped = array(
      '#prefix' => '
',
      '#suffix' => '
',
    );

    $form_wrapped['register_form'] = $firm_form;
    return $form_wrapped;
  }
  else {
    dsm('tst2');
    return array(
      '#type' => 'hidden',
      '#attributes' => array('id' => array('firm-reg-container-div')),
    );
  }
}

To show or hide some form elements you can use #states attribute.

$form['fm_first_in_firm'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show form.')
);

$form['firm_registration_container'] = array(
  '#type' => 'item',
  '#attributes' => array('id' => array('firm-reg-container-div')),
  // make this form item visible only if "fm_first_in_firm" is checked
  '#states' => array(
    'visible' => array(
      ':input[name="fm_first_in_firm"]' => array('checked' => TRUE)
    )
  )
);


What's the relative path to a user's profile? I've created a clickable block with Views and rewrote the fields with HTML like this:

<a href="user"> some divs... </a>

Clicking the block should refer the logged-in user to his/her profile. As the code mentions, I'm using user as relative link, but a problem occurs when the user clicks the link when he/she is already visiting his/her profile: the link is then turned into mysite/user/user instead of mysite/user.

Using /user doesn't work either, because it redirects the user to localhost/user instead of localhost/mysite/user.

What's the correct way to construct a path that takes into account either being relative or the $base_path?

There is no, and can not be always correct relative path.

Relative path is relative, and there is no infinite amount of paths to user profile, to be in the same relation with each and every path in your system. There cannot be. What you need is to properly generate an absolute path instead.

So instead of the code you are using, use Drupal's built-in link generator, l():

<?php print l('some divs', 'user'); ?>

or, if above is not feasible, url():

<a href="<?php print url('user'); ?>"> some divs... </a>


Form States conflict I've two forms in a page, one of the field name is same in both forms.

<form id="form1">

        <select id="field_a" name="field_a_name"> ... </select>

</form>

<form id="form2">

        <select id="field_a" name="field_a_name"> ... </select>

</form>

In hook form_alter, i assign the states to the field:

 $field_state = array( 'visible' => array(':input[name="field_a_name"]'
 => array( array('value' => 'H') ))       );

 $form['field_a_name']['#states']   = $field_state;

The state does not work as expected, i believe it's caused by the same field name, most likely because of the jquery selector confused with the two fields with same name.

It works fine if the field name are different.

How to solve this?

In states you can use jQuery selectors. For example add form id to state selector:

$field_state = array(
  'visible' => array(
    '#form1 :input[name="field_a_name"]' => array(
      array('value' => 'H'),
    ),
  ),
);


Image module for photogaleries I wanted to download Image module, but I notice that it's not for Drupal 7. Is there some alternative I can use in Drupal 7?

thank you

The Future of Image in Drupal 7 reports the following text:

  Image module is being put into core, but not in its current incarnation. Drupal 7 has already made several major improvements that will make handling images (and files in general) much easier, eliminating a lot of the existing code from image.module.

  The Drupal 7 core plan is as follows:

  Move ImageAPI into core to provide better support for toolkits such as ImageMagick (done).
  Move ImageCache into core to provide thumbnailing abilities as part of image.module (in progress).
  Move FileField into core as file.module.
  Move ImageField into core as part of image.module.

This means that most of the functionality of those modules are already integrated in Drupal 7.
ImageAPI still contains code that has not been merged with Drupal 7 code; you should install it if you need the ImageMagick toolkit it implements, or the unsharpen mask action.

As gallery modules, you can try:

Galleria
Fast Gallery
Galerie


How to disallow some emails in Drupal 7? Some temporary emails are frequently used by human spammers and I want to disallow them either from registration or posting.

I know that there is a similar question here but that one is for D6 and did not work for me. I'd like to do that in D7. Appreciate your help.

Use the User Restrictions module. This module allows you to block both emails and usernames based on certain patterns.

For example, to block mails from spammers.com create a user restriction with:

Access type: Denied
Rule type: Email
Mask: %spammers.com


Render private image on twig template I have a content type with a private image field. I would like to render the image on the twig template in order to show it to the user when it has enough permission, but the image source is a private directory and I don't know what could be the path to show it.

Normally you would configure the formatted output of an image field in the content type and then render it in the node template:

{{ content.field_image }}
{{ content|without('field_image') }}

If you want to access the path of a private file directly then use the file scheme private://:

{{ file_url('private://foo.jpg') }}


Is it possible to turn on/off two layers at once with the openlayers_plus module? Using the BlockSwitcher module that comes with the openlayers_plus module, is it possible to create a button that turns on/off two layers at once?

I think the best way to do this would be to create a function that uses setVisibility()

For example (without toggle logic):

$('.my-button').click(function(e) {
  e.preventDefault();
  var ol = $('.openlayers-map').data('openlayers');
  ol.openlayers.getLayersByName('myLayerName1')[0].setVisibility(false);
  ol.openlayers.getLayersByName('myLayerName2')[0].setVisibility(false);
});


HTML stored in text field and not rendered in view I'm trying to render HTML that's stored in a text field in a view. The output looks like this

My text

If I inspect it, it's wrapped in quotes so it's treated as a string. How do I parse this on the front end?

I've never used this, but you could try the Simple Field Formatter


Which library is better for image processing, GD2 or ImageMagick? Is ImageMagick is supported by Drupal 7? If the answer is positive, which is better for image processing, between GD2 and ImageMagick?

Are any other alternatives for Drupal 7?

Drupal 7 supports ImageMagick with the ImageMagick module

I suspect better is subjective depending on your specific image manipulation tasks. The benchmarks I could find didn't conclusively favor either one overall but specific tasks were faster in one or the other. Opinion favors ImageMagick for quality but recent posts suggests GD2 has caught up.


How to set a different theme when the site is on maintenaince mode? Hi i am searching for a way to change the active theme when the site is on maintenaince mode (Drupal 7), can you help me? thanks in advice

I think there is no way to set active theme while on maintenance mode, but you can change the way site looks.

For that to happen in your local site there is /modules/system/maintenance-page.tpl.php available.

You can overwrite as you need by pasting this into your theme directory.

Then in settings.php you need to set

$conf['maintenance_theme'] = 'ThemeName'


Allowing a user role to edit only their own content I am having some difficulty setting up a user role that can access the admin/content/node section of the site but only view their own content.

For the user role i have some permissions set like so (events is a custom content type)

create events content
delete own events content
edit own events content

The admin/content/node will not appear unless i set a permission.

administer nodes

This allows the user role to create, edit, delete any content. Definitely not what i need!

Reference:

Permissions Reference
Possible duplicate

Can anyone shed some light on how to allow user roles to only access their own content?

Your best bet would be to create a view that duplicates this functionality but only references content to the currently logged in user. You could then add in View Bulk Operations to add the edit/delete links usually found on that page.

You could give the view a path of /admin/content/node/self maybe.


Why is my Strongarm feature immediately overridden? I am using features to save a content type.  Here are the fields that my new feature contains:

body  field_product_site_id  field_product_repair_price  field_product_manufacturer  field_product_description  field_product_terms  field_product_url  field_product_model  field_assigned_to  field_role_designater

node-product-body  node-product-field_product_description  node-product-field_product_manufacturer  node-product-field_product_model  node-product-field_product_repair_price  node-product-field_product_site_id  node-product-field_product_terms  node-product-field_product_url  node-user_role_marker-field_assigned_to  node-user_role_marker-field_role_designater

I decided to add the Strongarm module to capture additional fields (and hopefully save the field order/weights of my content types.)  The strongarm module added a few new variables to the list:

 field_bundle_settings_node__product  menu_options_product  menu_parent_product  node_options_product  node_preview_product  node_submitted_product

After recreating the feature, I discovered that it had become overridden.  As I understand it, features are only overridden if the data stored within it is difference that the data stored in the database.  How can this feature be overridden as soon as it is created?

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

The feature now seems to be in the Default state.  All I did was install the diff module.  Could this have been a cache issue?

I can't tell why it's telling you something is changed, but you can use Diff module to see what changed. Diff module


How to sort the blog I am trying to sort blog by title. The blog does not appear at view. Taxonomy does not has any setting related to sort. What else I should check?

The /blog path created by the blog module does not have an option sort by title. The easiest way to do this is to use the Views module to create a page view and just build a display of blogs sorted by titles.

Another way, if you're looking to alter the built in /blog path created by the blog module, you could use hook_menu_alter to alter the page callback from blog_page_last() that's in blog.pages.inc.

You can place this code in your custom module:

function mymodule_menu_alter(&items) {
  $items['blog']['page callback'] = 'mymodule_blog_page_title_order';
  return $items;
}

function mymodule_blog_page_title_order() {
  global $user;
  $build = array();

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('title', 'ASC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    drupal_set_message(t('No blog entries have been created.'));
  }
  drupal_add_feed('blog/feed', t('RSS - blogs'));

  return $build;
}


display a node id within a specific content type I'm looking for a way to display the node id somewhere on all displayed instances of a given content type.  It doesn't need to happen in any particular way, but it would sure help my users to be able to see the node id, as we use it to track physical objects.

I would imagine that there are a couple of ways to do this, so if someone could outline the options that would also help.

I've tried something like

<?php
$node_id = arg(1);
echo($node_id);
?>

To no avail, as I can only put this in each individual node instead of all nodes for a given content type.

If you're trying to do this for a certain content type, and have a custom theme you're using with your site, I'd suggest modifying the template file for that content type to print out the node id somewhere below or above the content.

However, if you're not very good with theming a really creative way to do it is by creating a view block and enabling it for that content type.  Then the node id can be displayed on the side of the content.  It can be nothing more than a line... doesn't have to be obtrusive.

To do the above:

Create a new view and call it something like 'Node id display' (uncheck the page version of the view and only create a block version).  Restrict it to the content type you want here, and make sure it's displaying fields, rather than titles, summaries or whatever is the default
Under the view's 'Fields' section, remove all fields that appear by default and only dislay the 'Content: Nid' field.  You can change the label to be something like "Node id" instead of 'Nid' if you prefer.
Under the 'Advanced' section of the view, add a contextual filter of 'Content: Nid', and in the configurations, select for it to 'Provide a default value' if a filter is not present.  From the drop-down, select 'Content ID from URL'
Either through a context or from the block's admin page, enable the new block for your specific content type... place the block on a sidebar, above the content, below the content... anywhere you want.

:-)

Hope this helps!


How to use Drupal in the cloud with on demand instances Services such as Rightscale do lots of things to help mange unpredictable traffic and bring more servers online when traffic spikes.

Is it possible to use Drupal with services such as this?

While Drupal can be set up for a number of configurations, is it possible to set it up so the configuration is flexible.

What do you need to do to make sure it works?

Assuming that you can bring on demand instances online, what do you need to do to make sure that Drupal will work in this situation. What do you have to do?

What is the optimal setup?

Once you have done what you have to do, what should you do to ensure that you can scale to more servers seamlessly. What is the best configuration in terms of number of servers. How many caching servers should you bring on line for each web server. Should you scale each tier independently?

edit

Edit to clarify that this is to do with the implications of on demand scaling for a Drupal site.

Rackspace put together a pretty decent start to this subject here which uses a couple of specific technologies which you might not want to use, but the principles are the same.

You might also need to look at Mysql clustering, but only really if you're hitting serious traffic levels


Module compatibility between major Drupal versions I am planning to use Drift chat on Drupal website, which is built in Drupal 7.

I could see Drift modules only for Drupal 8? Will this work with Drupal 7 as well?

Will this work with Drupal 7 as well?

Nope. D7 and D8 are vastly different under the hood; therefore, there is no backward and no forward compatibility across Core versions. If there are none for D7 you will have to build one or upgrade your site to D8 if you see fit.


breadcrumb containing a link to a path that's deeper than the one of the page it's on On my site i have the weird problem that for one of the menu pages the breadcrumb shows as one lvl deeper than the page it's on.

So it's showing: Home > Page i'm on > subpage i'm not on
instead of: Home > Page i'm on

In addition, contrary to other pages i have, the bottom level of the breadcrumb is clickable which makes no sense, as that's supposed to be the page i'm on (wel it's not due to the above described error, but anywho).

I've no breadcrumb-modules installed.  I do have a hook to modify the breadcrumbs like so:

function mytheme_breadcrumb(&$variables) {
  if (isset($variables['breadcrumb']) && !empty($variables['breadcrumb'])) {
    $crumbs = '
';
    $breadcrumb = $variables['breadcrumb'];
    $array_size = count($breadcrumb);
    $i = 0;
    while ( $i < $array_size) {
     $crumbs .= '
' . $breadcrumb[$i] . '
';
     $i++;
    }
    $crumbs .= '
';
    return $crumbs;
  }
}

Doesn't look like the theme_breadcrumb function is responsible, as it uses the values it's getting from drupal by standard.

Anybody any ideas as to what might be causing this?

Is it possible that there is an old link to this page in your menu that is nested in the tree like.
home
-page
--MY-PAGE

Because breadcrumbs seem to use the menu tree to build the breadcrumb items.


How to get value from {{ item.content }} I have a node named "reviews" and a custom field named "field_rating".
I created a field template named field--node--field_rating--reviews.html.twig.

I want inside the node to change the color with an if statement.

I try to do something like that:

{% for item in items %}
  {% if item.content > 5 %}

{{ item.content }}

  {% endif %}
{% endfor %}

but it doesn't work.

Any suggestions?

Drupal Version 8.6.1

You are comparing an array with a number:

item.content > 5

Try the field value instead:

element['#items'][key].value > 5

Full code example:

{% for key, item in items %}
  {% if element['#items'][key].value  > 5 %}

{{ item.content }}

  {% endif %}
{% endfor %}


Drupal 8: The proper alternative to exit(); for terminating a request Does anybody know how to avoid the brutal PHP built-in exit(); function and use the "right" Drupal 8 class method to terminate the request? If so: a bit explanation would be appreciated.

You would have been looking for drupal_exit() in the past, but this was removed in D8. It is now advised to use the appropriate HTTP Exception. See the example on the change notice:

https://www.drupal.org/node/2017339


How to parse definition lists ckeditor? I want to write definition lists with ,  and  tags with drupal commons 3 in CKEditor. I am writing code directly (while I am in source mode) then switch to WYSIWYG and go back to source. CKEditor change this tags to paragraphs.

How to not transform definitions tags (dl, dt, dd) ?

I just had this issue myself.

The way I got around it was to add them to the Extra Allowed Content in the profile edit form.

You'll also be pleased to note that while the definition list tags are being presented as p tags they are still stored as the original tags in the db. You won't need to rebuild your definition list.


Programmatically creating users attach profiles to correct uid on localhost but uid 1 on production While programmatically importing thousands of users from an old site, I'm facing this very strange behaviour. The code snippet below correctly attach commerce customer profiles to the created users on localhost site, but attach them to uid 1 on production site !

localhost is a strict copy of remote site : git clone for code and Backup and Migrate DB copy The users are imported uploading and parsing a csv file in a custom form, connected as admin

$new_user = array(
  'name' => $new_name,
  'pass' => $pwd,
  'mail' => $email,
  'init' => $email,
  'status' => 1,
);

$account = new stdClass;
$account->roles = array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  9 => 'client',
);

if ($saved_user = user_save($account, $new_user)) {
  dpm($saved_user, $new_name.'/'.$saved_user->uid );
  //VERY STRANGE HERE (ON PROD SITE ONLY) see screen capture below
  //the dpm title prints $saved_user->uid as a new uid
  //but "inside" dpm $saved_user->uid is 1 !
}

//create user commerce profile
$profile = commerce_customer_profile_new('billing', $saved_user->uid);
$profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);
//... add profile values ...
$profile_wrapper->save();

Localhost : expected uid when dpm($saved_user, $new_name.'/'.$saved_user->uid );

Production site : uid 1 instead. The user is created with the new uid though, but uid 1 is passed then to commerce customer profile

Sounds like somewhere in the first few lines of code your $account variable is getting switched to the user 1 or perhaps the currently logged in user. Perhaps trying to change the "$account" variable name to something definitely unique to see if that fixes the problem.


Modifying default workbench view filter via code Workbench ships the 'My Content' view default in code. I want it to actually show "my content" by adding a contextual filter with the author by field = current user.

I've looked into http://blog.arvixe.com/altering-default-views-in-code/, but it is a drupal 7 implementation and doesn't touch on the filtering.

The preferred approach to do those things in Drupal 7 is to:

Clone "My content" view to "My content clone view".
Make modifications to "My content clone view"
Disable "My content" (the original view).

I still haven't tried this in Drupal 8, but I think the principle should be the same.

Regards,
Oleg


microblog module - problem with max characters On the left column on http://ruh.kz, you can the output of the Microblog module. This module uses the node title as a microblog entry; the maximum length of the title is by default 255 characters. In a microblog.module I've made the following changes:

function microblog_form(&$node) {
  $type = node_get_types('type', $node);

  $form['title'] = array(
    '#type' => 'textarea',
    '#title' => check_plain($type->title_label),
    '#rows' => 4,
    '#cols' => 30,
    '#required' => TRUE,
    '#maxlength' => 500,
  );

  return $form;
}

Now, when I'm typing, it shows only 450 characters or less. Why it happens?

The title column of the {node} table is limited to 255 characters. Just because you change it in the UI doesn't mean that it can be saved like that in the database, unless you mess around with the database schema manually (and you should not do that).

I am not sure why that module is exposing itself as a node type, sounds rather strange to me. The only reason I can imagine is being able to rely on the node access system. But nodes are a rather heavy thing, there is a lot of overhead that seems unecessary to me for this use case.


Setting up Pressflow 6 with Vagrant VM Has anyone managed to get Pressflow built into a Vagrant box? I'm new to vagrant and am completely failing at this. Have looked into both Puppet and Chef to configure it (either would be fine) and can't seem to find a recipe that does the trick.

This example.make file seems to describe a way to do this with Puppet, but then I have the added complexity of putting Drush on the vagrant box and I'm not really even sure what to do with the ".make" file.

Any pointers are appreciated - thanks!

EDIT:

Here's the state of my Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant::Config.run do |config|

 # Every Vagrant virtual environment requires a box to build off of.
 config.vm.box = "quetzal64"

 # Boot with a GUI so you can see the screen. (Default is headless)
 # config.vm.boot_mode = :gui

 # Forward a port from the guest to the host, which allows for outside
 # computers to access the VM, whereas host only networking does not.
 config.vm.forward_port 80, 8080
 config.vm.forward_port 3036, 3037

 # somehow specify to use drush, puppet, and the example.make file?

end

and example.make:

; Core version
; ------------
core = 6.x

; API version
; ------------
api = 2

; Core project
; ------------
; Use Pressflow instead of Drupal core:
projects[pressflow][type] = "core"
projects[pressflow][download][type] = "file"
projects[pressflow][download][url] = "http://launchpad.net/pressflow/6.x/6.15.73/+download/pressflow-6.15.73.tar.gz"

After trying quite a few things, we ended up putting together a shell script to do the provisioning. Most of it is specific to our application, but here are the relevant excerpts for anyone who might want to try this:

(there is probably some configuration necessary that this script omits)

#!/bin/sh

cd ~

echo "Beginning fresh install..."
sudo apt-get update

echo "Installing base utilities..."
sudo apt-get -qq -y install zip unzip

# Install LAMP stack
echo "Installing LAMP stack..."
sudo apt-get -qq -y install tasksel && sudo tasksel install lamp-server
sudo apt-get -qq -y install php5-gd php-pear php5-xdebug php5-dev php5-curl
sudo a2enmod rewrite # Enable apache rewrite module

# Install pressflow if necessary
echo "Downloading and installing pressflow..."
wget -qNO /tmp/pressflow.tar.gz https://github.com/pressflow/6/archive/pressflow-6.26.109.tar.gz
sudo rm -rf /tmp/pressflow && mkdir /tmp/pressflow
tar -xzf /tmp/pressflow.tar.gz -C /tmp/pressflow
sudo rm -rf /tmp/pressflow/6-pressflow-6.26.109/sites/all
rsync -a /tmp/pressflow/6-pressflow-6.26.109/* ~/yoursitepath # !! Your Drupal directory here.
sudo rm -rf /tmp/pressflow /tmp/pressflow.tar.gz

# Update php.ini
echo "Updating PHP config options..."
PHPINILOC="/etc/php5/apache2/php.ini"
sudo sed -i 's/memory_limit = 128M/memory_limit = 1024M/g' $PHPINILOC
sudo sed -i '/error_reporting = E_ALL.*/c\error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT' $PHPINILOC

# Create database schemas
echo "Creating databases..."
mysql -uroot -e"CREATE DATABASE IF NOT EXISTS ourfa5_drupal; CREATE DATABASE IF NOT EXISTS stats;"

# Here, you'll probably need to download any default tables needed by your
#   application, update /etc/hosts, etc.. This portion of the script is
#   specific to our application so I've left it out.

# Restart apache for good measure
sudo service apache2 restart

sudo apt-get upgrade


How do I output a hidden password field as part of Drupal form? I want to alter an existing Drupal form built with form API to contain a hidden password field.  (I.e. I want to create a honeypot field in the form that only 'bots will see and fill in, while humans will leave this field it empty).

The HTML I want included in the form shall be something like this:

<input type="password" name="password" style="display:none;" />

I've looked  at hook_FORM_ID_alter, but so far I haven't seen how it can help me with this.

I think I am looking for a way to theme this particular field, some way to manipulate the HTML after it has been rendered, but before it shown to the human (or 'bot), but I am open for other answers as well.

(For what it is worth: I am using Drupal 7.)

If you don't want Honeypot module as mentioned by Jimajamma, you can do it with Form API #attributes all right:

$form['pass'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#maxlength' => 64,
  '#size' => 15,
  '#attributes' = array('style' => array('display:none;'));
);

Of course it's easy to catch display:none in bot's code. It's also common and not so much harder to find out that class applied is styled with it in CSS. There are two methods that are not yet so easy to catch:

Using box model and overflow to make element hidden under other HTML boxes.
JavaScript code to move it out of sight or apply display: none to it

In both cases you shouldn't use obvious identifiers in html, like .honeypot or .hidden, as this will be probably easily found by the bot, too. Also, z-index usually isn't the way to go, as it tells bot "this element is under other one", or "this element is over other one, hides something".


Alert a message after ajax callback I would like to implement something like the second example in this link but not when the form is submitted, actually when a radio button is clicked. (click to alert) http://d7.drupalexamples.info/examples/ajax_example/advanced_commands. With the code below i managed to alert the message but after that the form does not work properly, after the submit it redirects me to $base_url/system/ajax and a json array is displayed.

$form['submitted']['test']['#ajax'] = array
        (
           'callback' => '_test',
           'wrapper' => 'nimportequi',
           'progress' => array('type' => 'throbber', 'message' => '')
        );

and the callback:

function _test($form, $form_state){
    $commands = array();
     $text = "";
     $alert = 0;
     if (valid_email_address($form['submitted']['email']['#value']) !== FALSE)
     {
        $result = user_load_by_mail($form['submitted']['email']['#value']);
        $text = ($result !== FALSE)?$alert=1:"Based on your email, you are not a member yet!";
     }
     else
        $text = "Based on your email, you are not a member!";
     if ($alert != 1 && $form_state['values']['submitted']['member'] == 1)
     {
        $commands[]=ajax_command_alert($text);
       // $commands[] = ajax_command_data("#foo", 'label_radio', '1');
     }
     $form_state['rebuild'] == TRUE;
     return array('#type' => 'ajax', '#commands' => $commands);
}

Also i am using a rule when the form is submitted. What am i doing wrong ? I cannot figure it out…

Add the ajax callback in the submit button of the form like this:

Edit

$form['radio_buttons']['#ajax'] = array (
  'callback' => '_test',
  'wrapper' => 'nimportequi',
  'event' => 'change',
  'progress' => array('type' => 'throbber', 'message' => ''),
);

This will ensure that when a radio button is clicked your ajax callback will be executed. Selecting radio buttons will give alert message, therefore the ajax callback should be applied to radio buttons.

Your ajax callback seems ok.


Custom module's output is not wrapped in the site theme I've put together my first Drupal 7 custom module. I've implemented hook_menu() to get it to path correctly, but I cannot seem to get the output wrapped in the page tpl.

I can visit domain.com/mycustommodule to see the output, but it's just the photos and links that the custom module built, not the site wrapper. How do I get this output into the node area of the page?

Here's my hook_menu if that helps.

function mymodule_menu() {

$items = array();
$items['mymodule/view'] = array(
'title' => 'Mymodule',
'page callback' => 'mymodule_display',
'access callback' => 'user_access',
'access arguments' => array('Access administration menu'),
'weight' => 1,
'type' => MENU_CALLBACK,
);
return $items;
}

What would help is the code for the mymodule_display() function. However, it sounds like you are printing the output in the function instead of returning it.

Blank page:

/**
 * Creates a blank page with only the module output.
 */
function mymodule_display() {
  print 'Module content';
}

Themed page:

/**
 * Output the content in the main content area of active theme.
 */
function mymodule_display() {
  return 'Module content';
}


how to add "access callback" function to a path defined by a view? I'm using Drupal 7, Views 3, and hook_menu_alter

function MYMODULE_menu_alter(&$items){
  $items['client/place/%'] = array(
    'access callback' => 'custom_function',
  );
}

to override the view visibility (access), also flushing caches, but this doesn't seems to work, can somebody give some light about how to solve this, is this the right way to override path defined by a view ?

thanks in advance

Reminder: Views module allows you to set the access from Views UI

If you want to create your own logic; this is how your code should look like:

function MYMODULE_menu_alter(&$items){
  $items['client/place/%']['access callback'] = 'MYMODULE_custom_callback';
}

function MYMODULE_custom_callback(){
  $isValid = false;

  /* your logic */

  return $isValid;
}

Make sure your module is called after the Views module. Usually Views module wight is 10; so your module wight should be 11 or more.

Also, don't forget to clear your cache.


Append current query string to private file urls? If I use template_preprocess_file_link, can I add the current url query string and append it to the link per user? Will this link be cached for all users?

Update:

This appends it, but does seem to get cached:

  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }
  }

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));

Adding this cache context seemed to do it (although I do not know if this is bulletproof):

  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }

    $variables['#cache']['contexts'][] = 'url.query_args';
  }


User Fields pending Admin Approval? I'm putting together a public facing site with not always mature users, and I'm wondering if there is an off the shelf module for requiring admin approval to user field submissions/changes?

I.e. so that one of our staff get a notification when a user updates some selected settings (My Biography, that kind of thing) and it sits, pending review, before it goes public?

I'm trying to avoid the inevitable genital-graffiti that I know this lot are very capable of...

I set up a workflow for doing this using field permissions, rules, and revisioning.  It works at the node level rather than the field level though, and it's rather complicated to set up.  In my searching there was no single module able to handle this.

Basically, I used rules to create a workflow in which users can only create and edit certain content types, all of which are subject to approval either upon creation or edit (using revisioning).


EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() I am creating nodes programmatically. I Have written following code,

$e = entity_create('node', array('type' => 'some_node'));
// Specify the author.
$e->uid = 1;
// Create a Entity Wrapper of that new Entity.
$entity = entity_metadata_wrapper('node', $e);

// Specify the title.
$entity->title = 'Some Title';
$entity->body = 'abc';
$entity->save();

On giving value to body i am getting following error. Commenting body it works fine

  EntityMetadataWrapperException: Invalid data value given. Be sure it
  matches the required data type and format. in
  EntityMetadataWrapper->set()

What is causing this error and how can I fix it?

Body is a Field API field and not a native PHP variable, therefore you cannot assign values to it like that. Instead, you would need to pass an array with the following keys:

$entity->body->set(array(
  'value' => 'This is the body',
  'summary' => 'This is the summary',
  'format' => 'full_html',
));

If you wish to set the value for a specific language, you call prior to set:

$entity->language(LANGUAGE_NONE); // or 'en' or whatever

More on wrappers: https://drupal.org/node/1021556


How can I echo a views object ($data->nid) into javascript? I need to echo out a few different variables in an onclick event for Google analytics.

I figured this would work but the specific $data objects aren't echoing out.  The variable_get does, however.

<?php
  echo "<script>jQuery(document).ready(function($) {
 _gaq.push([ '_trackEvent', 'my_category', 'my_action', '". variable_get('4_measly_letters', 'AAAA') ."|".$data->nid ."|".$data->node_data_field_i."']);
  });
 </script>";
?>

If I understand well your case, you can test if $data indeed is loading your desired data. you can do this with <?php print_r($data); ?> (or if you use Devel module, is best use <?php dsm($data); ?>). if you see the list of values, you also will see the respective keys's names of each value.

If you do not see values, you can load the respective node informatation with $data = <?php node_load($IdNode) ?> where $IdNode is the ID of your node. Remember <?php dsm($data); ?> to see the data of your node.


Drupal Commerce: Number of a sales per product How can I find the number of sales for a particular product in Drupal commerce?

With this view I solved: https://www.drupal.org/node/1292104#comment-8524109
Just import it and play around for get what you want.


How can I create menu links to external URLs? With my module MYMODULE I would like to create external link and place it into main menu.
Is it possible to do that in MYMODULE.links.menu.yml file or MYMODULE.routing.yml?

Something like this???

mymodule.links.menu.yml

mymodule.googlecom:
  title: 'Google'
  route_name: 'googlecom'
  menu_name: main

mymodule.routing.yml

googlecom:
  path: 'http://google.com/'

mymodule.menu_external_link:
  title: 'External link'
  url: 'https://www.drupal.org'
  menu_name: main
  weight: 10
  options:
    attributes:
      target: _blank
      class: my-class


Access denied messaging and behavior Currently my users are being redirected to a node after trying to first access that node's comment page (comment/reply/nid) via a link in a view.  This is because I've set it so you have to be logged in to leave a comment.  In the message area, on the node that they are redirected to, is an error message, "Error message: You are not authorized to post comments."

I want to change this so that when an anonymous user accesses the comment/reply/nid she is presented with a login page and then directed back to the comment/reply/nid.

I've tried logintoboggin, but that doesn't seem to work.  This is possibly because an access denied message is being displayed, not a 403.

I have a view that displays links to comment on various nodes, and I tried altering the links in this view via hook_views_pre_render.  I was going to try and add a modal window containing a login form if the user was anonymous by taking a more html and js approach a la Twitter Bootstrap.  But I was unable to locate the link in the massive view array.  I was hoping for a render array to modify (add a class, add an attribute, etc).  Not even sure if this would be a "Drupal kosher" approach.

Any ideas?

You can do it in hook_views_pre_render() like this:

/**
 * Implements hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME') {
    if (!user_is_logged_in() && !empty($view->field['FIELDNAME']->options['alter']['path'])) {
      $view->field['FIELDNAME']->options['alter']['path'] = 'user/login?destination=' . $view->field['FIELDNAME']->options['alter']['path'];
    }
  }
}

Where in this case I would say 'title' is your FIELDNAME.

This will, if the user is logged out, replace whatever you have for your link in the rewrite settings, with a link to the login page, with your original path as the query destination, which will be used to return you to that page after the login form is submitted.

Also, there is the modal_forms module, which might be worth trying for a pop-up solution.  However then you need to take them to the comment reply page after the modal form closes.


Why taxonomy term view is showing only a single content? I'm working on customizing some templates on an existing Drupal 8 site. I was about to start working on the taxonomy term page but noticed only a single content is showing in it. I already checked and there are several contents associated with the taxonomy I'm testing.
It's not the pager settings, which could be limiting the results to 1. Neither the filter apparently, I've disabled all filter and sort criteria.
Another thing I tried was clearing the cache. I even disabled the cache for this view, completely.
Finally, it seems the theme has no custom hook that could be changing this view in some way.
Here are the settings I currently have for this view:

What else could I check in order to show the correct results?

After following @ShawnConn's advice on enabling the Show the SQL query option, I figured out what happened.
The query was indeed returning only one result. But then I remembered the categories were recently changed right on the database. To do that, we've updated the respective field table -- node__field_categories in our case. However, the taxonomy_index table was not updated. I went ahead and manually (again, I know) updated the taxonomy_index table and now the view is showing the expected content. I hope this is the last and only side effect.
The lesson learned is: only touch the database if you really know what you're doing. And even then, think twice. :P


How do I enable authenticated users to be able to add ubercart products? I’m new to drupal, so I apologize if my questions are too basic

Any help would be appreciated

I’m using drupal 7 with Ubercart version 7.x-3.8

With Ubercart Auction module version 7.x-1.x-dev

I’m trying to create a car auctioning website, where users can place a car up for auction and other users can bid on it.

How do I enable authenticated users to be able to add ubercart products?

Ubercart products are nodes, so access is controlled in the normal way:

Visit the permissions page, and assign whatever roles make sense to the "create", "edit", etc permissions for the relevant product content type.


limit custom html.tpl.php to exact page, not subpages, drupal 7 I have a custom tpl page intended for a specific page like so:

html--something--anotherthing.tpl.php

This allows some custom handling on the page /something/anotherthing as desired. Unfortunately it is also being applied to sub pages like /something/anotherthing/details where the custom handling is not desired. Is there a syntax for naming tpl files so that it only applies to the desired page?

edit: I've enabled theme_debug and it suggests exactly what I already have for the filename so not helpful.

If it's just one page you can just use something like node--nid.tpl.php
 or page--node--nid.tpl.php right? (Assume that /something/anotherthing and /something/anotherthing/details are two difference nodes)


Menu creation problem I am trying to create a new menu link. But the system doesn't allow me to do so.

The path 'New' is either invalid or you do not have access to it.
The path 'testss' is either invalid or you do not have access to it.

A Drupal menu item can point to external URLs, URLs to files in the filesystem or an internal path. The latter has to exist before creating the menu item and access permissions are needed for the user creating it.

A path can point to a node or any other entity, or any path provided by a module (e.g a view from the Views module). Virtually any path can have any number of aliases but it's worth using the path in the menu items as aliases may change throughout the lifetime of the site, paths are less likely to change.


User can't access own private files via Views I've set up a private directory sites/default/files/private and use it for a file field.

As an admin, everything works as expected when uploading and viewing a private file.

As a user who uploads a private file, I can only download own private files with the Views formatter Download link (example.com/file/585/download?token=TcBjzT2I), but not view them via Generic file (example.com/system/files/private/mypic.jpg) or other formatters. When using the latter, I get

"Access Denied
You are not authorized to access this page."

Permission "View own private files" for role enabled. Even enabling "View private files" has no effect.

What am I missing?

Files in the private directory are not accessible directly through the web server;

You may have to use file_create_url or hook_file_download to access the files under private directory.

For More info on Accessing Private Files check here


Is the Admin role different than a role with all permissions enabled? Is the default Admin role inherently different than other roles? Does Drupal extend privileges to the Admin role that are not configurable/available to other roles?

To be clear, I am not referring to user/1 on the site, but rather the official Administrator role as has been assigned here: admin/config/people/accounts.

Here's why I'm asking:

I've been having trouble with a Data Export View where a non-Admin user runs the export and the resulting output is incomplete. When running the export logged in as an Admin, the resulting output is complete.

I spent some time futzing with the permissions of the non-Admin role with no good results. So, as an experiment, I made a new role and enabled every permission… which, presumable would make this role equivalent to the Admin role. I logged in as a user with that new role, ran the data export, and still got the same incomplete dataset. What gives?

As a bonus question: any idea why is my Data Export view outputting incomplete data for the non-Admin roles?

Yes, the user 1 is different in Drupal:

  The Drupal account created during installation (i.e. with user ID or
  UID=1) behaves differently from others. Primarily, it can bypass all
  access callbacks: it has permission to do everything by default.
  Failing to secure this account could result in potential security
  risks. Treat the UID=1 account as you would with root on Linux
  systems.

Source: https://www.drupal.org/node/947312


How can I tell to the rule I am writing that the value of region field is the value coming from webform data? I successfully created a webform using the Webform module.

Using Webform Rules I can create a new entity of type user and I fill the requested fields using, for example, [data:name-value-raw] for name, [data:surname-value-raw] for surname, etc...

This is very easy for text fields but I have troubles with text list fields, in my custom user fields I have two text-list fields (region list and country list), I set the same list in the webform.

In the Rules Action "Create a new entity" the Rules UI tells me to set a value for these fields but I'm forced to choose from a value in the list.

If I Switch to data selection I can't find submitted values, so how can I tell to the rule I am writing that the value of region field is the value coming from Webform data?

If I switch to data selection I can't find submitted values, so how can I tell to the rule I am writing that the value of region field is the value coming from webform data?

You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable (call it whatever you want), with a value assigned to it equal to your [data:ComponentFieldName-value-raw] (with a data type which equals the data type of your Webform component), and with ComponentFieldName whatever you're using for that region field in your Webform).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).


Image Upload Issues Same Image Different File Name Always Receive This Error We are currently working on fine tuning and updating the dev backend of our CMS we're rolling out for a new site.

I was familiarizing myself with the new system and uploaded some images in error.
I then deleted said images using module Reports > Audit Files > Managed not Used.
Once I removed the file another user tried to upload the same file with a different name and we keep getting this error.
We've removed the file from the Database and the  file server but still get the below error every time.

New to Drupal 8 and this forum... If you have solution or work around please let me know.

You may have the File Hash module installed, and the Optional duplicate file protection feature enabled. That configuration would result in exactly the error message you're seeing, but obviously you may have custom code that does this instead.

If you are using File Hash, and don't want that functionality, you can either disable it at /admin/config/media/filehash, or uninstall the module entirely.


On the user edit page, how can I show the "Help text" for my fields after the "Label" and before the selection widget? I have a field on the user edit page that looks like this:

Label: What kind of fruits do you like?

(checkbox) Apples
(checkbox) Bananas
(checkbox) Grapes
(checkbox) Oranges
(checkbox) Pears

Description: Check all that apply.

The actual list of checkboxes is quite long (20 or so items) and so I would like to put the description after the label and before the checkboxes-- preferably for all fields displayed using the checkbox widget provided by the select (or other) module.

How can I adjust where the description is displayed?

Install the theme developer module and point to your widget. It will tell you which hooks and templates are rendering it and what functions/templates you can use to override this functionality.

Often I find myself first copying the default code to the custom function/template and then twicking it to my needs.


How to merge 2 date fields I am working on a D8 instance and i would like to have 2 dates which are in different fields to be displayed at once when the month is the same i.e. :
21-22 december instead of 21 december 22 december.

What is the best way to do that ?

This isn't a direct answer to your question, but is probably the best option to move forward.

Drupal 8.2.0 (due 2016/10/05) will include the new datetime_range module, which provides date ranges in a single field.

I would wait until this is available, and then migrate your two datetime fields into a single daterange fields (one to the start value and the other to the end value).

Then, I would make a custom formatter for daterange fields that implements your logic to combine month/year when they are the same for start and end.

You can then configure your various vide modes to use this new formatter.


Search results for URL or Views Titles I have pages generated by Views with some page url: e.g. /testimonials.
When I search the word 'testimonials' I want in results page to be shown the link to testimonials page.

How it can be done this feature?

I use Drupal 7.

It sounds like you're wanting to index a Views page in the search result. There's similar question been asked already if that's the case. A solution wasn't marked but the search by page module was mentioned. It has a submodule that allows you to index any arbitrary path on your site.


How to restrict a field choice allowing only one to be populated? On a basic page I have two similar fields. One for an image and the other for a video.

Either can be populated, but preferably not both, as I don't not want two fields to be displayed on the front end. I also want consistency across multiple view modes with only one being displayed in teasers etc

This trouble is, some editors do not appreciate the reasons and populate both fields, so I need to method for limiting this.

With D7 I found a good solution by using Conditional Fields module. By using a select list (for the file type). the corresponding field input would be exposed in the admin and the same field would be displayed on the frontend. Even if both fields were populated, only the current selection would display.

The D8 version of conditional_fields does not yet have this functionality, and may not get it. See my issue

I am therefore looking for an alternative method and hoped one of the experts here might some suggestions. I am looking for something simple and could not consider anything unsuitable for an untrained editor.

A bit confusing because it is rare for me to attempt any coding.

For this example I will pretend the content type is "Article".

First go to manage fields, and add a new field of list (text) to your content type. Let's say the possible values are "video" and "image". So For allowed values list, put

image|image
video|video

In /themes/your_theme_name/your_theme_name.theme add the following

/**
 * Implements hook_form_FORM_ID_alter().
 */
function your_theme_name_form_node_article_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  $form['field_image']['#states'] = [
    'visible' => [
      'select[name="field_select"]' => ['value' => 'image']
    ]
  ];
  $form['field_video']['#states'] = [
     'visible' => [
       'select[name="field_select"]' => ['value' => 'video']
    ]
  ];
}

Replace your_theme_name with your actual theme name.
Replace article with your actual content type name.
Replace field_select with the machine name of your select field.
Replace field_image with the machine name of your image field.
Replace field_video with the machine name of your video field.

Lastly, clear and flush all cache to see changes.

Source: Drupal 8 - Conditionally hide a form field


Display all dates for a multi-day "event" I have an "event" content type that can have multiple dates or repeating dates. Up until last week the node view of a repeating event would display all the dates for the event.

  Repeats every week every Friday until Fri Apr 27 2018.
  Friday, April 6, 2018 - 10:00am to 11:00am
  Friday, April 13, 2018 - 10:00am to 11:00am
  Friday, April 20, 2018 - 10:00am to 11:00am
  Friday, April 27, 2018 - 10:00am to 11:00am

Now it only displays the first date.

  Repeats every week every Friday until Fri Apr 27 2018.
  Friday, April 6, 2018 - 10:00am to 11:00am

I don't know what change I made that caused this. I checked the date field settings and the field display settings against a recent backup, and everything is the same.

Do you have any idea?

EDIT: It's not a display issue, it's a data issue. Via node_load() I can see that only the first data is written to the database:

'field_reserved_time' => array(
    'und' => array(
      array(
        'value' => '2018-04-05 19:30:00',
        'value2' => '2018-04-05 20:30:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;UNTIL=20180427T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
    ),
  ),

While previously it would write all dates to the db:

'field_reserved_time' => array(
    'und' => array(
      array(
        'value' => '2018-04-06 17:00:00',
        'value2' => '2018-04-06 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-13 17:00:00',
        'value2' => '2018-04-13 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-20 17:00:00',
        'value2' => '2018-04-20 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-27 17:00:00',
        'value2' => '2018-04-27 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
    ),
  ),

You have removed the repeat date option for date field. Please check your content type, for repeat date you must have to enable repeat option of date field.


No layout and menu not working I installed latest version of Drupal 8.1.3 on my site.
Everything went fine and no error message.
But after installation done, my homepage became this.
No layout, menu not working.

How can I fix this?

Check that the sites/default/files directory and any directory inside that are writeable from the account used to run Apache. After that, force Drupal to clear its cache.
It happened to me too, and all the times it was because Drupal was not able to write the files it uses for rendering the page in that directory.


Workflow for an entity based menu system? I've been considering stopping to use the menu system all together, in favor of taxonomy terms, or other entities. Entities are superior to regular menu-entries in many ways because they integrate well with most other Core systems as well as contrib.

Since vocabularies already have the ability to create a hierachical structure, taxonomy terms seems to be the ideal candidate here.

The question is, how have you attempted to implement this, and how did it work out? Are there any pitfalls that one should be aware of before trying this, or any limitations that limit the usability of this approach?

I have pretty much abandoned the menu system for most of my sites, or at least the main menu, in favor of Taxonomy Menu. Here is a link to my most recent site that takes advantage of Taxonomy Menu

buyagainbaby.com

The main menu there as well as all the blocks you see on the front page are done with taxonomy menu.

The types of sites I design usually categorize some type of product or other information, and it's easy to use views to do some pretty amazing things with taxonomy as arguments, which you cannot do with just the default menu terms or IDs alone.  Take a look at some of my other questions having to do with taxonomy menu, or ask any questions about implementation if you have any.


JavasScript from custom module not detected I have created a custom module, which is working. Except the JavaScript, which is not being detected. I have been following the description at https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview and I have checked other modules.

What have I done to implement JavaScript? I have created a file with the following JavaScript content (location: MODULE-ROOT/js/info.js):

/**
 * @file
 * Info behaviors on node edit form.
 */

(function ($, window) {

  'use strict';

  Drupal.behaviors.nodeEditForm = {
    attach: function () {
      console.log('Hi there!');
    }
  };

})(jQuery, window);

Then I have added the following content into my MODULE-NAME.libraries.yml file:

nodeEditForm:
  version: 'VERSION'
  js:
    js/info.js: {}

I expect to see "Hi there!" in my webdeveloper tools inside Google Chrome browser, after I flush the entire Drupal 8 and browser cache. I do not get any output there.

Is it a "must" to attach the JavaScript to any existing behavior? If so: how can I learn which behavior is tied to an node edit form?

Thanks for your attention.

Drupal uses a high-level principle: assets (CSS or JS) are still only
  loaded if you tell Drupal it should load them. Drupal does not load
  all assets (CSS/JS) on all pages, because this is bad for front-end
  performance.

You need to inform Drupal to attach your library to the page.

In your case, you can use hook_form_alter and check the $form_id or hook_form_FORM_ID_alter for a single case and add this:

$form['#attached']['library'][] = 'mymodule/nodeEditForm';

Then clear the cache. Search the core folder for $form['#attached'] for more examples. You should then see your js file listed in the source of the page as well as console log output.


Checking for changed fields - Identifying an empty array & Field Type This is probably a simple question, but I am not finding it right away. I have a mostly working function to check for changed fields in a form. Here is the snippet checking for change:

// Check the number of values for each field, or if they are populated at all.
$old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
$new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

The problem I am a having is when I submit the form, empty text fields always respond as changed. The $old_field_count is not set, so comes up as 0. The $new_field_count is 1, because for some reason it is an empty array.

old count 0
new count 1 ... (Array, 1 element)
    0 (Array, 1 element)
        value (String, 0 characters )

There has to be an easy way to say "If ($new_field_count = "An empty Array") {$new_field_count = 0;}"

Edit: I found my answer in part. I tried If (empty($new_field_count[0])) {$new_field_count = 0;} but that just breaks any empty field that isn't a text field. So now I am thinking I have to additionally identify if it is a text field.

Thanks, I've got it!

// Check the number of values for each field, or if they are populated at all.
$old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
$new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

If (empty($new_field[LANGUAGE_NONE][0]['value'] && ($field_info[type] == 'text' || $field_info[type] == 'text_long')) {
    $new_field_count = 0;
}

if ($old_field_count != $new_field_count) {
  // The two versions have a different number of values. Something has changed.
  $fields_changed[] = $field_name;
}


Including static pages in the search index? I've got a page set up like this:

$items['mypage'] = array(
  'title' => 'My Page',
  'page callback' => 'mymodule_mypage',
  'access callback' => TRUE,
);

and then

function mymodule_mypage() {
    return 'This is a test! Also, pollywog.';
}

Now, if I go to /search/node/pollywog, I would like to see the above page as one of the search results. I currently don't, because I assume search just covers database content. Is there a way to make it also include specific pages? Something like the below would be amazing:

$items['mypage'] = array(
  'title' => 'My Page',
  'page callback' => 'mymodule_mypage',
  'access callback' => TRUE,
  'includeInSearchIndex' => TRUE, // <<----- this!!
);

Would it be possible to build in something like "includeInSearchIndex" and then make that index the static page?

Your module needs to implement hook_search_info, hook_update_search and as part of that hook call search_index and then fully define how the content is indexed.

Out of interest why don't you just create static pages as regular nodes?


storing value in session with ctools wizard I have created a multi-step form using Ctools wizard and its working fine.

In multi step form, there is only images, so user will select the image and click on "Continue" button for next step. In the final step, I am showing the result of merged images which are selected in all previous step.

Images are rendering as ajax link in each step and when user click on any image, an ajax callback be executed.

In each step form load and ajax callback, fid of the images be stored in $_SESSION variable.

But the problem is that $_SESSION are not updating on the ajax call.

Suppose, there are five images in step 1 in the Ctools multi step form. When step 1 load, I am storing fid of first image into $_SESSION variable and If user click on any images, I am updating the fid in $_SESSION variable.

But, if I check print_r($_SESSION) in next step, its not showing the updated fid. Its only showing fid of the first image in previous step.

If I check ajax callback in fire bug console, its showing correct value of fid and $_SESSION variable.

Please suggest me what I am doing wrong.

Thanks in advance.

you cannot use form_state. every step will have it's own.
cache the date with ctools_object_cache_set


Migration Multisite D7 to Single D8 I have several D7 sites that I inherited that should have been one site.  We are now trying to migrate to D8 (not all needed modules are available yet on D9).  We would like to migrate them to one site.
When I migrate site 1 nodes and/or webforms/submissions, all goes well.  When I migrate site 2, some of site one items are overwritten because they have the same ids.  How do I configure a migration so it does not overwrite a previous migration?

There is more than one way to migrate Drupal content. Usually if you assign a migration from a database into a different database the assumption is that it's about migrating content into a new structure, without any additional content considerations.
As mentioned in the comment you should export/import the second site content rather than migrate.
You can look into Feeds module to import from a CSV, for example, and you can use Views to create a list of your content then export it into a CSV file. This isn't the only way to go about it, just one suggestion. Try to research the export/import ways of content in Drupal ;)


Drupal 7: entity field as single/multivalued based on content type I have a 'gender' entity(taxonomy) field.

I want to use it as single valued for content type X and multi-valued for content type Z in Drupal 7?

Is there any other work around to achieve this functionality?

Shortly, no.

Take a look at project Field instance cardinality and an issue #1029298.

  This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.

Theoretically, you can create field as multi-valued and limit cardinality for content type X programmatically.


Custom view for Entityform submission I have a simple Entityform where the user selects from a list of Profile2 user profiles (internal staff and external staff). In simpler terms, the user selects from a list of entities (ie. pick 3 from a list of 10).

The Profile2 user profiles are being shown on the form via an Entity reference view so you can see the name (from user profile), picture (from user profile), status (from Profile2 staff profile) etc. associated with the selected users.

Unfortunately, the submission confirmation and submission screens only show the entity name (User Profile) instead of the actual user profile details. Basically I see:

Submitted by There, Hello on Thu, 03/05/2015 - 10:53
Person Selection
External Staff
Internal Staff

What I want to show is:

(picture) Joe Schmoe, Washington
(picture) Alex Trebec, Montreal

Does anyone know how to alter the confirmation and submission pages to show more detail about the underlying Entity (and/or associated Entity)?

Here is what I would suggest.

Clone the built in View
In the Entityform Type edit form select your new View under Submission Views -> View for submissions reports
In your new View add relationship to Profile2 entity via the Entity Reference field on the Entityform
Now you can add any field from the Profile2 to the View.


DrupalChat module polling method I am using drupalchat module for my website. And I wanted to check which polling method is best - "Normal AJAX" or "Long Polling". Actually We are facing performance issue. Currently we are using "Normal AJAX" as polling method.
Can somebody suggest which polling method we should use and why?

I had a experience about that, when using Ajax each short time each user and all of open each pages has requested to server ( if you look at firebug console you see what I mean ), another method is Long Polling method that also it is not the best way ( although it is better than Ajax method if very quick response time is not important for you), In Both cause heavy load on server (especially memory exhausted).ajax and polling is old method to interactive real time applications like chat
I strongly recommend you using Nodejs method, Nodejs is very good for realtime chat system

So use  Drupalchat nodejs integration solution

  f you use node.js as backend in this module, then it will be highly
  scalable. There are two ways to use this backend:

 First way is to setup your own node.js server and install Nodejs Integration module. This is currently under development.
If you don't want to or can't setup your own node.js server, then you can checkout our ready to use node.js server. If you opt for this

  method, then there is no need to install any additional
  software/package on your web server. To do so, please visit us at
  https://iflychat.com.

another solution is using nodejs_chat drupal module ( in both solution you require nodejs on yourserver).


how to resend email to new created user with wrong email I created a new user, after several hours the email sent by the system was undelivered because the email was not correct.

After changing the email with the correct email, how can I resend the email? I could not find this.

_user_mail_notify() is the underlying Drupal function that does the work of sending out a user account creation email. You can reference the API doc link on how it's used, then call the function in the appropriate code context (e.g. menu callback, submission function, drush eval, etc.) for your situation.


error Refused to execute script, because its MIME type ('text/html') is not executable When migrated my site from localhost to webserver. I see an error in chromeconsole. I used git clone to transfer my site.

  Refused to execute script from http://mydomain because its MIME type
  ('text/html') is not executable, and strict MIME type checking is
  enabled.

Mysite is unformatted.
Theme bartik, core drupal-8.2.5

It's running smooth on localhost.

I contacted serversupport, they say it's a debug problem and not a server problem.

there is an refer in the stylesheet to ojqe8x, but is empty, how to solve this?

<title>mysite | mysite</title>
<link rel="stylesheet" href="/joehoe/mysite/?ojqe8x" media="all" />

Edit:

on this domain http://pcwebber.nl/alex/lkch/

I get this error Refused to execute script from 'http://pcwebber.nl/alex/lkch/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

You are asking the wrong question....

When you look at your page's source code, you'll see this:

<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/sites/default/files/css/css_Z5jMg7P_bjcW9iUzujI7oaechMyxQTUqZhHJ_aYSq04.css?ojqox6" media="print" />

The last one is a real CSS file. The first two are not (those link to your front page). So your browser attempts to load a stylesheet, but is receiving your front page instead. That is what is triggering the error; The browser expects CSS and is instead served HTML.

The real question is, where do these 2 lines come from... And that is hard to tell, since everything in Drupal can do that.

Things you can try;

Disable CSS aggregation in Administration > Configuration > Development (you want to enable this once you go live)
Disable all non core modules (if any)
Try a different theme

It could be something coming from a custom template as well.


How to put select option value into particular category in webform module? I am using webform module and added a select field.

My option values are

  One|Sample 1
  Two|Sample 2
  Three|Sample 3
  Four|Sample 4
  Five|Sample 5
  Six|Sample 6

But I want these three fields in a particular category named Sample list 1

  One|Sample 1
  Two|Sample 2
  Three|Sample 3

Sample List 2:

  Four|Sample 4
  Five|Sample 5
  Six|Sample 6

Note: I don't want to show it in groups <>.

I want a select list which consists of Sample List 1 and Sample List 2
In a single select field I want to store both of option values into their respective select lists.

I think you want to store this a 2 separate fields however present it to the user as 1 field.

One solution would be to use hook_form_alter() to combine the 2 selects into 1, and then put the values back where it should be after the form is submitted.

For this example lets call the first select field A, and the second field B, and the new field that combines both A and B, C.

So - first combine the fields and add an additional submit handler:

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

  if($form_id == 'webform_client_form_<ADD WEBFORM ID HERE>') {

    // Make a new field which will have both options. Base in on the existing
    // field A.
    $form['submitted']['field_c'] = $form['submitted']['field_a'];

    // Combine the options of field A and B for the new field.
    $form['submitted']['field_c']['#options'] = array_merge($form['submitted']['field_a']['#options'], $form['submitted']['field_b']['#options']);

    // Hide field A and field B.
    $form['submitted']['field_a']['#access'] = $form['submitted']['field_b']['#access'] = FALSE;

    // Add an additional submit handler to put the values back where they
    // should be. Add this before the existing submit handler so we can make
    // our changes before anything is saved.
    array_unshift($form['#submit'], 'split_combined_select_values_out');

    // Add a validate function to make sure only 1 option is selected from each category
    $form['#validate'][] = 'combined_select_validate';

  }

}

In the new validation function make sure that only 1 option is selected from each category:

function combined_select_validate($form, &$form_state) {

  $count_a = $count_b = 0;

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $count_a++;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $count_b++;
    }
  }

  if($count_a > 1 || $count_b > 1) {
    form_set_error('submitted][field_c', 'Can only select 1 option from each category');
  }

}

And then in the new submit handler put the values back where they should be:

function split_combined_select_values_out($form, &$form_state) {

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    // Check if the value  selected is from field A or field B
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $form_state['values']['submitted']['field_a'][$val] = $val;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $form_state['values']['submitted']['field_b'][$val] = $val;
    }
  }

  // Unset the value from field C.
  unset($form_state['values']['submitted']['field_c']);

}


Undoing Content Changes Made with Admin Panel I administer an existing site, and accidentally changed some of the formatting on our homepage.  In the past, I have been able to press "back" on my browser to undo changes, but for some reason it's not working this time.  Does anyone know of a way I can "undo" changes I made to the website under the admin panel?

Your ability to undo changes depends on what you changed and how your site was set up. Some components of Drupal can be reverted, like if you have revisions enabled on your nodes. A more advanced set-up may have "Features" which allow you to revert all sorts of things. It really depends.

For most changes you make in the admin panel, you need to find the setting you adjusted and change it back to its original value. It would help if you described your issue in more detail, like what settings were being adjusted and what version of Drupal you were using.


How do I sort the list of modules by the number of open issues? Is there any option to sort the list of modules on drupal.org by the number of issues?

No, there isn't.

The number of issues isn't really relevant because you need to see what type of issues there are (cosmetic / blocking), how actively the module is maintained, how many maintainers, etc.

Big modules can have a lot of issues, but if they are frequently updated it's no problem. If a module has only one (blocking) issue but it isn't resolved due to lack of maintenance than it's worse.


Get the displayed node of a commerce_line_item in a component rule using 'commerce_display_path', doesnt work I ve found something quite interesting in an other post Discount based on a field in product display node in Drupal Commerce?

It describe a way to get the 'node display' associated with a line_item

Build a component rules action set with custom php code in it,
providing a 'node_fecthed' provider variable and then use it with
other rules to do what you need.
The php code use the commerce_display_path backlink exploded url to find the displayed
node, then return it.
The given code is the following :

$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$url = $line_item_wrapper->commerce_display_path->value(); $url_parts = explode('/', $url);
$nid = $url_parts[1];
return array('node_fetched'=> $node);

Just before the return line, i added, regarding to a comment suggestion from the original post, 2 lines :

$node=node_load($nid);
dpm($node);

when rules is run, devel dpm() displays the right associated node as expected.
But when in an other rules i try to display/debug/use the 'node_fetched' it appears to do nothing as if it was set to null.
What may be wrong with that ?
Any suggestions will be appreciated as i'm going mad with that for 2 days.
Thx

In fact returning variables (providers) from a custom php code doesn't work !
If you do it in a module the same code works !
Rules bug ??


How to load login, register and other forms and nodes in modal window? I am seeking a module or technique to show forms (for example login form, register form etc.) and nodes in a modal window/pop up.

I found some modules that promise to do that, but none of them seems good for my use case:

Ajax Login/Register It does not work with programmatically created login link, I followed this post, without any success.
Modal forms (with ctools) Is seeking maintainer, so who knows whether or not development will be continued?
Colorbox Node Cant get it working for login, register pages/forms

What is the best way to have this feature. I would prefer a solution that is easily extendible to load nodes or other entities as well within a modal window.

What is the Drupal 7 way to do that?

No need to write single line of code.

To open node add/edit form in modal window, try below modules

https://www.drupal.org/project/ctools_automodal
https://www.drupal.org/project/ctools_automodal_admin

I tried & it works properly for me.

To open node add form in modal
admin/config/system/ctools_automodal_admin -> Modal content types and select content types.

To open node edit form in modal add
node/%node/edit in Extra modal links textarea.


How to find the name of changed file in Forms API I've a file field attached to a node form. I want to know in the submit handler if the file has been replaced then I'll take some action.

For example I delete the previously uploaded file : abc.txt and then upload a new one "newdoc.txt" in place of it and "Submit".

I don't want to  load the node and read it's contents or use hook_presave and read the value using $node->original.

I have just verified it... Form submit handler does store old values and new values..

In $form you see old fid in #node property , In $form_state['values'] you see new fid that was uploaded...

By comparing above two in your submit handler you can take action..

function my_custom_submit_file_alter_detector($form, &$form_state) {
  dpm($form);
  dpm($form_state);
}


Entity view displays are throwing dependency errors during installation I have a custom entity in my module. During installation I am creating a bundle for this entity. Then in the config I have two entity view displays for this bundle. One of those displays is for the default view mode.

During installation I am getting dependency exception for these two displays. But if I import them manually via config import everything works just fine.

So I have moved these into the optional config for now. This causes another issue and that is the display for default mode for my entity bundle.

When a new bundle is created the display for default mode is automatically created. So since I now have the config as optional it will try to import it afterwards but the display for default mode already exists so it will do nothing. The only solution that comes to mind is putting the config for this display into code bude I'd rather not.

So the solution for the first issue causes the second issue. Therefore how can I fix that dependency issue?

I was thinking about removing the dependency on the bundle form the display config and putting dependency on the display into the bundle config but that would not work since display needs an existing bundle first.

No, removing the dependencies is not the solution.

As I said in my comment, automatically doing something when config is installed or imported is an anti-pattern that should be avoided when possible.

Just create all the config through config/install and don't trigger automatically creating displays through pre/post save hooks/methods and your problems should go away.


site slogan in h6 following h2 site name not matching WCAG 2.0 requirements Configuration : Drupal 7.26 / Omega 3 / Delta module
An accessibility check made with achecker.ca on a website gives me one result :

  Success Criteria 2.4.6 Headings and Labels (AA)

  Check 38: Header nesting - header following h2 is incorrect.
  Repair: Modify the header levels so only an h3 or any header less than h3 follows h2.
  Error Line 112, Column 7:

for ...

As I understand, it comes from the file : "sites/all/modules/delta/delta_blocks/includes/delta_blocks.theme.inc" The delta for the site slogan is defined as a h6, which doesn't match with WCAG 2.0 (AA) requirement :

  The header following an h2 is h1, h2 or h3

(http://achecker.ca/checker/suggestion.php?id=38).

So I might need to use a hook to change it, but I am such a newbie with hooks. I found this : https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_info/7 but it seems to hook the core module. Not very sure I want to do it.

Any help?

Hooks won't help you with this - the markup for the slogan is in the region--branding.tpl.php template file:

<h6 class="site-slogan<?php print $class; ?>"><?php print $site_slogan; ?>

To fix, you can just create your own region--branding.tpl.php file in your sub-theme, and alter the markup to your needs.