Must an admin theme be enabled to be used? I've created a sub-theme of the admin theme, Seven, in order to override some CSS used to display date combo inputs on a node edit form. The info file lists a new style sheet and the regions that are defined in the original Seven info file.

Everything seems to work fine if I select this sub theme as the Admin without even enabling it. I can easily override the CSS.

However, if I also enable the sub theme, blocks suddenly appear inside the admin theme whenever it's invoked*. I believe this is because the new sub theme has different (default?) settings for active blocks in the block table. (rfay has a solution for this problem here: http://randyfay.com/content/changing-theme-name-or-adding-subtheme-without-losing-block-and-theme-settings)

My question: Is it necessary to enable a theme/sub theme that will only be used as an Admin theme? If so, is there any way to avoid the block problem, or is that just the way it goes?

* Edit: A lot of blocks appear in the new admin theme when it is enabled. Below is a visualization of the blocks table. Before the custom theme is enabled, it does not appear in the block table, so there are no blocks at all. After it is it enabled, the 12 blocks from the main theme ("custom" in the table) are all placed into the content area. Blocks might end up in the Content region because regions in the enabled theme don't exist in the customized seven theme? In any case, it's just a nuisance really, and can be easily fixed using the SQL at the link above. However, if there is no downside in using an admin theme that is not enabled, the block clean up wouldn't be needed.

No, it's not needed to enable theme to use it as an admin theme. You only need to enable it if you want to alter it's settings, both the ones in "appearance" section, and blocks. Just go to http://example.org/admin/structure/block/list/seven and http://example.org/admin/structure/block/list/your-seven-subtheme and set up the blocks the way you want them, that's all.


How can I consolidate the views that are auto generated by nodequeue I'm using the nodequeue module to potentially create a large number of queues. With each new queue I create, a view is auto generated for that queue. Ultimately, I want to be able to access each queue as a view, but I'm wondering two things.

Are there performance implications to have in potentially hundreds of views created?
Isn't there a better way to display nodequeues in a view? why does there have to be a different view for each nodequeue ? isn't there a way to pass the relationship in through a contextual filter?

Are there performance implications to have in potentially hundreds of views created?

Views are just queries. If you're concerned about performance use caching in Views under the advanced settings for each view. There are contrib modules that enable caching for all views.

  Isn't there a better way to display nodequeues in a view? why does there have to be a different view for each nodequeue ? isn't there a way to pass the relationship in through a contextual filter?

Possibly, but then your view(s) would only be accessible from say 1 url via the contextual filter ... a freedom of the Page view provided by the nodequeue is that as a site builder you can define unique url routes per view.


Create a Drupal 7 node by email and populate multiple fields I'm trying to import an email from Salesforce to drive node creation in Drupal 7. I've got mailhandler/feeds set up to do most of the heavy lifting, but the one thing I can seem to figure out is how to populate 4 separate fields in the node from a single email.

I know I can map the subject line as one field and the body as another, but isn't there a simple way to parse the body content into three distinct fields?

You can take a look at Feeds Tamper that allows you to modify data before it gets saved. Then create a custom plugin if needed.


How to avoid sending 2 emails at the same time? I use Drupal 7 and I'm testing a function to automatically send email from a custom module.

I have 3 fields to check, and I have to send mail to a specific address.

I have write simple test code in a custom module:

function test_mail_node_presave($node) {
 if($node->type == 'rso') {
  if ($node->field_a['und'][0]['tid'] == '10'){
   mail('example1@mail.com', 'example2@mail.com', 'example text');
  }
 }
}

It works, but in any verification "field_a" Drupal sends 2 equals email.

Note: I'd also be interested to know about any other technique that can achieve the same result.

You could get pretty close to what you're trying to do by simply (and only) using the Rules module. Some more details about this approach:

Use Rules Event "Before saving content".
Use as many Rules Conditions as needed, for any of your fields you want to validate.
Use Rules Action "**Send Mail".

For more details, Have a look at this rule (in Rules export format):

{ "rules_field_validations_before_saving_nodes" : {
    "LABEL" : "Field validations before saving nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "example1@mail.com, example2@mail.com, example text",
          "subject" : "Subject of eMail triggered via Rules",
          "message" : "Message content of eMail triggered via Rules",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event is "After saving new content", but as a sample I've limited it to content type "article" only (omit or adapt that extra verification as needed).
In my case I have a selection list field with machine name field_optionlist.
This field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to add these Rules Conditions (validations), in the order specified:

a validation to ensure that this rule only applies for nodes that have a field with machine name field_optionlist.
a validation about attempts to save a node where "The selected value" of field_optionlist equals Custom.

If all these Rules Conditions are satisfied, then the Rules Action will send an eMail (feel free to change the eMail subject/body to whatever you want).

If you want, you can use the Rules UI to import the above rule in your own site. But before doing so, make sure you have defined 2 similar fields (with machine names field_optionlist and field_free_format_text). As a variation, adapt the machine names to similar fields you already have (attention about field-optionlist versus field_optionlist though, same for the 2nd field, important!).

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Voilà, the above solution depends on Rules, nothing but Rules ...


How to make address1 field and zip code non required with Address Field module I'm using Address Field module

I want to make it a required field but only the Country and City values. I want to leave the zip code and Address as optional. I don't find a way to configure it like this. Is it possible?

To provide more info, I am using Geocoder to fill a Geofield field. I want it to be able to geolocate with City and Country if only that are provided if also zip code and address are provided use them too.

EDIT: I forgot to mention that if I make the whole Address field non-required works as I want to, but I would like to make Country and City required, another way to look at the problem.

I would use form_alter to hook into the form, identify the form element and unset or make required FALSE

eg:

mymodule_form_alter(&$form, &$form_state, $form_id){

  if($form_id == 'xyz'){
   $form['zipcode']['#required'] = FALSE;
   $form['address']['#required'] = FALSE;
  }

}


Odd behaviour on form validation when in block mode Hi gurus and fellows,

I have to generate an application form, that needs to be displayed both a as "page" (hook_menu) and as "block".

I factorized the form generation within the same function (generate_form). It works fine, except for the validation process. Clearly the validation happens (form is not submitted when it fails), but the form_set_error() is never displayed  in block mode (in page mode, it works fine).

This "lack of display" also happens for regular validation ('#required'=>'true'), so I don't think my custom validation code is at stake :

When in page mode, the required fields get highlighted, the error
message is displayed.
When in block mode, the required fields get highlighted (red-bordered), BUT the error message is NOT displayed.

Of course, I checked that the page.tpl.php, used to display the block, has a 'message' section, within it. Proof is my drupal_set_message() gets displayed on submit.

Oddly enough, when I put a drupal_set_message() within my custom validation function, it gets displayed, as long as (and only when) the validation passes ! Wierd...

I pasted the *.module code here :  http://pastebin.com/cnwzp3UU

Any idea ?

Taking a bit of a stab in the dark here, but I'm suspicious of this comment in your linked code right above hook_block_view():

// used in node--landing-page.tpl.php

That suggests that you're calling this block in directly from a template file, not through the normal block system, which won't work properly.

The problem is that the template files are built too late in the page build, in this case after the system messages have already been taken from the session and cleared out for the next page. So the validation messages do get added to the messages array in the session, but they won't be outputted until the next page is loaded.

I would suggest instead implementing hook_node_view() and adding your block into the content there. That hook is run early enough on in the page build that you won't see the delay with error messages.


Adding items to another Modules Admin form I have a module that I need to add a few items to, I was told that using hook_form_alter was
the best way to do this, but have been completely unable to get anything to work. Maybe some
one could help me out on it a bit....

The PURPOSE of this enhancement is to add text and links to a login modal, but that's unimportant
at the minute.

The code that I have in my module atm is just to show the form I'm trying to alter

<?php
/**
 * Implements hook_menu_alter().
 */

function [modulename]_enhancements_menu_alter(&$items) {
  $form['modal_window'] = array(
    '#type' => 'fieldset',
    '#title' => t('Modal text and links'),
    '#collapsible' => TRUE,
    '#collapsed' => 0,
    '#weight' => -399,
  );

    $form['modal_window']['login'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Login text'),
      '#default_value' => variable_get('[modulename]_login_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui. ]'),
    );

    $form['modal_window']['registration'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Registration text'),
      '#default_value' => variable_get('[modulename]_registration_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui.]'),
    );
}
?>

The module has something like this going on with it
<?php
/**
 * Implements hook_menu().
 */
function [modulename]_menu() {
  $items['admin/config/services/[modulename]'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => '[modulename] Settings',
    'access arguments' => array('administer [modulename]'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('[modulename]_admin_form'),
    'description' => '[modulename] Configuration.',
    'file' => '[modulename].admin.inc',
  );
?>

and here's the [modulename].admin.inc
<?php
/**
 * Form builder for the [modulename] administration form.
 */
function [modulename]_admin_form($form, &$form_state) {
  global $user, $base_path;
  include_once DRUPAL_ROOT . '/' . 'modules/user/user.pages.inc';
  module_load_include('inc', '[modulename]');
  $capabilities = [modulename]_get_capabilities();
  $form = array();

   $form['[modulename]_debug'] = array(
    '#type' => 'checkbox',
    '#title' => t('[modulename] debuging'),
    '#description' => t('Write errors to watchdog'),
    '#default_value'=> variable_get('[modulename]_debug', 0),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => -401,
  );
?>

For the sake of clarity, let's say that your custom module is named CUSTOMMODULE, and the one you want to alter is ALTERTHIS.

You can use hook_form_FORM_ID_alter() like this:

/**
 * Implements hook_form_FORM_ID_alter() for ALTERTHIS_admin_form().
 */
function CUSTOMMODULE_form_ALTERTHIS_admin_form_alter(&$form, &$form_state, $form_id) {
  // Alter the $form here.
}


Passing variables to custom templates In Drupal 7 I have a web site with dozens of custom templates. I used theme() to pass variables to my templates defined in hook_theme() in a page callback defined in hook_menu. How do you do this in Drupal 8? The theme() function is no longer available.

Drupal 8 uses render arrays for the structure, and drupal_render() to render them (as can Drupal 7 for themeing, incidentally).

The examples from the change record are as good as any:

Drupal 7

// Theme a table with header and row data.
$markup = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));

// Render a pager.
$markup = theme('pager');

Drupal 8

// Theme is available as an element type (may have additional processing in rendering).
$table = array(
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array(
    'id' => 'my-module-table',
  ),
);
$markup = drupal_render($table);

// Pager is not an element type, use #theme directly.
$pager = array('#theme' => 'pager');
$markup .= drupal_render($pager);

There's a useful warning too:

  Also note that when preparing output for Twig templates (in preprocess functions) it is preferable to avoid calling drupal_render() whenever possible. The Twig environment in Drupal 8 will automatically render any render arrays printed in the template, allowing for manipulation by later preprocess functions and preventing unnecessary rendering if the variable is never printed in the template.


Encode a line break in an HTML email sent by Rules? I have a rule that sends out an email when a node gets edited in a certain way. The rule fills the body of the email with the value of a <textarea> field from the node that was updated.

The email is being sent out in HTML format (not plain text) and the <textarea> is set to plain text (not Filtered Text).

When the email gets delivered, the HTML line breaks (
) that I've entered into the <textarea> field are not respected (they get encoded); it just one big mass of text with no line breaks.

What do I have to put in the <textarea> field for line breaks to come out in the HTML email?

I've tried:

\n
\r
\r\n
%0D%0A
&#x3C;br /&#x3E;
%3Cbr+%2F%3E

Any HTML I put in the field gets encoded and not processed as HTML. How do I put in
 and have it stay as HTML?

Have a look at my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?". It includes a rule (in export format) which looks like so:

{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Even though your question is not a duplicate of that question, this rule includes a solution which you could also apply in your case:

A Rules Action Add a variable, with machine name variable_for_email_body.
A Rules Action to actually populate the content of this variable_for_email_body (just replace that content to fit your needs, and include whatever HTML tags you want to use in our eMail body).
A Rules Action Send mail, with Message body equal to ... [variable-for-email-body].

Done ...

PS: obviously, this is for D7 ...


Views Contextual filter for matching taxonomy names I have a view of content type slideshow items. Each item has a taxonomy term fromslideshow_category vocabulary. I also have another content type: articles, which has it's own taxonomy article_categories.

I'd like to create a view that will match the names of those taxonomies and display the slideshow items accordingly.

For example on articles taxonomy page news the only slideshow items displayed are those which marked news .

What I'm doing right now:

I have created a contextual filter on the slideshow items view

When is NOT available

Content: field_slideshow_category
Provide Default value > Raw value from URL
Path component > 2
Use Path alias > checked

When IS available

Specify validation criteria > checked
Selected the slideshow_category
Filter value type > Term name converted to Term ID

PROBLEM

This works fine on page like /articles/news/ (using my previous example ), but obviously because I pass RAW value this view also appear on /articles/news/news-item (which is the actual article page). What I need is for this view to show up only on taxonomy pages. Is there a way to limit "Raw value"? should I be using a different "Provide Default value" ?

Thanks in advance :)

Yes try different "Provide default value" for this case "Taxonomy term ID from URL"

When it's available specify "Taxonomy name converted to ID"


Inherit all styles from base theme expect a few I am doing a base theme and child theme. I want the child theme to inherit all the css from the base theme expect a few for which i will have the stylesheet in this child theme. How will i achieve this ?

As noted on the sub-theme page, a sub (or child) theme will inherit all the parent's css files "as long as you declare at least one stylesheet in your sub-theme's .info file".

You can override a stylesheet simply by declaring one of the same name in your sub-theme's .info file. If there is a stylesheet you don't want in your sub-theme, just add an empty file with same name to the sub-theme's .info file.


How to change slider widget price range text and "Go" label in KickStart Commerce? How to change slider widget price range text and "Go" label in KickStart Commerce?

Want to remove "range from...." and change "Go" on the button to Russian "Найти".

What Drupal display view or template, page or module to change? Thank you (see fig. attached, please).

Below is a work around. See if it works :

Create a file custom_string_overrides.inc  inside your custom module folder and add the below code:

$conf['locale_custom_strings_en'][''] = array(
  'Go' => 'Add replacement here',
  'range from' => 'Add replacement here',
);

Add the below code to settings.php

include DRUPAL_ROOT . '/path-to-module/custom_string_overrides.inc';

The above trick does the string replacement and texts will be replaced where ever they appear. As I mentioned, this is just a workaround.


Letting only user #1 pass all the validations of required fields when saving content Is there any way I can let the user #1 save the content of some content type without validating required fields?

You could probably use hook_form_alter and check if the current user is uid=1 then make each field not required any more.

That would be easier for most forms than messing with the actual validation functions and it would also make the UI reflect what is actually happening. You could even put a little message at the top of the form letting the user know that the form has been manipulated like that.


Prevent Multiple Form Submissions (Server side) I'm running into a problem where a user can submit any form built by the Form API multiple times (fast clicking resulting in multiple requests).

I've put in the basic client side (javascript) solution of disabling the button, but I'm curious what the best approach to preventing this situation is on the server side.

Is there a recommended way to use Drupal's form token system to handle this?  Especially a global form solution (ie, adding a custom validator to every form using hook_form_alter()).

My approach so far has been something like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_form_validate';
}

function mymodule_form_validate(&$form, &$form_state){
  //initialize form array
  if (!isset($_SESSION['submitted_forms'])){
    $_SESSION['submitted_forms'] = array();
  }

  $form_token = $form_state['values']['form_token'];
  if ( isset($_SESSION['submitted_forms'][$form_token]) && $_SESSION['submitted_forms'][$form_token] = TRUE ){
    form_set_error('name]', 'This form has already been submitted');
  }
  else{
    $_SESSION['submitted_forms'][$form_token] = TRUE;
  }
}

I'm running into trouble where the form_token isn't unique to the form - it seems to stay the same no matter what happens.  I'm probably misunderstanding what the token is in the grand scheme of the form api.

Any insight is appreciated!

I had the exact same problem and managed to fix it using the Locking mechanisms from Drupal

In the validate function I used:

function mymodule_custom_form_validate($form, &$form_state){
  if (lock_acquire('your_custom_lock_name')) {
    // long operations here
  } else {
    form_set_error("", t("You submitted this form already."));
  }
}

And in the submit function I released the lock:

function mymodule_custom_form_submit($form, &$form_state){
  // submit code
  lock_release('your_custom_lock_name');
}


How to skip step 1 on multi-step/wizard webform? I need to skip step 1 and start on step 2 of a multi-step/wizard webform when a certain condition is true.

I found documentation regarding this, How to programmatically skip steps in wizard forms

The key part being in hook_form_alter putting

$form_state->set('current_step', $all_keys[$goto_destination_step_index-1]);

What this does is fool drupal into thinking you're currently in the previous step that you want to go to, when in reality you're not. But the problem with this solution, is that it only works when you click the "next step" button and not on page load. Thus, the above solution only works for all but the first step.

I have tried doing

$form['progress']['#current_step'] = 'step_2';

But all this does change the progress marker to step 2, but I still see step 1's form.

I need to find a way to fool Drupal into thinking that I have completed step 1.

I tried doing $form_state->set('form_field' $value); when I looked at form_state->getValues(); they were not set. I so I set them with $form_state->getValues()['form_field'] = $value; on all step 1 fields, but doing this alone does not trick Drupal.

There must be somewhere were Drupal stores that step 1 has been completed, but haven't been able to figure out where. My guess would be somewhere on $form_state, but I have not found it yet.

Update:

I don't really need the answer to this anymore, as the condition is no longer needed so it was decided to remove the question's step 1 altogether. But if you happen to know the answer, feel free.

You can autosubmit step1 using JavaScript and it will direct user to step2.
You can use Drupal behaviour so that no one can see step1.


How do I get debug_backtrace() to fire on the endpoint site of a Deployment process? I'm trying to work through this UUID features bug with the deploy module. On the receiving site, I see errors in that log like

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'fc661e5c-62de-fa34-2557-0f6f5a2acbfe' for column 'fid'

I've followed the example laid out here to have a backtrace show for any error on both the sending and receiving installations. However I can' seem to find a way to get the backtrace to show for the error on the receiving site after the deploy process completes. I can see the service error in /admin/reports/dblog but that's it.

Any help is greatly appreciated!

-adbo

note the following: fc661e5c-62de-fa34-2557-0f6f5a2acbfe
and then... General error: 1366 Incorrect integer value:

the number or UUID is not an integer.

therefore you'll get that sort of error message. I'm assuming deploy has either a bug in it or you've forgotten to run update.php on your DB the FID field is marked in the DB as an integer when it should be a varchar / string field.

Take a look at the schema and see what needs to change. that should at least give you an indication of where things have gone wrong.


How can i hard-wire a link, in blocks, using $base_url or something similar? I'm trying, unsuccessfully so far, to create a block that is simple hard-wired link. but i need to use $base_url or something equivalent (like base_url(); ?) but i guess adding php is not allowed.

i tried a few different things in the block body. for example…

<a href="<?php print $base_url . '/archive/program-archive-2012--2013' ?>"> Archives

how i can achieve this, without using a full, or literal URL?

Hard wired to what?

Personally I like to hard wire my URLs the the root of the site. If my site is always a full domain name as wwww.mysite.com The url would be:

 Archives

This is relative to the root of the website. Which makes sense to me. You can move your site to a new domain, www.mysite2.com, and this Path will still work.

If you move your site to a sub-directory later then .htacess BaseRewrite rules can still allow this to work.

I find trying to make a url work for any combination of directory prefixes or a subsite in a folder, etc .... to much of a pain to deal with.


hook_tokens() implementation no longer being called We have a custom module in development, the purpose of which is to fetch the email addresses of the users who review content. Upon revisiting this module (after updating from Drupal-7.41 to Drupal-7.51) its hook_tokens() implementation is no longer being called in the same way it was before.

I cannot understand why this functionality no longer works. I thought this was a proper implementation of these functions. It now no longer fires on nodes, but when an entity is on a node.

Why would hook_tokens() not be called on a node? (The module is enabled, depends on tokens and workbench_access, both of which are enabled.)

Please forgive me if my question is framed inappropriately, I may have an inaccurate understanding of the hook function(s), but I've checked the API and haven't gained clarity. I know for a fact that this module worked earlier this year with Drupal-7.41, but I couldn't find any changes in the related API since that release.

function mymodule_token_info() {
   $info = array();
   $info['tokens']['node']['publisher_one'] = array(
     'name' => t('Section Publisher One'),
     'description' => t('Email address of sections primary publisher.'),
   );
   $info['tokens']['node']['publisher_two'] = array(
     'name' => t('Section Publisher Two'),
     'description' => t('Email address of sections secondary publisher.'),
   );
   return $info;
}

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
   $replacements = array();
   if ($type == 'node' && !empty($data['node'])) {
      print_r('inside if conditional');
      $section_users = array();
      $users = entity_load('user');
      // Get the current Page's section ID (sID).
      $sID = key(_workbench_access_get_node_section_names($data['node']));
      $user_count = 0;
      // Is a given user 1) assigned to the same section as the node and also
      //  of the role identified as the one to be notified.
      // If so, their email address are acquired.
      foreach($users as $user) {
          $user_sections = _workbench_access_get_user_section_names($user);
          if(array_key_exists($sID, $user_sections) && $user_count < 2){
              $role_type = user_roles(TRUE)[variable_get('waemail_role', '0')];
              if(in_array($role_type, $user->roles)){
                  if($user_count == 0){
                      $section_users['publisher_one'] = $user->mail;
                      $user_count++;
                  }
                  else if($user_count == 1){
                      $section_users['publisher_two'] = $user->mail;
                      $user_count++;
                      break;
                  }
              }
          }
      }

      // Assign the values aquired above to the tokens.
      foreach ($tokens as $name => $original) {
          switch ($name) {
              case 'publisher_one':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
              case 'publisher_two':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
          }
      }
    } //end if($type == 'node'...
 return $replacements;
}

hook_tokens() is invoked only when token_generate() is called. Since that doesn't necessarily happens when a node is viewed (or similar events), but it happens when a module calls token_replace(), hook_tokens() not being invoked could not mean your code is wrong.

Assuming that the code you show is not causing any PHP error, that means that a module that was before calling token_replace() is not calling that function anymore, or it is calling it in very specific occasions.
For PHP error I mean:

The code is calling a function that doesn't exist anymore (e.g. _workbench_access_get_user_section_names())
It is calling a function that is returning a value of a different type from what it previously returned (e.g. _workbench_access_get_user_section_names() returns a value that is not an array)

There isn't any change in the token subsystem from Drupal 7.41 to Drupal 7.51 that could cause your code not to work anymore. The only reason for your hook_tokens() implementation not to be invoked in a change in the code of the module your hook implementation is using, or a change in the code of a module that was generating token when viewing a node (or a similar event).

To test your implementation of hook_tokens(), you should directly call token_replace() passing a string containing a token your module defines and a node object. If the token is not replaced, then you can check for errors in your code; if the token is replaced, then your code is working perfectly, and your hook_tokens() implementation is not invoked simply because no module is replacing tokens in a string when you are expecting it to happen.

I would use the following code, to put in a file in the same directory containing the index.php file that comes with Drupal.

/**
 * @file
 * Test page to check the hook implementation of a custom module work.
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Load a node to use as context for the tokens.
// Change the argument for node_load() to match the node ID of
// an existing node.
$node = node_load(1);

// Change the string to the token name for the token that needs to
// be tested.
$token = 'publisher_one';

$result = token_replace("[$token]", array('node' => $node), array('clear' => FALSE));

if ($result == "[$token]") {
  // The token has not been replaced.
}


Trying to create a link in a custom module I have the following code
  `  class PopularContentParselyBlock extends BlockBase {

 /**
  * {@inheritdoc}
  */

 public function build() {
 $client = new \GuzzleHttp\Client();
 $res = $client->request('GET', 'http://www.APIURL.com');
 $decoded = json_decode($res->getBody(),TRUE);
 foreach($decoded['data'] as $article) {
    $url = Url::fromUri( $article['url']);
    $endpoint = Link::fromTextAndUrl($article['title'], $url);

    }
  return $endpoint->toRenderable();
  }
}

`

When it prints out though all I get us Object. What am I doing wrong?

#markup is used for content that has already been rendered. As the caller seems to be expecting a render array, you can just return it directly:

return $endpoint->toRenderable();


How can I hide the entity ID on an autocomplete widget? I have an autocomplete widget for a taxonomy entity reference.

Every term shows its entity ID between parentheses; plus, if the term name contains spaces, it appears between quotes, e.g. "Lorem ipsum (125)".

How do I remove the entity ID and the quotes?

You should have a look on Chosen module.

  Chosen uses the Chosen jQuery plugin to make your  elements
  more user-friendly.

Follow this steps:

Install, enable and configure the Chosen module.
Change the widget type of your field to "Select list" at Manage Form Display of your content type
Check "apply chosen on this field" at Manage Fields > Edit of your field


Send email to specific users when Webform submitted How can I send emails to specific user roles when a specific Webform is submitted?

For example if a Webform named test is submitted then we have to send email to all users having the role say 'editor'.

This could be done by combining Rules and Webform Rules Modules
In Rules Module You could use the following Settings:
Events: After a webform has been submitted
Conditions: User has role(s) and Webform has name (to apply for particular webform)
Actions: Send HTML e-mail


Use multiple widget types for one field I would like to have different field widgets for distinct forms. Is there a way to define multiple widget types for a single field? Here's my case: on the create content form, the widget for the field "Tags", which is a term reference field, is an autocomplete term; but on another form that uses that same field, I would like to use a select list for the widget.

I'm seeking clarification but I'll go ahead and add this here:

As you commented, you can use hook_field_widget_properties_alter() like this:

function important_dates_field_widget_properties_alter(&$widget, $context) {
  // kpr($widget);

  $pageCheck = FALSE;
  $formPath = 'my/form/path';
  if ($formPath == current_path() || $formPath == request_path()) {
    $pageCheck = TRUE;
  }

  if ($pageCheck) {
    // switch from options to autocomplete
    /*if ($widget['type'] == 'options_select') {
      $widget['type'] = 'taxonomy_autocomplete';
      $widget['module'] = 'taxonomy';
    }*/
    // switch from autocomplete to options
    if ($widget['type'] == 'taxonomy_autocomplete') {
      $widget['type'] = 'options_select';
      $widget['module'] = 'options';
    }
  }
}

You can not define multiple widgets for a field.  You can, however, create another field of type "Term Reference" and choose a different widget.


Translate not working for some strings I am using Drupal commons. I am using I18n and other related modules for my website as it is created in English but is being used in French also. I am using translations provided. My issue is that I have string translations but for some strings, text is not being translated, although the translations are available in the drupal.

UPDATE
After going through code, I found that this "Request Message" field is not a normal form field, but it is being rendered using

     field_attach_form('og_membership', $og_membership, $form['membership_fields'], $form_state);

The issue is with this "field_attach_form()". Do ANYONE have any idea what can be done for this??

Although I know this solution is not best and structural method and is better solve this issue but sometimes we just need a solution and want save the time(maybe it be some issue with commons distributes.
Sometimes I do this trick in some projects

if you want translate all keystring  in every where use

 $('body').html( $('body').html().replace(/keystring /g, "TranslateString"));

and also if you want only some specified(with specified class and page class) string use

$('.checkout-review .field-name-phone-mobile .field-label').html($('.checkout-review .field-name-phone-mobile .field-label').html().replace(/keystring /g, "TranslateString"));

You just need put one of them in JS file.


hook_context_default_contexts() ? I used Bulk Export to export all my Context definitions into my module in a function that implements hook_context_default_contexts().  However, my default context definitions do not appear if I delete the ones in the database.

Does this hook no longer work in Drupal 7?

Here's the piece I was missing:

/**
 * Implementation hook_ctools_plugin_api().
 *
 * Makes module compatible with context 3.
 */
function MY_MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'context' && ($api == 'plugins' || $api == 'context')) {
    return array('version' => 3);
  }
}


How to hide a view if it has more than 1 row and also show some block if this is true? I have found a solution in "Hide a view if less than N results" for hiding the view by using the template.php file.

However I need to show a certain block also, the block is already in the correct region it would just need 'switching on' for this page.

Would it be possible to provide a callback inside the following code from the link posted above

function MY_THEME_NAME_preprocess_views_view(&$vars) {
  if ($vars['display_id'] == 'MY_DISPLAY_ID' && count($vars['view']->result) < 1) {
    $vars['view']->result = NULL;
  }
}

To a function which turned the block on

Note: I am just starting module development.

edit: I'm now thinking that this would need to be done inside a custom module as it might be too late to turn the block on from the template.php file. If someone could clarify this.

Part 1

Enable the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

Part 2

As per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the number of rows returned by your view" (so that the block is only shown if the view has more then 1 row).

For that, perform these steps:

Use the Views Bulk Operations module to create a variation of your view in which you add a VBO field to it.
Create a Rules Component with a Rules condition "Check number of results returned by a VBO view". And select the VBO view created in the previous step.


How to theme date combo input side-by-side? I'd like to theme a date combo field on a node edit form to be side by side, rather than stacked vertically, as shown below. Dates are popups, if that makes a difference.

I'm working with the admin theme Seven, which I've sub-themed, in order to override theme functions or CSS as needed. What is the approach should I take for this kind of customization? Moving the "to" label isn't strictly necessary, but would be nice if possible.

Before

After

Also wondering if there is some good reason why the to and from fields are arranged this way?

Edit: instructions for creating a subtheme are here: https://drupal.org/node/225125 This is an easy way to customize an Admin theme if needed.

Looking at the CSS provided by the module, the boxes are foreseen as block elements. Even the used classes on the form fields are date-no-float, so for some reason they don't want that the fields are shown in column layout ...

The fact that you used a sub theme for your admin, you can add these CSS styles (based on Seven theme) in your css file. These will create the desired result you want.

.date-no-float { float: left; width: auto; clear: none; }
.date-no-float > .form-item > label { float: left; margin: 34px 40px 0 30px; }
.start-date-wrapper { clear: left; }


My site only listens to the event after I clear all caches I have a module with an event subscribe that I use to redirect to an age verification page if a cookie is not set, and as long as the current request is not the age verification uri.
if(!isset($_COOKIE['age_gate_ok']) && $request != '/age-verification')
{
    $welcome = new\Symfony\Component\HttpFoundation\RedirectResponse("/age-verification");
    $welcome->send();
}

Problem: the event seems to listen once only, and that is when I use drush to clear cache.
To further explain, I use clear site cache using drush and when I reload the page, it redirects me to the correct page(/age-verification) and then I pass the gate.
However, if I open the inspector to clear cookies and refresh the page, the site does not redirect me to the age verification url.
How do I have to clear cache in order to have the age verification working?

You need to use a Trusted Redirect Response and properly set cache metadata for your response. This is mostly documented in an answer to a related question, Disabling Page Cache for Redirect Response. However, in your case, you'll need to manually build a CacheableMetadata object, so I'll show that here.
// Tell the browser not to cache the redirect by setting these headers.
$response_headers = [
  'Cache-Control' => 'no-cache, no-store, must-revalidate',
];

$response = new TrustedRedirectResponse($url, '302', $response_headers);
// We need to add cache metadata to the response so it can be properly cached by
// Drupal. If redirecting was based on a $node or entity, you could simply call
// $response->addCacheableDependency($node) and addCacheableDependency() would
// automagically pull the correct cache tags, contexts, etc from the object.
// Since your redirect depends on a cookie, you'll have to build a
// \Drupal\Core\Cache\CacheableMetadata object manually.
$cache_metadata = new CacheableMetadata();
// Since you just want to cache the response based on whether they have a cookie
// you can use just the cookies:NAME cache context.
$cache_metadata->setCacheContexts(['cookies:age_gate_ok']);
// Add the metadata to your response.
$response->addCacheableDependency($cache_metadata);

$event->setResponse($response);


Commerce: Extra information per quantity bought Is there any module or solution that allows extra information to be collected for each item bought? Example of what I mean below:

A user can buy any number of tickets, and for the amount of tickets purchased they have to complete details of the other guests (name, email address etc...). So if they buy 10 tickets they have to complete 9 lots of guest information in addition to their own.

Is there any module that can facilitate this? Additionally, the user should be able to log in and change the details of the guests before the event occurs. This part I'm almost certain will be a custom module, but I'm open to any ideas!

Not a simple answer here, you've got a lot of ways to do this, but if you're focusing in the ticket/registration case, you could take a look to Commerce Registration, that will provide the closest feature I know for that matter.

It is based in Entity Registration, so you've got there a starting point.


How to remove edit tab after create commerce order How to remove edit tab after create order for Authenticated User.

You should edit the permissions for the user role in question. Doing so will mean they will not have access to edit orders, and only create them if you so choose to.

It might be a little easier to use the secure permissions module to manage the permissions in code.


How do I create a bundle under my custom content entity type in Drupal 8? I am working on creating a base list entity type I will call CustomList for the sake of this question. I pair it up with CustomListItem so that I have an entity type to define the list and another to define the items in the list.

I intend to create bundles underneath these to build a custom cart, a saved item list, and an item group list.

So far everything I have found in Drupal 8 either creates Node Bundles (which I don't want) or a bundle of config yaml files to define the bundle (in this case ECK did this for me). But nothing useful on how to create a bundle under a specific entity type.

Would I just declare a new entity type and do something in the annotations to make it a bundle? If so I am unsure as to what annotation to use or how to use it.

Thanks,
Patrick

Yes, you declare a config entity type to store the bundle definitions. For example that for Custom Block Types (bundle of block_content):

Drupal\block_content\Entity\BlockContentType

namespace Drupal\block_content\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\block_content\BlockContentTypeInterface;

/**
 * Defines the custom block type entity.
 *
 * @ConfigEntityType(
 *   id = "block_content_type",
 *   label = @Translation("Custom block type"),
 *   handlers = {
 *     "form" = {
 *       "default" = "Drupal\block_content\BlockContentTypeForm",
 *       "add" = "Drupal\block_content\BlockContentTypeForm",
 *       "edit" = "Drupal\block_content\BlockContentTypeForm",
 *       "delete" = "Drupal\block_content\Form\BlockContentTypeDeleteForm"
 *     },
 *     "list_builder" = "Drupal\block_content\BlockContentTypeListBuilder"
 *   },
 *   admin_permission = "administer blocks",
 *   config_prefix = "type",
 *   bundle_of = "block_content",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "delete-form" = "/admin/structure/block/block-content/manage/{block_content_type}/delete",
 *     "edit-form" = "/admin/structure/block/block-content/manage/{block_content_type}",
 *     "collection" = "/admin/structure/block/block-content/types",
 *   },
 *     ...
 * )
 */
class BlockContentType extends ConfigEntityBundleBase implements BlockContentTypeInterface {

Which is then referenced in the content entity type:

Drupal\block_content\Entity\BlockContent

*   bundle_entity_type = "block_content_type",

If you use Drupal Console to generate a custom content entity type and you say yes to the question if you want bundles, this config entity type is set up for you automatically.


How to run Drush commands on a schedule? I'm deploying content to Drupal remotely (I'm in an Enterprise environment) and I need  something to run Drush commands based on a schedule. E.g on a cron task, read commands from the database table or file, execute the commands and record the result.

I've looked at the Rules and Job Schedule modules, but they don't really work because I need to enable Features.

I was thinking of creating a module which reads commands from a database and executes the commands in php. But is there a better way to do this?

Yes, you can use Jenkins, which could be described as an advanced version of cron, though it is more powerful than that.  John Smith made a slideshow about integrating Drupal with Continuous Integration practices.

If you're in an enterprise environment, hopefully you have the resources to get a Jenkins server set up.  You can then also use this to run automated tests, etc. too.


CDN, SEO and image styles: 301 on GET request Recently I installed the CDN module. To avoid duplicate content I added a RewriteRule to my Apache config:

RewriteCond %{REQUEST_URI} !(^/(.*)(.js|.css|.jpg|.jpeg|.gif|.png)) [NC]
RewriteCond %{HTTP_ACCEPT} !(.*image.*|.*css.*|.*javascript.*) [NC]
RewriteCond %{HTTP_HOST} ^(static1.domain.com|static2.domain.com)$ [NC]
RewriteRule ^(.*)$ http://domain.com$1 [L,R=301]

This is working, except when I'm using image styles. If the image exists everything works, but when it doesn't exist, I get a 301 to http://domain.com/index.php

These are the current situations using the implemented RewriteRule:

GET static1.domain.com - 301 to http://domain.com - OK
GET static1.domain.com/image.jpg - 200 - OK
GET static1.domain.com/sites/domain/files/styles/.../image.jpg when
file exists - 200 - OK
GET static1.domain.com/sites/domain/files/styles/.../image.jpg when
file doesn't exist - 301 to http://domain.com/index.php - WRONG

How do I force the image style file to be created when browsing to it from a static URL?

I dont really understand your question, but we handled a similar problem.
We also did rewrtie for all images to static server (different server running lighttpd).
On the lighttpd the files folder was mounted as well, so all files are in sync.

We also had a domain that forced back to one of the webservers (varnish>drupal), and not to use the CDN server .
If the file did not exist in the static server it got rewrtitten (temporary) back to the webserver, which created the imagecache file.
From that moment, the file was there and it would always be there.

attr = lighty.stat(lighty.env['physical.path'])
 if (not attr) then
 lighty.header["Location"] = "http://directto.webserver.com"  .. lighty.env["request.uri"]
 return 302
end

Hope this can help.


How can I get the module path in twig? I have a module and created twig templates there. I just followed the documentation here: https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-for-custom-module

I want to include a JS file from the twig. And the JS file is located inside the module folder. I have this code in the twig:

<script src="/{{ directory }}/js/script.js"></script>

But the directory is returning the theme path NOT the module path. How can I get the module path inside the twig?

There is a solution that can work for your problem without going into php and this solution will work only in case if twig template is under module directory.

Suppose my module structure is like below:

modules

custom_module

templates

my-template.html.twig

js

script.js

To include script.js in my-template.html.twig file. Use below code in twig file -

{% set module_path = _self|split('/templates') %}
<script src="/{{ module_path[0] }}/js/script.js"></script>

In above script _self returns the path upto twig file and split('/templates') splits the string from /templates AND

module_path[0] = /modules/custom_module/
module_path[1] = /my-template.html.twig

However, this is not the appropriate way. This is only a solution for your problem. Appropriate way is to set module path in a variable in preprocess hook and use that variable in twig.


Creating products with Rules and calculating price in Drupal Commerce I am creating products on the fly with Rules, using Drupal Commerce. After user clicks on checkbox near product (additional service to product), I need to "add the service" to cart. Service is always 15% of price of Base product.

I created a rule which creates new products, and add them to cart. This works nicely but I am unable to set up the price field. In Data Selector mode I can not see my calculation field anywhere, not even when calculated value is Integer and price is also integer.

Any help with this? I am posting a Rule here:

{ "rules_grafeon_doplnkov_slu_by_pri_pridan_do_kosika" : {
"LABEL" : "Grafeon - Doplnkov\u00e9 slu\u017eby pri pridan\u00ed do ko\u0161\u00edka",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_discount_extra", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "commerce-line-item" ],
      "field" : "field_doplnkove_sluzby_item"
    }
  },
  { "data_is" : {
      "data" : [ "commerce-line-item:field-doplnkove-sluzby-item:0" ],
      "value" : "Service SLA"
    }
  },
  { "commerce_discount_extra_line_item_has_product_type" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "product_types" : { "value" : { "product" : "product" } }
    }
  }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "date", "value" : "now" },
      "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "text", "value" : [ "variable-added" ] },
      "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "commerce_order",
        "property" : "order_id",
        "value" : [ "commerce-line-item:order-id" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "commerce_product",
        "param_sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
        "param_type" : "doplnkov_slu_by",
        "param_title" : "Service SLA",
        "param_creator" : [ "site:current-user" ],
        "param_commerce_price" : { "value" : { "amount" : 1000, "currency_code" : "EUR" } },
        "param_commerce_stock" : "1000"
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
        "quantity" : "1",
        "combine" : "0"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  }
]

}
}

Any advice how to get the value to Price value? Thanks a lot.

Well It looks like I found a way. I needed to save an entity before adding to cart.

If someone will found himself struggling in the same spot, I will leave an exported rule here:

{ "rules_grafeon_doplnkov_slu_by_pri_pridan_do_kosika" : {
    "LABEL" : "Grafeon - Doplnkov\u00e9 slu\u017eby pri pridan\u00ed do ko\u0161\u00edka",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_discount_extra", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item" ],
          "field" : "field_doplnkove_sluzby_item"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:field-doplnkove-sluzby-item:0" ],
          "value" : "Service SLA"
        }
      },
      { "commerce_discount_extra_line_item_has_product_type" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "product_types" : { "value" : { "product" : "product" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "date", "value" : "now" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "text", "value" : [ "variable-added" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "order_id",
            "value" : [ "commerce-line-item:order-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "commerce_product",
            "param_sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
            "param_type" : "doplnkov_slu_by",
            "param_title" : "Service SLA",
            "param_creator" : [ "site:current-user" ],
            "param_commerce_price" : { "value" : { "amount" : 100, "currency_code" : "EUR" } },
            "param_commerce_stock" : "1000"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "commerce-line-item:commerce-unit-price:amount" ],
            "op" : "*",
            "input_2" : "0.15"
          },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:commerce-price:amount" ],
          "value" : [ "result" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "commerce_cart_product_add_by_sku" : {
          "USING" : {
            "user" : [ "site:current-user" ],
            "sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
            "quantity" : "1",
            "combine" : "0"
          },
          "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
        }
      }
    ]
  }
}


Upgrade error: Attempt to create a field body that does not exist on entity type node I am struggling with Drupal 8 upgrade for a months now. The Travis CI build is always failed with below errors.

I'm upgrading from Drupal 8.3.7 to 8.4.8 with Lightning (2.2.9), BLT 8.9.7, Drush version 8.2.3

Synchronized configuration: update views.view.frontpage.             [ok]
Synchronized configuration: update dropzonejs.settings.              [ok]
Synchronized configuration: update lightning_roles.settings.         [ok]
Finalizing configuration synchronization.                            [ok]
The import failed due for the following reasons:                     [error]
Unexpected error during import with operation delete for
node.type.page: Attempt to create a field body that does not exist on
entity type node.
Unexpected error during import with operation delete for
node.type.landing_page: Attempt to create a field body that does not
exist on entity type node.

I've successfully upgraded on localhost and exported the config file using "drush [mywebsite] cex sync" command. However, when I push to Github the Travis CI build failed with the errors above.

I've done the "drush [mysite] updb" command and it went without any errors.  I also ran the command "drush [mysite] entity-updates -y"

Googling the errors without any luck, so I thought to post it here.  Any help would be most welcome.

The solution is to manually create a "body" field in my landing_page content type.  Once I created the body field, the error no longer show up.

This can be apply to any other fields is show up in the error.


How do I display the domain owner of a node in a view? I have a view that's generating a block showing upcoming events. On the main site those events might be coming from multiple domains (the site is using Domain Access) and I'd like to show the domain owner as a link to their site sub-domain.

Example:

Aug. 14 - Sample Event
Domain Owner (http://owner.mydomain.com)

Is there a way that I can add this directly to the view? If not, what is the most effective/correct method for coding that into a view template override?

I believe that's relatively straight forward to achieve directly in your view without having to touch templates.

All you need to do is in your view, add a relationship of "Domain Source: Domain Node". This will then provide domain information against your nodes. Then in your fields you will be able to add relevant domain information against the node (using the relationship). So in your case I believe you would want to add the field "Domains: Site Name" and select the relationship in the dropdown. You should then have your site name displayed against your events which would link to the domain.

hope thats helps.
Cheers


Cropping image with Drupal 7 api I tried below codes but nothing happen.Any ideas?

$image = image_load('/home/ok/sites/default/files/20140213030054333.jpg', $toolkit = FALSE);
//print_r($image);
 image_scale_and_crop($image, 350,700);

Taking a wild stab in the dark:

image_save($image);


How to get success message in popup using custom form? How to get success message in popup form  here is my code :

   <?php
 /**
 * Implements security_settings_form().
*/
function security_settings_block_info() {
$blocks['testing'] = array(
'info' => t('testing1'),
'cache' => DRUPAL_NO_CACHE, //there are a number of caching options for this
 );

 return $blocks;
 }

function security_settings_block_view($delta = ''){
  switch($delta){
    case 'testing':
  if(user_access('access content')){ //good idea to check user perms here
     $block['subject'] = t('testing');
     $block['content'] = drupal_get_form('security_settings_form');
     //$block['content'] = security_settings_form();
     return $block;
  }
  break;
  }
  }
function security_settings_form($form, &$form_state) {
$form["wrapper"] = array("#markup" => "

");

   $result = db_select('taxonomy_term_data', 'ttd');
  $result->fields('ttd');
  $result->condition('ttd.vid', 2, '=');
  $results = $result->execute()->fetchAll();
   $termName = '';
   foreach($results as $record){

   $v[]=$record->name;

}
$form['cities'] = array(
'#type' => 'select',
'#title' => t('Click on your city'),
//'#multiple' => true,
'#options' => $v,

 '#attributes' => array('class' => array('my-class-1')),
  );
   $form['email'] = array(
   '#type' => 'textfield',
   '#title' => t('Enter email'),

   '#validate' => array('security_settings_form_validate'),
 );
    $form['save'] = array(
    '#type' => 'button',

    '#value' =>  'Save',

     "#ajax" => array(
  "callback" => "dr_search_test_form_callback",

  "wrapper" => "test-ajax",
  "effect" => "fade")

    );

return $form;
 }

function security_settings_form_validate($form, &$form_state) {
$email = $form_state['values']['email'];

 // Verify that the email address is valid.
   if (!valid_email_address($email)) {
  form_set_error('email',('You must provide a valid email address.'));
  }

}

  function dr_search_test_form_callback($form, $form_state) {

   global $user;
   $v=db_insert('security_settings')
   ->fields(array(
  'uid' => $user->uid,
  'email' => $form_state['values']['email'],
  'cities' => $form_state['values']['cities'],
    ))->execute();

   $email = $form_state['values']['email'];
   if (valid_email_address($email)) {
   $message = array('A new entry has been submitted');
   $to = 'abc@gmail.com';
   $params = array(
    'body' => $body,
    'subject' => 'Website Information Request',
     );
       if (drupal_mail('security_settings', 'some_mail_key',   $to,          language_default(), $params)) {
    drupal_set_message('Thanks, email sent.');  //success message
   } else {
    drupal_set_message('Email not sent.');
  }
  }

return "
".$v."
";
  }
 function security_settings_mail($key, &$message, $params) {
   $message['subject'] = $params['subject'];
   $message['body'] = $params['body'];
  }

You can return the messages to the ajax form by adding the following to your ajax callback function (you'll need to remove your current return value)

$messages = array('#theme' => 'status_messages');
$commands = array();
$commands[] = ajax_command_prepend('#form_id', render($messages));

return array('#type' => 'ajax', '#commands' => $commands);

Make sure to change #form_id to the actual ID of your form, or use whatever jQuery selector you want to prepend the messages to.


Hiding fields when creating node and showing them only when editing I'd need to enable editing of certain fields only when the node they're assigned to already exists. Therefore I need to disable them on node create form and enable them on node edit form.

I though I'd do it the same way as with users where you have two separate forms (user profile a user register) and therefore can use settings array on field instance (at least I believe it works this way).

...
'settings' => array(
   'user_register_form' => 0,
),
...

The problem is you can't do it with nodes as nodes don't have separate forms for edit and create.

I know I can do it directly via altering CONTENTTYPENAME_node_form (changing the access status of the fields to false or unseting them completely when the node does not yet exist) but it doesn't seem to be the very best solution (It doesn't feel systematical to unset it on form alter hook).

BTW: I know that someone asked similar question but he hasn't received any answers.

This is certainly without a doubt a job for hook_form_alter() and quite easy to accomplish, eg, something along the lines of:

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

  switch ($form_id) {

    case 'foo_node_form':

      if ($_GET['q']=='node/add/foo') {

        // we are creating a node of type foo so do stuff to the form one way here

      } else {

        // we are editing a node of type foo so do stuff to the form another way here

      }

      break;

   // other forms here

  }

}


How to get field label from a field machine name $fields = \Drupal\Core\Entity\EntityTypeManagerInterface->getStorage('field_storage_config')->loadMultiple();

This is listing me all the fields.

foreach ($fields as $key => $instance) {
   $label = $instance->getLabel();
   $name = $instance->getName();
}

$label is giving me node.field_image

$name is giving me field_image

My question is how can we get the label of the field in drupal 8

The label is not stored in the field storage configuration. You'll find the label in the bundle specific field definition:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
foreach (array_keys($definitions) as $key) {
  // get label for field machine name $key:
  $label = $definitions[$key]->getLabel();
}

Reference: EntityFieldManager::getFieldDefinitions


How can I create an entity bundle programmatically? Given a custom defined entity 'Foo', how can I make a bundle programmatically?

Such as Node entity has the Article and Basic page bundles (with fields) on install.

Bundles are configuration.

You define a config entity with the name of the bundle of the custom entity:

class FooType extends ConfigEntityBundleBase

Then you can create a new bundle:

$bundle = FooType::create([
  'id' => 'newbundle',
  'label' => 'New Bundle',
  'revision' => FALSE,
]);
$bundle->save();

Bundles usually are not created programmatically. Most times modules put bundles in /config/install as yml files.


Drupal 8 REST add custom error messages to existing core /entity/user/ resource I am using drupal 8 rest and I want to be able to do a few computations and return custom json messages as per the defined condition when posting a user. I am using the already existing /entity/user/ resource provided by core out of the box. I tried to create a custom module and tried to use the Drupal\rest\ResourceResponse class in the module file like below:

function magri_rest_user_presave($account) {

    if (isset($account->field_region->value)) {

        $taxonomy_query = \Drupal::entityQuery('taxonomy_term');
        $taxonomy_query ->condition('vid', "region")
            ->condition('name', $account->field_region->value);
        $tids = $taxonomy_query->execute();

        $tid = array_values($tids)[0];

        if($tid){
            //set taxonomy ref field on user entity
            $account->field_region_tax->target_id = $tid;

        }else{
            die;
            $response = ['message' => 'Region not found'];
            return new ResourceResponse($response);
        }
    }
}

This does not stop the rest call to return the custom message. Is there a way I can archive this withouts creating my own custom rest plugin?

You can't return a response from a presave hook. You can however throw an exception, which in a json route will return a json error message:

throw new NotFoundHttpException('Region not found!');

If you want to change the default error response, implement an exception subscriber to catch this exception and return your own response.

For reference the default exception handler: ExceptionJsonSubscriber::on4xx


Date field: prepopulate off When adding a new node with a date field in it, the date field is prepopulated with the current date. Is there a way to easily switch that feature off so that the date field is empty?

You can set the default-values in your Content-type > Field-settings > More settings and values > Default values, (Now, Relative, No default value) set it to "No default value".


How to nest Rules, call a rule from another rule and how to choose between 2 Rules Actions? Is there a way to nest Rules, or make them behave more like an if / then / else functionality.

Currently I can only figure out how to trigger a Rules Action based on a Rules Condition, but not how to choose between 2 Rules Actions.

In addition, is there a way to call one rule from another?

Your question consists of multiple questions, so my answer also consists of multiple parts ...

Part 1

To implement conditional logic in Rules, your very first attempt should be to only use Rules Conditions, and try to use the AND and OR operators to combine multiple Rules Conditions. If no such operator is specified, then the default is that ALL Rules Conditions must be true for the Rules Actions to be executed (this is equivalent to using the AND operator).

For way more details about this, refer to my answer to "What's the difference between combining Rules conditions with AND and just have them follow one after the other?".

Attention, even though using these AND and OR operators may seem obvious, it is NOT! For an example of how confusing it can be, refer to the video tutorial about "Combining conditions".

Part 2

  Currently I can only figure out how to trigger a Rules Action based on a Rules Condition, but not how to choose between 2 Rules Actions.

You're right, to "choose between Rules Actions" is like performing Rules Conditions within Rules Actions, which you cannot do with only the Rules module. However, the Conditional Rules module allows you to exactly do that (execute Rules Conditions as part of Rules Actions).

My favorite example to illustrate this can be found in my answer to "How to check whether one's current User Points are negative with the Rules module?", which includes a rule that looks like so:

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

This rule retrieves, as the very first Rules Action (not Rules Condition!), the current amount of user points of a user. And after the Rules Action to display some message, you can see the Conditional Rules module at work (starting from CONDITIONAL): it will show a message that depends on the total amount of points.

For another example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Bonus: Instead of using if/else (conditional) logic within the Rules Action, you can also use Switch logic. For another example using such Switch logic, refer to rule included in my answer to "How to set the values of some fields depending on the value of a list box?".

Be aware: the Conditional Rules module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed, but also with additional Rules Conditions equivalent to any Rules Conditions you'd want to include by using the Conditional Rules module. And then perform that Rules Component inside your Rules Actions of your original rule. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?"

Part 3

  In addition, is there a way to call one rule from another?

That's what Rules Components is all about, which you can do for:

only Rules Conditions, using a Rules Component of plugin type "Condition set".
only Rules Actions, using a Rules Component of plugin type "Action set".
both Rules Conditions and Rules Actions, using a Rules Component of plugin type "Rule".

Rules Components may use variables, whereas there are 2 variations of them:

Parameters which are used as input that the Rules Component needs in order to execute.
Provided which are output (instead of input), and which can be used (after the execution of the Rules Component completed) in the rule that calls the Rules Component.

For more details about this, refer to:

the video tutorial about "Rules Components".
the community documentation about "Rules Components".

PS: I'm assuming this question is about D7.


Can I use hook form alter to add an attribute to a webform field? I am trying to use hook form alter to add an onchange attribute to a select field but it is not working. Is it possible or is there something wrong with my module code?

function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#onchange'] = 'changevalue';
  }
}

Thanks for any help.

You have to do something like this:

function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#attributes']['onchange'] = 'changevalue';
  }
}


Maintenance Page -> Show a specific block How to make a block available on the maintenance page (e.g. jQuery Countdown) ? Is it about setting right permissions?

You cannot. The maintainance page is used for when you have put the site offline, or when the site is experiencing trouble.

When you put the site offline, you typically will be doing database migrations, updates and the likes.
When Drupal puts the site offline, there is trouble; e.g. the databaseserver cannot be reached/is crached etc.

In case 1. You don't want your average users to reach the database, after all, no-one knows what state that database is in. The whole point of bringing it down, is to avoid people writing and reading from a crippled, stateless and changing database.

Since Drupal stores its blocks or their configuration in the database, Drupal cannot should not read from the block system.

From the relevant code:

// The bootstrap was not complete. So we are operating in a crippled
// environment, we need to bootstrap just enough to allow hook invocations
// to work

That said, you can still modify the maintainance template. Just be very carefull with calling Drupal API's and/or the database in there. The maintainance theme is there for the cases when these are not available. And if they are not, your users are going to see ugly fatal errors (or nothing at all).


How can i know who has created user? I have created some roles and these role's user also can create certain type of user.so how to know who is creator i.e, user author name.

By default Drupal don't save anything about who create a user.
If you want do it, go to user account fields  admin/config/people/accounts/fields add entity_reference with select list widget, then in your custom module in hook_form_alter set default value for field with get current user uid and then hide it there, in this manner the current user id (the user that create user) saved in fields without he/she know that this, also you can dont use hook_form_alter just get $user->uid(the current user that create user ) form global $user in hook_user_insert

shortly

add a entity reference field to user save creator uid in
hook_form_alter when or hook_user_insert


Module for username suggestions on registration Is there any Drupal module which checks the username in the database, if its present then it should display some suggestions to be selected just like the yahoo or gmail gives on registration?

There is no module that does that. The closest you will find is the one that just checks if the username is available while registering. An example of such module is username check. To achieve the username suggestion bit, you may have to write a custom module for that.

  This very simple module allows visitors to check username originality
  quickly using AJAX request during registration (completing
  registration form). This makes registration process more convenient as
  you don't need to submit your registration form to find out whether
  this username is already taken or not. This module is sensible to
  standard Drupal username validation as well as Access Rules
  validation.

or friendly register

  Friendly Register module allows users to see if a username or email
  address has already been used during registration before they submit
  the form. This module checks the database and returns an error if the
  username is already in use. In addition to checking the username the
  module checks if there is already an account using that email address,
  if there is, a message is displayed with links to the login or reset
  password pages.


Formatting email sent with Contact form I created a custom form (adding some additional fields) using the Contact module from the core of Drupal 8.

When I submit the form is sent an email containing all values, but it is really bad formatted. The email only contains form's values without any field label and it is unreadable.

How can I customize the template of the email sent on the form's submit?

What I already tried

hook_mail_alter

I found some answer about the same problem for Drupal 7 suggesting to implement a custom hook_mail_alter function (for example: 1, 2).

So I created a custom module with my function:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {

  // Process only 'contact_page_mail' messages
  if ($message['id'] != 'contact_page_mail') {
    return;
  }

  $params = $message['params'];

  // Body
  $message['body'] = [];
  $message['body'][] = t('Some custom message');

  // I don't know what should I do here?
  // How can I access values of all fields in the form?
  // ...

  return;
}

The function is correctly triggered before the email is sent, but I can't access field's values so I'm not able to build a custom email.

Also I can't get the form's id (only a generic 'contact_page_mail' valid on all contact forms) so I'm not able to handle different contact forms in this function.

Swift Mailer

As suggested in this other similar question, I tried with the Swift Mailer module.

After some effort, I'm able to get it working and now I have a swiftmailer.html.twig template file with this content:

<div>

  {{ body }}

</div>

But as for the hook_mail_alter solution, I don't know how to access form's field values so I can't customize the email format.

Moreover, the Swift Mailer module currently is an alpha version (8.x-1.0-alpha1) and the Mailsystem module (required to get things working) is a beta version. So I would like to avoid to install unstable modules on a production website (anyway this can be the last solution, if no other works).

EDIT

Thanks to @Berdir, now within the hook_mail_alter function I can access field values with:

$contactMessage = $message['params']['contact_message'];

// Value of 'field_my_field_name'
$contactMessage->get('field_my_field_name')->getString();

So I can put them inside the $message['body'].

Quite complicated, but it works.

Is there a way to get field values within the Swift Mailer template? I tried with {{ params.contact_message.field_work_with_us_name }} but it doesn't works.

What happen if I have two or more contact forms? The function hook_mail_alter will be triggered on all of them. Is there a way to have a specific function for each contact form?

Putting together an answer based on the comments/discussion there so this can be accepted/closed.

General instructions on how to theme a mail can be found in this existing answer: How can I theme the outgoing contact mail?
You might want to watch https://www.drupal.org/node/2680731, once resolved, you can rely on that instead of your own custom code to send the mail as HTML.
To use a custom template for the inner parts of the mail, you can set a custom template in hook_contact_message_view(). Or use field templates for specific fields.
To check for a specific contact form, you can use the bundle() method of the contact message entity, which you can find in $message['params]['contact_message'] in hook_mail_alter(). Make sure you combine this with a check that it is there and an entity object, otherwise you could have fatal errors for other mails.


Ajax error while saving a view When I edit a view, and click on the "Save" button, I get the following message:

  An AJAX HTTP error occurred.
  HTTP Result Code: 200
  Debugging information follows.
  Path: /admin/structure/views/view/vouchers_list/preview/page/ajax
  StatusText: OK

What does that message mean? How can I fix the error?

When you make a change to a view in the UI and click "save" before the preview has finished loading, you'll get this error. It's simply because you've made a 2nd request to the server while the ajax request to load the preview is still running.

You can either wait for the preview "loading" icon to finish before you save the view, or you can ignore it :)


How can I display conditional fields on page view? I want to display one of two fields on page render, depending on which field was selected on save.

I have a content type with a paragraph field called Banner Header. Banner header has a field group called Callout links. Callout links contains three items:

A field that accepts a single link.
A field that accepts multiple links.
A select list radio button called Callout Link Control.

Here is the custom paragraph code for my banner header:

{# initiate the printing of the banner #}
{{content.field_banner}}

    {# print out the title of the node #}

{{ node_title }}

           {{content.field_leadin}}

    {# If there is content in the field_callout_icon or field_callout_text #}
        {% if content.field_callout_icon.0 or content.field_callout_text.0 %}

                {% if content.field_callout_link_control.0 == 'A single large button link' %}

                {% endif %}
                {% if content.field_callout_link_control.0 == 'Multiple small button links' %}

                        {% if content.field_callout_link.0 %}

{{content.field_callout_link.0}}

                        {% endif %}
                {% endif %}

                   {{ content.field_callout_icon }}
                   {{ content.field_callout_text }}

        {% endif %}

Depending on which radio button is selected, I want to display the corresponding Callout Link field: either field_callout_link or field_small_callout_button_link.

I've tried this a couple different ways. As you can see my my code, I attempted to control the way the fields display with twig.

I have also tried the conditional_fields module and set the following dependencies:

Cond. 1

Target Field: field_callout_link
Controlled By: field_callout_link_control
Description: !disabled
Value: [corresponding radio button is selected]

Cond. 2

Target Field: field_small_callout_button_link
Controlled By: field_callout_link_control
Description: !disabled
Value: [corresponding radio button is selected]

The behavior I see is that only the field field_callout_link displays on page render - regardless of which radio button is selected.

How can I control which field(s) display when the page renders based on radio button selection?

You don't need conditional fields for this. The simplest way to do this IMO is just look at the values either in the Twig file, or create a new variable in a preprocess function to indicate what to do.

Example:

{% if node.field_callout_icon or node.field_callout_text %}
  {% if node.field_callout_link_control.value == 'A single large button link' %}
    markup
  {% elseif ... %}
    markup
  {% endif %}
{% endif %}

Or you can preprocess the node and look at the field value there:

function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  $field_value = $node->get('field_name')->getValue();
  // .. do stuff with the field value
  $variables['my_new_flag'] = 'some value or bool';
}

Then in the node twig, if its a bool:

{% if my_new_flag %}

Or if you assigned a value:

{% if my_new_flag == '...' %}

One thing I would advise against is looking into the render array to read or look for values. Use the node object or preprocess the node to evaluate the values and create new variables if you need them.

Here is a real example I am using which seems very similar to yours. I have a select field in a node type that indicates if the content is a service or a tool. Depending on which, I need to output the right SVG file next to the title. I am checking the value and creating a variable for the template:

mytheme.theme:

/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  if ($node->getType() == 'services') {
    $variables['icon_type'] = $node->get('field_service_or_tool')->value;
  }
}

The node type twig file:

{% if icon_type == 'service' %}
  {% include "@mytheme/svg/general/service.html.twig" %}
{% else %}
  {% include "@mytheme/svg/general/tool.html.twig" %}
{% endif %}

I could just check that in the twig as well, but it keeps the template cleaner / easier to read in my opinion.


Facebook "like" button fetch wrong data on views I am using Drupal 7 with views and Addthis module for facebook "like" and "share" .

I have add a "like" field to views, so every piece of content has a "like" button.
when a user click on the "Like" button, facebook fetch the wrong data. It can be the picture of different content (e.g. content from the sidebar), it can the user picture instead of the content picture, etc.

How can I fix this?
Should I use different social module that is more suitable for working with views?

Update (2/28/2014):
I spoke with addthis support, and they say I need to add the open-graph for the image. The problem is that I have many images in all the views.
Anyway, I also have the metatag module installed and inside I can define open-graph. When I atried to define the Open Graph image as the image token ([node:field_image]) of the node - nothing change, meaning it doesn't work.
When I tried to add image token to the "views open-graph" -  I didn't find one.
Can someone help me define image open graph to the views output?

Read about og (open-graph) meta tags.
As I know, metatag module supports this kind of meta-tags.


Active trail when view has argument Let's say I have the view with arguments. My path to view page is /products. The path that contains argument eg. 3 looks like this /products/3.

Now as the view is displayed without arguments and the product path is in the main menu - active class for menu item is displayed correctly, however if I add path with argument product/3 and link it in my menu then there's not active item.

How to extort Drupal to show active item?

There are couple of modules for this.

1)Menu Position

Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

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

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

blog
blog/category1
blog/category1/article1

Note: I'm not sure about(didn't use) Menu Trail By Path module. but I used Menu Position module and works great for me.


Adding a Select List (Text) field to an entity bundle programmatically I've been searching for hours, but can't seem to find a solution to this. Now, I'm able to create a plain old text field as such as this:

In moduleA.install:

if (!field_info_field('field_myfield')) {
  $field = array(
    'field_name' => 'field_myfield',
    'type' => 'text',
  );
  field_create_field($field);
}

Then, in moduleB.install, I add that field to a specific taxonomy bundle:

$instance = array(
  'field_name' => 'field_myfield',
  'entity_type' => 'taxonomy_term',
  'label' => 'MyField',
  'bundle' => 'new_terms',
  'widget' => array(
      'type' => 'text',
  ),
);
field_create_instance($instance);

What I would like is the field it creates to be a select list, instead of just a text field. I've been looking around, trying to figure it out (using "list-select" in place of type), but any time I've deviated from what's above, I get an error on field_create_instance when installing moduleB. I realize it's probably (hopefully) something as simple as knowing the proper widget name, but I either can't seem to find it, or am searching for the wrong thing.

The field type would be list_text (as defined in list_field_info(), and the widget type is options_select, as defined in options_field_widget_info().

Kind of tricky to track down, but this little snippet should help in future:

$entity_type = 'node';
$field_name = 'field_name';
$bundle_name = 'article';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

It'll get you a complete field and instance definition of an existing field, ready to use in code.


Naming Structure for Create Node Page template? I need to create a custom template for:
/node/add/node

It's currently using:
page--node.tpl.php

What's the file naming convention for this?


Bypass field validation I have a content type form with some fields attached. I'm looking for an easy way of skipping core validation for one of those fields. I guess what I'm looking for is something like this:

$form['foo']['#check_valid'] = FALSE;

This could possibly be achieved using #limit_validation_errors, but this would require some work. Can this be achieved without too much of a hassle?

It should be possible to remove core validation from the field by adding the #form_validate array element to the form element you want to edit, then pass a custom validation callback that passes the field by default.  That should work.


Get page content from page-title Is it possible to get page content (in array) from for example a Title. Like this;

$wantedPage = function_to_get_page_content('This is the title');

and then just print_r($wantedPage) to get this page content, in array.

I'm pretty new on this great CMS-system..

If what you mean is the node contents, in D6, this would be as easy as $node = node_load(array('title' => $text)); and I would hope the same holds true it D7, but I've been known to misspeak a bit there :)  Just realize that titles aren't necessarily unique.  If you mean the page, with all the header, footer, css, js, blocks and so forth, that's another story in of itself.


Alter a date format in a view based on another date In Drupal 8, I have a View formatted as a Table displaying a node type with two Date-Time fields. They are Start Date and End Date. Within the View I have them in the same column. I would like to alter how the End Date displays based on the Start Date. In particular, if the End Date is the same day as the Start date, I only want the time component displayed. I have created a Time date format for use elsewhere, that I assume will be referenced for this. In the event that the dates are different days, they need to use the default format.

I assume that one of the view hooks is what I need. But I am unsure of which one and do not know exactly what I would need to alter in the view's code.

You can override the output using twig code:

{% if field_date1.striptags == field_date2.striptags %}
    {{ field_date1 }}
{% else %}
    {{ field_date1 }} - {{ field_vegdate2 }}
{% endif %}

Or something like this...