Using Rules to create a Comment with multiple fields formatted in the Main Body Text I'm trying to create a Rule that will create a comment on another post when a node is created. I would like the comment to contain a number of fields from the original post in a formatted manner.

For example: I have a content type called "Project Status Reports" which has 3 text area fields: field_preparation, field_methods and field_outcomes and a node reference field: field_project_node.

When a Project Status Report is created, the user selects a node to associate it with (in field_project_node) and fills the 3 text areas.

I would like to create a Rule that gets triggers when a Project Status Report is created, which will then make a comment on the node referenced in field_project_node. I would like the body of the comment to look something like this:

Preparation

[node:field_preparation]

Methods

[node:field_methods

Outcomes

[node:field_outcomes]

I have created the Rule successfully and have it triggering however I am unable to work out how to fill the Main Body Text of the comment with formatted text which will do the replacements. All I can seem to do is either add static html or have it post a single field.

Is this possible? Thanks in advance

Step 1: Getting around a known comment body limitation

I think the core of your question relates to what's written in Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields ", i.e.:

  ... param_comment_body doesn't assume any data types except 'formatted text' ...

This issue includes a Rule example that looks like so:

{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

The clue to solve your issue (= work around?) is to rework your exported rule (as in revision 1 of your question) so that it uses that last Rules Action starting with "data_set".

Step 2: Combining 3 fields

However, since in your case you want to combine those 3 text area fields, you should also include these extra Rules Actions (prior to that Rules Action starting with "data_set"):

Add a variable (to use as your comment-body later on), say with machine name like variable_for_comment_body.
3 (similar) Rules Actions to Set a data value, for variable [variable-for-comment-body] (added in the prior Rules Action), whereas each of these 3 Rules Actions will refer to the value of each of your 3 text area fields.

For an example rule where you can see this technique at work, refer to my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?" (you don't need a Rules loop though, just those 3 similar Rules Actions.

And with the above logic in place, theh value in your last Rules Action starting with "data_set" simply becomes [ "variable-for-comment-body" ].


Real world experience in scaling and tuning performance The website I'm working is allegedly going to have a massive hit rate soon after launch. The client is talking about the possibility  of around 2500 hits per second over a day or so.

Ignoring the fact that this hit rate is probably wild client optimism and apart from getting the largest servers possible, what is the best way that Drupal should be configured to support a large hit rate.

I've read Scaling the drupal.org Infrastructure, Drupal performance blog, Best Practices for Scaling Drupal and many other pages, but what I'm looking for is real experience of doing this, what works, what doesn't, and what to expect.

Markdorison's answer is basically the accepted method of attacking this problem. I'll take that a little further.

When you have Pressflow for D6 or Drupal for D7, Memcached and Varnish all working nicely together you'll need to custom code your VCL file. There are free ones available  that make starting points but you always need to play with them.

To get Varnish to work optimally make sure you start it with -s malloc xG rather than the default of -s file /path/to/file.
Also with Varnish have Varnish cache static items for as long as you can.

If you have more than one web server remove the ETag from the header sent to Varnish in VCL. I also remove Expires and simply rely on Age and max-age in the headers so get browsers back to the site.

Version 1.5 (as of 3rd March 2011) is still the fastest version of Memcached module from Drupal.org. I typically deploy it using a single bin per server to lower tcp traffic for connections to multiple bins at large scale)

Configure the caching in "Performance" to external and set a max age which will send the correct headers to a caching proxy such as Varnish.

If you can't get certain pages to cache properly in Varnish check out blog posts on the web that detail how to inspect the requests. Here is an example post I wrote a while back: What is stopping Varnish and Drupal Pressflow from caching anonymous users page views

You should pick InnoDB (or one of it's other names from other providers like XtraDB) for MySQL and move all tables into it. Then check out this blog post for basic tuning advice http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/

Having a large buffer pool is fundamentally important. When load testing the site turn on the slow query log. You probably want to at first capture queries taking longer than 50msec then tune the queries and repetitively reduce the slow log capture time down until you have most queries running using indexes, and executing fairly quickly.

Other basics involve having APC in for PHP. If you go for fast CGI rather than mod_php do spend some time trying to make the APC cache shared across the php instances by configuring a good wrapper script. Also make sure that the APC cache is in a memory mapped file to squeeze every last bit out of PHP.


How to add a custom attribute to the script tag via drupal_add_js? As part of API implementation of Queue-it framework, I need to add extra custom attribute data-queueit-c into script tag, e.g.

<script
    data-queueit-c="MyClientID"
    type="text/javascript"
    src="//static.queue-it.net/script/queueconfigloader.min.js">
</script>

I'm aware you can add other attributes such as defer, however this one is custom.

I've tried the following code using drupal_add_js, but without luck:

drupal_add_js('//static.queue-it.net/script/queueconfigloader.min.js',
  [
    'type' => 'external',
    'data-queueit-c' => 'MyClientID',
  ]);

How this can be achieved?

It's old but I have the same problem (adding "crossorigin" attribute) and this is my answer :

There is an issue about it here : https://www.drupal.org/project/drupal/issues/1664602
@kenorb solution can't work because "drupal_add_js" add "script" tag automatically.
But... you can try this workaround (a little dirty) :
close the script tag and open yours without closing

.

drupal_add_js('//--><!]]></script><script src="//static.queue-it.net/script/queueconfigloader.min.js" data-queueit-c="MyClientID"><!--//--><![CDATA[//><!--', 'inline');


For the creation of a prepopulate link, how can i strip out slashes if they occur in the title? if(isset($node->field_eventform['und'][0]['nid'])) {
          echo '

';
          echo 'field_eventform['und'][0]['nid'].'/'.$node->title.'/'.$node->nid.'">'.$node->field_eventform['und'][0]['node']->title.'';
        echo '

';
   }

?>

With this snippet we prepopulate a webform for events. But when a site editor uses a "/" in the title the link doesn't work anymore. How can I strip out slashes if they occur in the title?

echo 'field_eventform['und'][0]['nid'].'/'.str_replace('/','',$node->title).'/'.$node->nid.'">'.str_replace('/','',$node->field_eventform['und'][0]['node']->title).'';

You have to check, if the link works, when you strip the '/', if not, replace the '' in str_replace with the correct replacement, that your path alias use.


How to programmatically disallow some users to comment on some nodes? I've been asked to implement the following:

I have a content type with a user reference field from the References module;
a user creates a node and references another user using that field;
only that user and the node's author are allowed to add comments to that node;
at some point the author closes comments, but that's part of another question :)

I've browsed the API of node (both module and API itself) and comment, and couldn't find anything useful. In fact I tried with two of the most promising functions (hook_node_view and hook_node_view_alter) without success.

I'd appreciate pointers to look at.

(yes, I know I said "complex", but this is just the starting point :)

EDIT: Partial solution ahead

function _comment_access_check_permission(&$node) {
    if(user_is_logged_in()) {
        global $user;
        $account = user_load($user->uid);
        $account_uid = intval($account->uid);
        $asker = field_get_items('node', $node, 'field_asker');
        $asker_uid = intval($asker[0]['uid']);
        $author_uid = intval($node->uid);

        if($account_uid == 1 or $account_uid == $asker_uid or $account_uid == $author_uid) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

function comment_access_preprocess_comment_wrapper(&$vars) {
    if(!_comment_access_check_permission($vars['node'])) {
        $vars['content']['comment_form'] = array();
    }
}

function comment_access_preprocess_comment(&$vars) {
    if(!_comment_access_check_permission($vars['node'])) {
        unset($vars['content']['links']['comment']['#links']['comment-reply']);
    }
}

This code effectively hides the comment form for those users that are not supposed to comment on a given node.

BUT. If one goes to comment/reply/$nid or comment/reply/$nid/$cid the form is still shown, which is not acceptable. Another overview of the API didn't ring any bell to me, so if you have any suggestion…

I would hook_form_alter the comment form, and use your logic to set #access on the form.  You may need to explicitly call menu_get_item to get your node to use in the logic.

You could also use a template_preprocess_node that would perform your logic, and hide or show the comment form in the node's render array based on your logic (this assumes it is in that render array, which I am not 100% positive about).


Feeds import - Skip importing item based on some condition I am making API call to import data into Drupal. The API provides 2 filters by which I can get the data. Now I want to apply additional filter on the returned data and only save data which validate the third filter.
E.g.
The API - http://example.com/users?country=US&state=NY
Requirement - I want to import users data into Drupal only if users age is above 18 (And from US-NYC).

Now the API do not have age filter, but it provides age in the response. How can I write a code to ask feed importer to skip import if age is below 18.

Hope I am clear asking this question.

You can do this using hook_feeds_presave to check the data prior to it being saved.

function mymodule_feeds_presave(FeedsSource $source, $entity, $item) {

  // check that this is fired only for the importer being used
  if($source->importer->id=='my_user_importer'){

    // check that the age is over 18
    if($item['age'] < '18'){
      $entity->feeds_item->skip = TRUE;
      drupal_set_message(t("Skipping user who's age is below 18", 'warning');
    }
  }
}


Call a template file in hook_block_view So I'm using the $block['content'] = right now to display the html for my module. But I can't bake any php into it with it laying inline like that.

How can I make a call to my custom template file that I've added to my module directory?

in your module use hook_theme() in drupal 7

function YOURMODULE_theme() {
  return array(
    'YOURMODULE_CUSTOM_THEME_NAME' => array(
      'variables' => array('title' => NULL, 'path' => NULL), // eg: if you want $title, $path in ur tpl. you can use any variable or an entire array/object.
      'template' => 'CUSTOM-TPL',
    ),
  );

and in your module folder ,create CUSTOM-TPL.tpl.php

now you can call it in

$block['content'] = theme('YOURMODULE_CUSTOM_THEME_NAME', array('title' => $title, 'path' => $path));

for drupal 6 , user 'arguments' instead of 'variables' and

theme('YOURMODULE_CUSTOM_THEME_NAME', $title, $path);


absolute url of inline images in body using views and services I am using services module in Drupal 8 to output node body in JSON format. The inline images are broken in android app which uses json to render node. Is there any code/method or module for D8 which can rewrite relative inline images path to absolute. My drupal version is 8.0.5

This is discussed for a long time, but unfortunately there is no solution committed to core until now, see https://www.drupal.org/node/2630076

Basically this tells you, that you need a text filter like this

http://cgit.drupalcode.org/drupal/tree/core/modules/editor/src/Plugin/Filter/EditorFileReference.php

where you change the line

$node->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri())));

to

$node->setAttribute('src', file_create_url($file->getFileUri()));

by removing url_transform_relative().


Alter views 'Has taxonomy term' filter Programatically using views_get_view Im am having some problems setting TID filter values programatically. I have an array of term ids form a taxonomy field that I need apply to a views filter via views_get_view.

This is the code that I have within a DS field that Im trying to alter via the view's display_handler - Im not even sure if this is the best way to do this. Hopefully someone can explain how this can be done.

Any help would be much appreciated.
Thanks

    $pager_count = field_get_items('node', $fields['entity'], 'field_pager_count');
    $pager_count = isset($pager_count[0]['value']) ? $pager_count[0]['value'] : 10;
    $node_tags = field_get_items('node', $fields['entity'], 'field_tags');
    $current_node = (arg(0) === 'node' && is_numeric(arg(1))) ? arg(1) : '';
    $tags = array();

    // Alter view to set TID filter and pager
    $view = views_get_view('list_control');
    $view->set_display('block_1');
    $view->set_arguments(array($current_node)); // Remove current NID
    $view->set_items_per_page($pager_count); // Set pager Items
    $view->pre_execute();
    $view->execute();

    foreach($node_tags as  $node_tag) {
      $tags[] = $node_tag['tid'];
    }
    //Set filter values base on $tags array
    $filters = $view->display_handler->get_option('filters');
    $filters['tid']['value'] = $tags;

    // Return DS field.
    $field =  $view->render();

I managed to achieve this using the following

$view = views_get_view('list_control');
$view->set_display('block_1');
$view->set_arguments(array($current_node)); // Remove current NID
$view->set_items_per_page($pager_count); // Set pager Items

// Set filter based on $tags.
$filter = $view->get_item($display_id, 'filter', 'tid');
$filter['value'] =  $tags;
$view->set_item($display_id, 'filter', 'tid', $filter);
$view->pre_execute();
$view->execute();


How do you theme the taxonomy description field? I need to theme the description field on a taxonomy page. I've tried field--description.tpl.php with no success.

Also, do I also copy the contents of /modules/field/field.tpl.php as a default template?

The term description isn't a field, it's actually a property of the taxonomy term entity and doesn't have a theme/template associated with it.

It's built up in taxonomy_term_view() as a standard render array:

$build['description'] = array(
  '#markup' => check_markup($term->description, $term->format, '', TRUE),
  '#weight' => 0,
  '#prefix' => '
',
  '#suffix' => '
',
);

So to theme it you could write a preprocess function for the taxonomy term template, maybe something like:

function MYTHEME_preprocess_taxonomy_term(&$vars) {
  if (!empty($vars['content']['description'])) {
    $vars['content']['description']['#prefix'] = '
';
    $vars['content']['description']['#suffix'] = '
';
  }
}


Fatal error: Call to a member function extractFormValues() : Drupal 8 beta 14 I created a module with Drupal 8 beta11 which defines an content entity and a form (contentEntityForm) with custom submit callback.When I tried using the same module with Drupal 8 beta 14 it raise the following error.

  Fatal error: Call to a member function extractFormValues() on null in C:\xampp\htdocs\drupalbeta14\core\lib\Drupal\Core\Entity\ContentEntityForm.php on line 219

Form definition are like this:

public function buildForm(array $form, FormStateInterface $form_state) {

        $form['employee']['first_name'] = array(
            '#type' => 'textfield',
            '#title' => 'First Name',
        '#required' => true,

        );
     $form['employee']['last_name'] = array(
            '#type' => 'textfield',
            '#title' => 'Last Name',
        '#required' => true,

        );
  $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#name' => 'employee-data',
        '#submit' => array('::submitEmployeeData')

    );
return $form
}
// callback

public function submitEmployeeData(array $form, FormStateInterface $form_state){
     /some code here
}

After form submission it raises the error mentioned above.

I checked the contentEntityForm.php also on both beta11 and beta 14 and seems to have similar function definition for extractFormValues() function.

This question is old but I stumbled across this issue as well, so posting the solution for future googlers..

Basically, you need to init the form_state within the buildForm method with:

if (!$form_state->has('entity_form_initialized')) {
  $this->init($form_state);
}

I found this solution here: https://withpulp.com/blog/drupal-forms-api/#initialize-the-form-state

When extending the ContentEntityForm class the parent buildForm normally handles this for you, but if for some reason you choose not to extend the buildForm you will need to init the form_state yourself.


How to change page.html.twig depending on the content type I am viewing in Drupal 8? I was wondering how I would change page.html.twig depending on the content type of the node I am viewing?

For example I would like the title to be shown on pages with the article content type but be hidden on the site page content type.

Page title is available as a block, and you can control the visibility from there.

However, to answer your question, here's how to provide different template suggestions based on content type:

function YOUR_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
  // Try to get the node, so we can check if we're on the node page.
  $node = Drupal::request()->attributes->get('node');
  if ($node && $node->getType() == 'YOUR_CONTENT_TYPE') {
    $suggestions[] = 'page__NAME_OF_YOUR_TEMPLATE';
  }
}

This will allow you to use page--NAME-OF-YOUR-TEMPLATE.html.twig template in your theme only for specific content types.

You can read more about hook_theme_suggestions_HOOK_alter() here.


Shipping method and shipping service from a placed order Im trying to get the shipping method and the shipping service values after i place an order on a Drupal 8 commerce website so i can use it inside an email im sending the website's owner (not the receipt for the client). I know Swift email would be an option but i have to continue with what i have. So far the owner of the website does receive an email but i need to add more information to it like the shipping method and shipping service.

I've got as far as finding out that $order->shipments->entity  will give me, among other values, these 2 fields shipping_method and shipping_service.

Shipment {#4521 ▼
  #values: array:19 [▼
    "shipment_id" => array:1 [▶]
    "type" => array:1 [▶]
    "uuid" => array:1 [▶]
    "order_id" => array:1 [▶]
    "package_type" => array:1 [▶]
    "shipping_method" => array:1 [▼
      "x-default" => "2"
    ]
    "shipping_service" => array:1 [▼
      "x-default" => "PRIORITY_OVERNIGHT"
    ]

Where do I find the values of the shipping method value whose ID is 2 and the shipping service value whose ID is PRIORITY_OVERNIGHT?
Is there an easier way to get the shipping method and service from a placed order?

Since shipping_method is an entity reference field, you can call $order->shipments->entity->shipping_method->entity, to load the shipping method entity.

The shipping service is not an entity, but just a text field, so you can get the value by using $order->shipments->entity->shipping_service->value.

Hope it helps!


Remove the Argument from a views URL I have a view with an exposed filter using the hierarchical select module for taxonomy.

/browse?category=12345

On the same view, I have an argument which does the same thing.

/browse/12345

I want my users to navigate using only the select filter, but this doesn't support breadcrumbs and page titles like the argument does. I wrote a bit of code to inject the filter value into the argument, and that works fine, but the next time I change a filter and refresh the view, the URL changes to that previous value while showing the new value.

/browse/(term id of last selection)?category=(term id of new selection)
aka
/browse/111?category=333

How can I discard this url change and keep things how they work the first time?

function MODULE_views_pre_view(&$view, &$display_id, &$args) {
  switch ($view->name) {
    case 'resources':
      if ($display_id == 'page_1') {
        if ($_GET['category']) {
          $args = array($_GET['category']);
        }
      }
    break;
  }
}

The exposed filter form is always going to add a query string to the current URL as it's a simple GET form.

You need a form with a submit handler that redirects to the argument based path. You could do this to the existing exposed filter with hook_form_FORM_ID_alter or create a custom form and expose it in a block.

To make the existing form redirect you'd need to do something like:

function mytheme_form_views_exposed_form_alter(&$form, &$form_state) {
  $form['#method'] = 'POST';
  $form['#submit'] = array('mytheme_redirect_taxonomy');
}

function mytheme_redirect_taxonomy($form, &$form_state) {
  $form_state['redirect'] = '/browse/' . $form_state['values']['category'];
}


Trying to pass icon into the menu I am trying to use the icon API to pass an icon to the menu - I would use the icon menu module, but I want the icon to switch based on programmatic logic.

Here's what I have so far:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $icon = theme('icon', array('bundle' => "fontawesome", 'icon' => "envelope"));
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'title callback' => FALSE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => $icon . t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
        'options' => array('attributes' => array(
       'html' => true
       )),
  );
  return $items;
}

However this just seems to get the escaped icon HTML in the menu.

How do I get the actual item from the icon API?

Is there some way to tell hook_menu to pass everything as it is?

by hook_menu you are just registering a path to Drupal.

  Define menu items and page callbacks.

To get this printed with icon you can try contributed modules like

Menu Icons
Icon API

Icon API module is able to apply your programmatic logic


How to redirect a page to the custom location after form validation? I have a form with comment section. when the comment is given as empty it redirects to the page called /comment/reply. I have to change it to my custom path. how can i do this

You shouldn't really do it in validator. Redirect in submit handler, with code like:

$form_state['redirect'] = 'comment/reply';

For more details of form redirecting consult official documentation.


Why Recent log message is showing anonymous user? Whenever I do cron/clear cache, that activity are shown as anonymous in log message, while my login activity are shown with my name as shown in following image.

Should not be user be administrator's name instead of "Anonymous(not verified)" in case of cron? Is this by design or I am missing something in config? Thanks.

Running cron happens automatically when someone visits your site by default. Drupal does that automatically once every few hours to run certain cleanup/background tasks.

Additionally, cron jobs always run as anonymous user, that's why it is logged as that, even if you trigger it manually as admin.


How to insert table view inside another view? I have created a View and two display blocks inside the View and set the format to table on each.

like this:

I will display these two tables at the front page. Now I need to write a common  for both tables

For this may I need to use table view inside another view?

My tables looks like this

You should be able to put services view block reference into your members view block for example into Header / Footer. Then by overriding template for this view type view-view--<views_machine_name> you can easily add Bootstrap classes and wrap each table into specific container / wrapper.

In your main view click on button Add at Header section. Add Rendered entity - block and type in your second block block_machine_name (it means your second block needs to be added to some region with specific machine name).


Adding Placeholders for PHP variables When creating a query using db_query in my module I want to make sure it's as secure as possible. So I'd like to use placeholders in my 'WHERE' clauses. The problem I'm having is how to use placeholders when the array values to be used are PHP variables. So for example:

WHERE el.field_experience_level_value='$level'

Is what I'm normally using and it works fine. But then I changed it to the following and added the array part at the end like so:

WHERE el.field_experience_level_value=':level'
...some more code
array(':level' => '$level')

I get no error but it doesn't return those results. So my main question is, how do I add a php variable such as $level above (already defined in previous code, not here) to a placeholder?

Better to use PDO for DB related operations in Drupal like db_select(),
db_insert(), db_update() and db_delete().

Here you no need to worry about place holder and other injections.

Ex:
   $result = db_select('node', 'n')
    ->fields('n')
    ->condition('nid', $node->nid,'=')
    ->condition('status', 0,'>')
    ->condition('uid', array(1,5,7),'IN')
    ->execute()
    ->fetchAssoc();

Note from db_query() API page : Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.

Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.


Taxonomy Term header image I created a field for taxonomy terms called "Category Image". I am overriding the taxonomy term pages /taxonomy/term/% using views. The only way to add the "Category Image" on top of a page is to add the relationship Content: Taxonomy terms on node so I can have the category image field that I produce excluded from display and rewrite it on the header.

The problem with this solution is that I have multiple duplicates on my term page's nodes.

Any solution is appreciated.

I think https://www.drupal.org/project/taxonomy_display has the option to render the term in a certain view mode and then render a view below it. You should check it out.


How to tokenize a value in a custom field formatter for views? I am using an custom field formatter for a view field like this:

function custom_fields_field_formatter_info() {

  return array(
    // the key must be unique, so it's best to prefix with your module's name.
    'custom_fields_breadcrumbs' => array(
      'label' => t('Breadcrumbs'),
      'field types' => array('entityreference'),
    ),
  );
}

/**
* Implements hook_field_formatter_settings_form().
*/
function custom_fields_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {

  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
   if ($display['type'] == 'custom_fields_breadcrumbs') {
    $form = array();
       $form['active'] = array(
      '#type' => 'textfield',
      '#title' => t('Mark as active'),
      '#description' => t('You can specify a node id, which should have class "active". Yo can use replacement tokens.'),
      '#default_value' => $settings['active'],
      '#size' => 4,
      '#maxlength' => 128,
      '#required' => FALSE,
    );
  }
    return $form;
}
function custom_fields_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
     case 'custom_fields_breadcrumbs':
      $ids = array();
      foreach ($items as $item) {
        $ids[$item['target_id']] = $item['target_id'];
      }
      $items = array();
      // http://api.drupal.org/api/drupal/modules!node!node.module/function/node_load_multiple/7
      $items = node_load_multiple($ids, array(), FALSE);
      foreach ($items as $delta => $item) {
        $label = $item->title;
        // modeled after entityreference_field_formatter_view() in entityreference.module
        if ($display['settings']['link'] && ($uri = node_uri($item))) {
          $otpions = array();
          if (isset($settings['active']) && $delta == $settings['active']) {
            $otpions = array('attributes' => array('class' => array('active')) );
          }
          $element[$delta] = array('#markup' => l($label, $uri['path'], $otpions));
        }
        else {
          $element[$delta] = array('#markup' => check_plain($label));
        }
      }
      break;
  }
  return $element;
}

Everything works as expected, but I want to be able to use replacement patterns for my custom setting $settings['active']. How do I do this?

I think, I have to use the method:

tokenize_value()

from the views object. But I don't have the views object within the hook, haven't I?

I found out how to do this. We have the views object via the parameter "display", so we can use:

$display['views_view']->style_plugin->tokenize_value($settings['pager']['active'], 0)

to tokenize a field value.


Can I automatically regenerate all images after using Drush image-flush? I used drush image-flush to delete all generated image style images on my site.

I know that image style images are automatically regenerated when you try to view them in a browser, but is there a way to "prime the cache" and automatically regenerate all image styles for all images after they have been deleted?

I usually see people using wget or httrack for this - request every page in your site, and all of the images will be regenerated. Not very sophisticated, I know.  As far as I know, though, there is no Drush command to do this.


Field Validation and Highlighting How can I get custom Form API validation to highlight a field the same way the failed #required validation does?  (See attached graphic)

Note Graphic:

1) (Green Line) Company Name is empty.  '#required' Error is noted and field is highlighted red.

2) (Blue Line) Website is incorrect.  'Custom Validation' Error is noted, but field is NOT highlighted.

How can I automatically highlight the 'Website' field on validation fail and remove it upon success?

Currently using: form_set_error('', t('Your website address is incorrectly formatted.'));

See

As the first parameter to form_set_error(), pass the name of the field to be highlighted. If it's a nested structure, pass it with square brackets, like so:

form_set_error('[your][nested][field]', 'Your Error Message');

There's a convenience wrapper around this, form_error, which takes the element instead of the string, like so:

form_error($form['your_field'], 'Your Error Message');

Also see the docs to form_set_error() (d7).


How can I remove nodes? How can I remove nodes using Drupal Console?

Drupal Console is for creating boilerplate code (also known as scaffolding) rather than for general administration and day-to-day work.  You can see an overview of the features of Drupal Console:

How does Drupal Console help?

To delete a node you would be advised to use drush which is a general purpose DRUpal SHell. Drush doesn't have a command to do this out of the box but there are a number of different approaches outlined in this post,
Can I delete nodes of a given content type with Drush?


how to update order status in shopping cart to checkout Here is my code for updating order status in shopping cart to Checkout: Checkout. After running no error but it does not show order status as Checkout: Checkout.

function commerce_services_order_checkout_update($order_id,$data, $flatten_fields) {
    $status; $message;

    $status = $data['status'];

    $order = commerce_order_load($order_id);
    $order = commerce_order_status_update($order, "Checkout: Checkout");
    if($order != null){
        $status = 1;
        $message = "Order status set to checkout successfully.";
    }else{
        $status = 0;
        $message = "Order status can not set to checkout.";
    }

   $reply= (array('status' => $status,'message' => $message, "order status ". $order));

    return $reply;
}

Any suggestion is greatly appreciated!

Thanks

This is your problem:

$order = commerce_order_status_update($order, "Checkout: Checkout");

You should be passing the machine name for the status

$order = commerce_order_status_update($order, 'checkout_checkout');

See this API doc page on drupalcontrib.org: http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!order!commerce_order.module/function/commerce_order_status_update/7


How to adapt the date format in the admin/content page? Each Article shows "Authored on YYYY-MM-DD" date per configured regional date format. e.g. 2015-05-14 00:00:00 +0100

However, the content listing at admin/content shows the UPDATED date as MM-DD-YYYY unlike anything else and is confusing to admins.

Users have no choice of Default Time / Region on the Drupal 7.37 site.
Date and Time Long, Medium, Short formats are all ... YYYY-MM-DD

Date (and time) formats can be configured via admin/config/regional/date-time. It can be used to specify the format for data types Long, Medium and Short.

Other tabs that are available on that same page:

Formats (to define your own custom formats).
Localize (for language specific tuning).
Date Views (for date views specific to "day", "week" or "month").


How do I update weight using Rules? I am creating a sampler pack of all my products. I have a product display with several node reference fields (not product reference) so that whenever a new product is added, that reference field is updated.

I have Rules set up to automatically price those selections (each selection has a different price).

Now I'm trying to use Rules to update that line item's weight (for use with Commerce UPS). However, I can't seem to find a way to update the weight. Is this possible in Rules? Or am I going about this in the wrong way?

You'll have to add a condition to your Rule.

Make an "Entity has field" condition that checks for your weight field.

You'll now be able to use that data value.


Compare form input with user password in drupal 7 I'm trying to compare the user password from different databases so users of other drupal sites can also login.
I'm switching from the main database to other databases and then trying to compare the passwoord input field to the stored hash value.

I did not found a answer on this site maybe because my situation is a bit different.

I did found this question and tried user_check_password() and user_hash_password()
 returns nothing and user_hash_password returns a new hash every time I run it so I don't think I can use that to compare that to the stored value in the database.

If I copy the user from the other database and save it to the main database user_check_password() does work. While I don't like this it does work…

If you have a better answer please submit it.


Computed field module: value of field when creating new content for my content type I have this computed field code and when I update existing node everything is ok, but when I create new node, menu_get_object return empty values and drupal display this error message "EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7562 of /var/www/dev/testpage/includes/common.inc)." and nothing was saved. When I used dpm() in devel it show me that after creating new content $node is empty, but when I update node created before everything is OK.

$node = menu_get_object();
$start_time = field_get_items('node', $node, 'field_start_time');
$start_time = $start_time[0]['value'];
$entity_field[0]['value'] = '$start_time';

thanks a lot for your reply

menu_get_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu_get_object() will return that.

From: http://api.drupal.org/api/drupal/includes!menu.inc/function/menu_get_object/7

It returns empty upon creation because you add the node from "node/add/[content-type]" page but update it from "node/[nid]" and it can use the nid to load the node.

If you need just to duplicate the value from the start_time field of the same node, use this:

$entity_field[0]['value'] = $entity->field_start_time[0]['value'];


How to add JS to the search form? <?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'search_form') {

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

  }

}

Doing a dpm($form) on the search form, I see it has the my attached library, so what gives?

Solution:

The above code works fine, turns out it was my js code, I had copied over from another js file and it had an if statement that somehow I missed (it was 4 am). Credit @Alexei Rayu

In Drupal 8, you first need to define assets in a library in your theme or module: https://www.drupal.org/developing/api/8/assets

and then you can attach that library to your form like this:

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


How to force a JS library to be loaded via HTTPS? How can I force a js library to always load only via SSL?
Specifically, I want to get Drupal to always load stripe.js with SSL, because stripe.js refuses to load over http (you get a 403 FORBIDDEN error).
I'm loading stripe.js through the Commerce Stripe module.
commerce_stripe.libraries.yml looks like this:
stripe:
  remote: https://github.com/stripe/stripe-php
  version: "4.3.0"
  license:
    name: MIT
    url: https://github.com/stripe/stripe-php/blob/master/LICENSE
    gpl-compatible: true
  js:
    "https://js.stripe.com/v3/": { minified: true }

So I thought this would be sufficient to always load via SSL.
On my production site, for which all the assets are SSL, everything works.
On Lando, my local development environment, everything is fine when I access my site from a browser installed on my machine, even when the connection to the locally hosted website is http (connection to my dev site is http, connection to stripe.js is https).
However, when using the Standalone Chrome Debug docker image to test my site with Behat, stripe.js doesn't load. I get a 403 FORBIDDEN error because the Chrome browser in the Standalone Chrome Debug container tries to load stripe.js via http.
From the Chrome browser with the problem, this is what the <script> tag looks like for stripe.js:
<script src="//js.stripe.com/v3/"></script>

I'm not sure exactly why I am having this problem only with the Standalone Chrome Debug docker image, but I suspect it is because I cannot access my site via https from the image at all. However, in the browser, I can open other SSL sites such as https://www.google.com and perform a search without any problems.
So,

If I am accessing a local installation of Drupal via docker from inside a docker container
And I do not have access to the Drupal installation via HTTPS
Is it impossible to load a third-party js library (stripe.js) via HTTPS?

The reason I'm confused is that I can load stripe.js locally when accessing my site via a browser in Windows (my dev machine) through http, but in the Docker container (standalone-chrome-debug), accessing my local dev site through http gets a 403 forbidden for stripe.js. (When I manually type the stripe.js library link into the browser, I can download the library, so the problem only occurs with the link/connection generated by Drupal.)

That's a protocol relative include, meaning it will take the current protocol and use that. If you access via http, that's what you would get. Is the site being tested under https? Is something removing the protocols (advagg?)?
Modules like advanced aggregation have settings to remove protocol and make all links protocol relative. Disable settings like that and run the tests again.


Service module user update request payload I am using postman to update user. Please suggest me what headers need to be send and what should be the payload structure in JSON format.
Should I send user object in params OR in body in postman.

To update a user with the Services module, utilize these:

HTTP Method: PUT

URL: ?q=[endpoint-name]/user/123.json

Headers

Content-type: application/json
X-CSRF-Token: use value available from ?q=services/session/token

Data payload:

{
  "uid":"123",
  "mail":"new-email-address@example.com",
  "current_pass":"superSecret"
}


How do you programmatically enable a payment method? I have enabled the payment method module I want to use.  I am using Authorize.net.

However, by default it is disabled in the Payment methods listing.

In my module, I want to enable the payment method module for use when my module is installed.

Just update the rules_config entity.

$config = rules_config_load('name_of_your_rules_config');
$config->active = 1;
$config->save();

If you are not sure what the name of your rules config entity is run:

$configs = entity_load('rules_config');
foreach($configs as $config) {
  dpm($config, $config->name);
}

This will list all rule config entities that you have.


query API calling db_query result a non-object, but SQL works I query my database using the following query API code, but Drupal tells me that the result is a non-object. I can't find any reason to it

in what situation does db_query return anything but?

The error:

  Fatal error: Call to a member function execute() on a non-object

the code:

for ($counter = 1; $counter <= 12; $counter++) {
  $query[$counter] = db_query("SELECT `foo` FROM `{bar}` WHERE DATE(FROM_UNIXTIME(`thing_$counter`)) = CURRENT_DATE");
  $results = $query['$counter']->execute()
    ->fetchAll();
}

The SQL works and produced results when I ran it in PHPmyAdmin.

The answer in this exchange looked tantalizing:

$date = date_create();
$date_to_test_against =  $date->format('U');
 $query[$counter] = db_query("SELECT `foo` FROM `{bar}` WHERE `thing_$counter` = $date_to_test_against");

however that produced the same result, calling execute on a non-object.

I know I don't have enough experience with this API yet. Can someone please point me to what I'm missing?

In the case of db_query, what you get back from it is a resource (it is just a wrapper around php's mysql_query.

But the answer depends on if you're in Drupal 6 or 7

Drupal 6:

In order to turn that into an object, you need to run db_fetch_object on the result, and if you have multiple results you'd need to loop through it.

For example:

<?php
    $sql = "SELECT buckles FROM foo WHERE llama = 'cheese'";
    $result = db_query($sql);

    while ($rowObj = db_fetch_object($result)) {
        echo $rowObj->buckles;
    }

Drupal 7

Use the nifty db_select api! The examples on that page pretty good, but basically it builds a query and then returns something that's very similar to a PDO object (see SelectQuery::execute for the following example)

<?php
  $matches = array();
  $query = db_select('table')
     ->fields('table', array('field_name'));

  foreach ($query->execute() as $row) {
     $matches[$row->relation_type] = $row->label;
  }


theme variables in array I try to rewrite

return theme('table', array('header' => $header, 'rows' => $rows, array('variables' =>$my_vars));

into:

$build = array();

$build['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows);

 $build['variables'] = array(
'variables' =>$my_vars);

 return $build;

But it does't work:

$build['variables'] = array('variables' =>$my_vars);

How can I do this?

Since the second argument of theme() is an array, you are writing code for Drupal 7. In that case, theme('table') doesn't use any array item whose index is an integer. The only array indexes you should pass as second argument to theme('table') are the following:

header
rows
attributes
caption
colgroups
stricky
empty

Since you are using array('variables' =>$my_vars) it could be you are trying to set attributes, but in that case the array should be an array of HTML attributes, or colgroups, and in that case the array should be similar to the following one.

$colgroup = array(
  // COLGROUP with one COL element.
  array(
    array(
      'class' => array('funky'), // Attribute for the COL element.
    ),
  ),
  // COLGROUP with attributes and inner COL elements.
  array(
    'data' => array(
      array(
        'class' => array('funky'), // Attribute for the COL element.
      ),
    ),
    'class' => array('jazzy'), // Attribute for the COLGROUP element.
  ),
);

If you are trying to set attributes, your code should set the $build variable as following.

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => $my_vars,
);

Replace '#attributes' with '#colgroups' to set colgroups.

In the case theme('table') accepted variables (which could be the case if a module overrodr the default implementation of the theme function), then the code should be similar to the following one.

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#variables' => $my_vars,
);


Migrated data via XML doesn't import to nodes Link to my previous question, which has info on data structure etc.

Now I've gotten my XML read into Migrate and content type and fields set up right (I think), but now I can't get the nodes to save. The import has the correct number of nodes, but they don't ever get imported. The wine examples in the documentation didn't say anything about using prepareRow() or anything when you are using XML. Where are my nodes? Can I pull out that data with Views even if nodes don't import? My end use for this is to arrange everything with Views.

EDIT

Here is my class:

<?php

class ItemNodeMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('itemnode', array('default')));
$this->description = t('Grab data in XML');

// There isn't a consistent way to automatically identify appropriate "fields"
// from an XML feed, so we pass an explicit list of source fields
$fields = array(
   'id' => 'ID',
   'type' => t('Description of producer'),
   'Owner' => t('Owner'),
   'Text' => t('Text'),
   'modifiedAt' => 'Date last changed',
);

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'id' => array(
      'type' => 'varchar',
      'length' => 6,
      'not null' => TRUE,
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

// This can also be an URL instead of a file path.
$xml_folder = 'http://example.com/item/';
$list_url = 'http://example.com/CompanyID/Items.xml';
// Each ID retrieved from the list URL will be plugged into :id in the
// item URL to fetch the specific objects.
$item_url = $xml_folder . ':id/desc.xml';

$this->source = new MigrateSourceList(new MigrateListXML($list_url),
  new MigrateItemXML($item_url), $fields);

$this->destination = new MigrateDestinationNode('migrate_module_itemnode');

$this->addFieldMapping('id', 'id')
     ->xpath('/@id');
$this->addFieldMapping('body', 'Text')
     ->xpath('/Text');
$this->addFieldMapping('type', 'type')
     ->xpath('/@type');
$this->addFieldMapping('owner', 'Owner')
     ->xpath('/@Owner');
$this->addFieldMapping('created', 'modifiedAt')
     ->xpath('/@modifiedAt');

}
}

EDIT2:
I have determined that my problem lies here:

    $this->map = new MigrateSQLMap($this->machineName,
         array(
                 'id' => array(
                 'type' => 'varchar',
                 'length' => 6,
                 'not null' => TRUE,
               )
         ),
         MigrateDestinationNode::getKeySchema()
    );

This isn't correctly mapping to my source's ID, which lies at Item/@id. How can I correct this?

As per this issue -- I think you need to tell MigrateSourceList where your item id's are, as an example (from isssue):

    // As with MigrateSourceMultiItems, this applies where there is not a separate
    // list of IDs to process - the source XML file is entirely self-contained.
    // For the ID path, and xpath for each component, we can use the full xpath
    // syntax as usual. However, the syntax to select the elements that correspond
    // to objects to import is more limited. It must be a fully-qualified path
    // to the element (i.e., /producers/producer rather than just //producer).
//  $item_xpath = '/producers/producer';  // relative to document
    $item_xpath = '/FMPXMLRESULT/RESULTSET/ROW';
//  $item_ID_xpath = 'sourceid';          // relative to item_xpath
    $item_ID_xpath = 'COL[1]/DATA';

    $this->source = new MigrateSourceXML($items_url, $item_xpath, $item_ID_xpath,
      $fields);

You only have 3 values in your constructor. I haven't done alot with migrating XML (just CSV and SQL). This issue is for D7 -- I think it should apply to D6.


change quicktabs default tab according to current documentation of for change alter quicktabs should use this method
in my module

mymoule_quicktabs_alter(&$quicktabs){
    $quicktabs->default_tab=2;
   }

when i print result with dsm  it changed applied, but it not apply to visual output of quicktabs.

tell me how i can change quicktabs default tab ?
tnx

Its not done simple, by default quicktabs ordered by wieght,
Quicktabs has quickly become one of my favorite Drupal modules of all time. To think that I was actually wasting time creating tabs by using jQuery plugins, and writing custom AJAX. Creating tabbed content is one of the most popular techniques used on the web today, and with Quicktabs it has never been easier to add tabs to your Drupal site - even with AJAX!

First you'll want to install Quicktabs

Once you have Quicktabs installed, there are a couple of ways to generate tabs. You can do it through the Drupal interface, or you can do it programmatically, but first, make sure you have some content that you want to show in tabs! Quicktabs works with your existing content. You can tab between views, blocks, nodes, or a mixture of these.

For this demo, we'll use Views and set up 2 displays filtered by a certain taxonomy term. We will then create a tab that displays nodes of each taxonomy term respectively. Make sure you have some taxonomy terms to choose from for each post. Then you'll want to create a view called "my_listing", or whatever makes sense for you.

Once you have created your View, create a couple of different "page" displays. Name each display according to your taxonomy term, so if you want to tab between say "Development" and "Theming" nodes, each page display will be named respectively.

Since you're creating page views, you'll have to specify a URL for each under the Page Settings section. You can use something like "list/development" and "list/theming" respectively. This is required by page displays, but it is also good if a user for some reason does not have javascript enabled, they will still be able to see the listings, just not through AJAX.

Also, for simplicity, make "Row style" node, so we don't have to play with fields.

Under "Filters" filter on each display for that specific taxonomy term, so that each display is only displaying nodes of whichever taxonomy you choose. Save the view.

Now that you have some content to play with it's time to create some tabs. Browse to admin/build/quicktabs and click on the "New QT block tab".

By default, Quicktabs creates a block for you which you can then place anywhere in the site like a regular block, but there is also a way to output your quicktabs in code, which i'll show you further down.

In the Block Title field, give your block a meaningful title. Next is the style dropdown, where you can select between various styles of tabs. You can also select "no style" so you can theme them your own way

The next field allows you to select whether or not you want your tabs to be AJAX. In most cases you will want to use AJAX so that you only load the second view when the user requests it.

The "Hide empty tabs" will only work if you do NOT use AJAX, which is kind of unfortunate. But, an easy way to deal with this is to use the "empty text" area in your views to give the user a friendly "There is no content here" message.

The next section is where you will start creating your tabs

Let's say the view you created with the 2 page displays are for a taxonomy term "Development" and one for "Theming". Give each tab their respective title. For the Tab type, select "view". In the tab content section, select the view you created (my_listing). Then select the display you want to show. For the Development tab, show the display that filters on Development. For the Theming tab, show the display that filters on Theming. You can also pass arguments into your Quicktabs to use with Views that accept arguments which is really cool, but I won't be covering that here.

Click save. You now have a block available for you to place anywhere on your site, that will tab between nodes of each taxonomy term! Very cool! But, what if you dont' want to use a block...what if you want a bit more control to place these tabs wherever you want? It's easy.

On your tabs listing page (admin/build/quicktabs) hover over the 'edit' link and take note of your quicktabs ID in the url. (quicktabs/1/edit). If this is your first quicktab, the ID will be 1.

Now to print out your quicktabs, all you need to do is call this function and run it through theme("quicktabs"); like this:

$tabs = quicktabs_load(1); // where 1 is your quicktabs id
$mytabs = theme("quicktabs", $tabs);

return theme("my_custom_template", $mytabs);

Then in your custom template, just print out the mytabs variable and you should see your quicktabs!


Render chart with data from Views PHP custom field How to render a Column Chart using data from Views PHP custom field (BAR Number (PHP custom) in the screenshot below)?

I am trying to achieve a Column Chart; with each bar in the chart being distinct count number of "bar number".

I have tried using aggregation (with charts module chart add-on enabled), but does not give option to aggregate/count on PHP custom fields.
have tried Google Chart Tools module, but again it does not consider PHP Views custom fields for Grouping.

Just for more information on what I am trying to achieve, please refer below Requirement screenshot!

Thanks in advance!

A work around for issue 1. & 2. Add Bar number as a field to each study node. Then add field to view, and aggregate.

How exactly is the Bar Number being calculated? You could use Rules to calculate this value when node is saved and save the calc number to your Bar number field. If there is no calculation, then ignore this part.

Use field permissions to not allow certain roles to change the value of this field, if needed.

Add a new field called Bar Number (machine name: field_bar_number) to your study content type.

You can create a custom module.

mymodule.info

name = My Module
description = Makes calculation for Bar Number field in Study content type.
package = Custom
version = 7.x-1.0
core = 7.x

mymodule.module

/**
 * Implements of hook_node_presave
 */
function MYMODULE_node_presave($node) {
  if ($node->type =='study') {
    // calculates bar number
    $node->field_bar_number = $node->some_field - $node->other_field;
  }
}

Use Views Bulk Operations and set title = title, and save again all your 500 nodes. As your custom module makes the calculation and sets the bar number before the node is saved. VBO Tutorial.


Show initially 4 fields for Text field with unlimited value I am building a website using Drupal 7. In my website there is a form for user to add some content.

In the form there is a field of type "Text Field" (core). The "Number of values" for this text field is "unlimited". Thus, when the form appear in the first time,there is only one text field and a button- "add another item". Then users can add more items / fields just by clicking on the button. the problem is that every clicking takes time to process, and this is not best-practice for my opinion.

I want that always will appear at least 4 fields on the form (and not one). If the users will want, they will be able to just click on the button and "add another item" (regularly).

How can I can display 4 text fields (and not only one)?

here is a screen-shot for example:

Check Multivalue Settings Module

  Warning: this module is still very buggy. Actually, it only works in
  very few use cases. I suggest to only attempt using it with core
  fields (not fields from contrib modules). Even this may not work. I'm
  working on fixing things, but don't have much time. Help is welcome.

Functionality:

Number of values allowed
Number of values required
Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra)

Though the module is buggy but can be a good starting point for building a custom solution or patching the same module.


Can't get Corresponding node references to work I installed the 'Corresponding node references' module to avoid double editing between nodes that should point to each other (by means of node reference fields). I have followed the instructions to first create nodes with node reference fields and manually editing these fields so that node A point to node B. Then  I checked the box in the modules settings page on admin/config, that indeed showed this correspondance.
But I still have to double edit nodes of these same types. The "other" node is not automatically updated with a reference...
Any suggestions? The site is Drupal 7.42.

Solved! It turns out that CNR does not support other languages than English in the stable version. I just installed the dev version and now it works wonderfully. Thanks for maintaining this useful module!


Using IN clause in db_query I can't figure out how to add an IN clause in my query, using placeholders.

I'd want it to be something like:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN :nids', array(':nids' => $nids));

Can't find any documentation on this simple task. What's the proper way to achieve this?

You are missing the braces.

Try this:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN (:nids)', array(':nids' => $nids));

For more information, see http://drupal.org/node/310072, especially the chapter on Placeholder arrays:

  Placeholder arrays

  Drupal's database layer includes an extra feature of placeholders. If the value passed in for a placeholder is an array, it will be automatically expanded into a comma separated list as will the corresponding placeholder. That means developers do not need to worry about counting how many placeholders they will need.

  An example should make this behavior clearer:

<?php
// This code:
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144));

// Will get turned into this prepared statement equivalent automatically:
db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array(
  ':nids_1' => 13,
  ':nids_2' => 42,
  ':nids_3' => 144,
));

// Which is equivalent to the following literal query:
db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");
?>


Quicktabs and views to create tabbed views I see that quicktabs uses blocks as tabs.  This is fine if i create 4 views blocks for 4 single items of a content type and then add them to quick tabs manually.

Is there a workaround to show the latest 4 items of a certain content type using quick tabs and views?

Thanks,

Is this not just a matter of editing the view block to show four items rather than one? Under "Pager" in the view, select "Display a specified number of items" and then the quantity you prefer.


Passing variables via template.php for search module I'm using search.module. I used dpm(get_defined_vars() ); in my search-results.tpl.php file to see all returned variables, so I can reference a needed variable in some PHP code I'm writing in there.

However, although the variable is being returned in the teaser/snippet (and is outputting to the page) the only place I'm finding the 'variable' is in the $search_results array which is just a massively long string of html code. How can I parse out a needed variable (I assume in template.php) so that I can reference it and use it for comparisons on search-results.tpl.php?

The content is coming from a content type node called 'resource'. The field in questions is called 'field_type'. Here's the code I'm currently working with in template.php to get other variables:

function themename_preprocess_search_results(&$variables) {
        foreach($variables['results'] as $result) {
                $node = $result['node'];
                if($node->type == 'resource') {
                      $items = field_get_items('node', $node, 'field_type');
                      $variables['field_type_items'] = $items;
                      $variables['field_type_item'] = $items[0];
                      $field_view = field_view_field('node', $node, 'field_type');
                      $variables['field_type_rendered'] = render($field_view);
                }
        }
}

// function to enable correct variables for search results
function themename_preprocess_search_result(&$variables) {
  $variables['search_results'] = '';
  if (!empty($variables['module'])) {
    $variables['module'] = check_plain($variables['module']);
  }
  /*foreach ($variables['results'] as $result) {
    $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
  }*/
  $teaser = node_view($variables['result']['node'], 'teaser');
  $variables['teaser'] = $teaser;
  /*
  $variables['body'] = substr(render($teaser['body']), 0, 200);
  if (strlen($variables['body']) >= 200) {
    $variables['body'] .= "...";
  }
  */
  $variables['snippet'] = drupal_render($teaser);
  $variables['info'] = '';
  $variables['pager'] = theme('pager', array('tags' => NULL));
  $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'];
}

Is there something I can add to this to get the field field_type and pass it to my tpl files?

Or, if that's not the right solution, what is?

Adding fields programatically

Use plain old dpm($variables); in your search-results.tpl.php file to check variables.

And yes, the preprocess function is where to add in extra information, you can use something like:

$variables['custom'] = field_view_field($entity_type, $entity, $field_name)

field_view_field prevents you from having to load the whole node and takes care of languages etc for you.

Adding fields in the UI

Go to the Manage Display tab for the content type in question and scroll down to CUSTOM DISPLAY SETTINGS.

Turn on the Search result checkbox and save, then go to the Search Result sub-tab.

Arrange your fields how you wish them to show in search results - note that fields aren't available to the template file unless they are displayed in the Manage Display tab, this might be the root cause of your problem.


Using #states to disable a field collection field I am trying to disable a date field's second value, inside a field collection, but it isn't working.

My hook_form_alter has this:

  $form['field_certification']['und'][0]['field_validity']['und'][0]['#states'] = array(
        'disabled' => array(
          'input[name="field_certification[und][0][field_auto_calculate_validity][und]"]' => array('checked' => TRUE),
        ),
      );

The HTML for the date field is here:

<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-certification-und-0-field-validity-und-0-value2-datepicker-popup-0" name="field_certification[und][0][field_validity][und][0][value2][date]" value="07/23/2014" size="20" maxlength="30">

The checkbox is here:

<input type="checkbox" id="edit-field-certification-und-0-field-auto-calculate-validity-und" name="field_certification[und][0][field_auto_calculate_validity][und]" value="1" class="form-checkbox">

Could it be because I'm not specifically selecting the (second) value of the date field?

My original answer totally missed the point (apologies), this is updated version:

I do not think you can use Drupal's form api #state property to accomplish what you would like. States can be used to hide, reveal and disable whole form elements, such as a fieldset, text input or date field, but you aim to disable one part of a single (contrib) element (ie the second value of a date_combo field provided by the date module).

There are two possible solutions:

load your own jquery when the form is loaded, and add a change() function to disable the relevant date field component
separate the start/end dates into separate date fields and use the drupal #states functionality (as above) to disable the (whole) second date field:

$form['field_certification']['und'][0]['field_validity']['#states'] = array(
'disabled' => array(
    ':input[name="field_certification[und][0][field_auto_calculate_validity][und]"]' => array(
        'checked' => true
    ),
)

);

I hope this helps, I played around with it on a blank d7 install, and this was the only way I could get your intended functionality to work.


How do I force a 403/410 error code for specific users and content? I have a content type in a Drupal 6 site that allows the creator of a node to mark the node as "withdrawn"; he can still see it, but attempts by others to see it are caught and redirected somewhere else, like their user page.

So far so good, but I'm concerned about what happens when search bots show up looking for the node; they get a 302 response from the server and are then redirected to the "somewhere else" page with an http code 200. What ought to happen (I think) is that the request by Googlebot for the node should result in a 403 or 410 error code, causing (eventually) the page to get dropped from the Google index. So I'd like to have the page generation work just like it is, except with a 401/410/whatever getting sent back as the response to the initial request.

I've tried putting some header() calls into the part of the code that detects the disallowed access, but they're not working, presumably because I'm too far along in the page construction by the time that call happens for the new header information to matter.

Is there any way to get this error code generated while still getting the user to the page I want them to be at?

drupal_goto Can help you

drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

Parameters

$path:
A Drupal path or a full URL.

$query:
A URL-encoded query string to append to the link, or an array of query
key/value-pairs without any URL-encoding. Passed to url().

$fragment:
A destination fragment identifier (named anchor).

$http_response_code:
Valid values for an actual "goto" as per RFC 2616 section 10.3 are:

301 Moved Permanently (the recommended value for most redirects)
302 Found (default in Drupal and PHP, sometimes used for spamming search
engines)
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect (alternative to "503 Site Down for Maintenance")

Note: Other values are defined by RFC 2616, but are rarely used and poorly
supported.


Drupal 7 force active menu item I got a page where I link to in the menu bar. On this page there is a custom module. On this page there are items from anothor database where the user can click on. When they click on it they go to another page with more information. When they are on the second page there is no active button in the menu bar. On the second page I also have a custom module.

How can u force a button in the menu bar to have the .active class or in another way so that it haves the active lay-out button.

I use Drupal 7.

The Menu position module will solve your problem.

  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.


Disable modules when browsing mobile site I have a site that also serves its content to mobile devices. As these sites(desktop/mobile) uses same code. I have a problem in performance since the modules being used in desktop site is also loaded in mobile site even if I'm not using it. Is there a way to excludes those modules(custom/contrib) without hacking each modules? Any good idea in this kind of situation?

Hi Patrick...something like this code I created so far...but I'm not sure if this is feasible.

function array_search_regex($pattern, $array) {
        for($x = 0; $x < count($array); $x++) {
            if(preg_match($pattern, $array[$x])) {
                return true;
            }
        }
      return false;
  }

  //Collect all css and place in an array
    $get_all_css = array();
    $get_all_css = drupal_get_css();

    //Put the return html styles in an array
    $ret_all_css = explode("\n", $get_all_css);
    //Get the array index of the matched in the search
    //$lookup_css = array_search('<link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?G" />', $ret_all_css);
    $lookup_css = array_search_regex("/<link type=\"text\/css\" rel=\"stylesheet\" media=\"all\" href=\"\/modules\/node\/node.css\?.\" \/>/", $ret_all_css);

    //Unset the searched styles.
    unset($ret_all_css[$lookup_css]);

    //Return all essential styles. This should replace $styles in page.tpl.php
    $styles = implode("\n", $ret_all_css);

The load caused by modules is handled by the server, so merely having the modules enabled will not affect the performance of your mobile site.  In any case, it is impossible to disable the modules because you could be serving web pages to both mobile and desktop machines at the same time.

Instead, what you want to do is add a mobile theme.  There are lots of ways to do this but the Mobile Tools module is a good way to get started.

For a more specific solution, you'll have to identify which modules are causing the performance problems on your site so that workarounds can be found.


When is taxonomy appropriate If I, hypothetically, ran a business and kept data on products, part data related to those products, and service procedures for those products would it make sense to fit this into the Drupal taxonomy? Is that the Drupal way?

I'm just getting going on Drupal; I have an existing working php application that I shoved into a module without really making use of Drupal functions, to the extent that I even have a separate database. My app uses some non-trivial database organizations, lots of database views and heavy usage of inner joins. This app will be a suite of apps that will also include standard web functions, which I why I want to use Drupal/CMS. But I don't know if I should my module data into taxonomies.

Edit: 99% sure that entities will do what I need, searching on that now.

Taxonomies are best used to define properties that:

are shared across multiple content items;
need to be grouped with similar properties.

For instance, if you're selling t-shirts, the taxonomy terms 'blue', 'red' and 'yellow' are grouped in the 'color' vocabulary. By tagging all t-shirts of the same color with the same taxonomy term, you define a relationship between those t-shirts. This makes it very easy to generate a page showing all blue, red or yellow t-shirts.

Taxonomy terms, like many other entity types, are 'fieldable', which means that you can add fields to them to contain data. For instance, if you add an image field to the taxonomy terms in the 'color' vocabulary, you could define an example image for each color term.

If this example with t-shirts and colors matches your use case, then the answer to your question is: Yes, taxonomy is the Drupal way to do it.

By the way, the word "entity" has a very broad meaning in Drupal. 'Taxonomy term' is a type of entity, just like 'node', 'user' and 'file'. Saying that "entities will do what you need" is like saying "building materials will allow me to build a house". It's a statement that (almost) can't be wrong. You need to answer the question: Which type of entity is best to solve this specific problem?


Users to choose how to view images Is it possible to offer viewers different options on how to view an image?

Currently, it just defaults to a flexslider that I have put as default on my image style.

Looking for instructions on how to achieve this functionality by using views.

I know there is a similar post here but that is WHILST creating the content type - I want the user to choose how to see a set of images after the images have been added to the website!

Use different view modes for your entity (node).  Each view mode (also called a build mode) can have different template (.tpl.php) files.  Use hook_entity_view_mode_alter to decide which view mode to use (based on your user's selection).

You can use the View Modes module to create custom view modes.


How do I read response headers? I have data in custom response headers that I need to read. I have looked in the Drupal API guide and there is a reference to Response::$headers, but I'm not sure how to exactly use this to read header data.

Edit - to further elaborate what I am trying to accomplish:

I have a form in a custom module that redirects some data in the headers to another page. Here is the code for that:

$response = new RedirectResponse('/path/destination', 302, array(
            "username" => "value"
          ));
$response->send();

The redirect is made successfully and the values that I'm pushing to the headers (illustrated by "username" above) are successfully transferred onto the response headers - I can see that with the browser inspector.

What I am now trying to do is read the values of those custom headers, i.e. "username", as a means of pre-populating the username field on my destination page (/path/destination).

As suggested in the answers, I have also done the following:

$response = new ResponseHeaderBag();
$response::get("username");

I also tried:

$response = new ResponseHeaderBag();
$response->get("username", $default = null, $first = true);

Even though I have both these inclusions on the top of my file:

use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

I get the following error:

Fatal error: Call to undefined method Drupal\module_name\Form\MyClass::all() in ../vendor/symfony/http-foundation/HeaderBag.php on line 113

Response::$headers is a public property, which means you can access it with $response->headers, where contains an object of the ResponseHeaderBag class or some inherited class of it.

Essentially, it means you can access the headers using either ResponseHeaderBag::all or ResponseHeaderBag::get($key).


How to create the equivalent of a spreadsheet? I don't want to start with too many unnecessary details on this one. I've got a stack of codes. Weekly more codes are added. On occasion these codes will be 'used' by other systems. These other systems are not Drupal sites.

I'm not sure how else to describe this, but all I want is the equivalent of a spreadsheet in Drupal: It should be possible to add rows, and delete rows of data on a single page, instead of creating a new node for every single code. I just want a table where I can add and delete codes, something like this, a CRUD table.

My current solution is this:

Build a table (my_codes (id, code) )
Create a CRUD for the table so someone can manually enter in new codes (one by one)
Create a REST for the crud so these other systems can use these codes (codes/list, codes/add, codes/delete)

However, the main site is in Drupal, and only certain users should be able to add codes.

What is the simplest way to achieve this goal?
I could do all this work in a block, but I'd prefer to just install a Drupal module. If I can achive #1 and #2 with a module, then I should be able to do #3 myself. Note that last time I looked at CCK it did not have a "table" option.

The TableField or the Slickgrid modules may help here.


Redirect to last page visited on 404 error Just wondering if there is a simple way to automatically redirect users to the last page they have visited if they receive a 404 error? I am using Drupal 7.

There's a module for that: CustomError, which has a development snapshot for Drupal 7.

  This module allows the site admin to create custom error pages for 404 (not found), and 403 (access denied), without the need to create nodes for each of them.

  Since the error pages are not real nodes, they do not belong a category term, they do not show in the search, and will not show up in node listings, or in Popular Content block.


How to create an unsortable Field with multiple values? When a CCK field accepts more than one value, the widget will display a sortable table (usually with those cross-shaped handlers); this is the default behavior. I would rather have a non-sortable widget, since the order doesn't really matter. I hope this will avoid the usage of a table element, as well.

How can I achieve this? Do I need to use hook_form_alter()?

I think you'll need to create your own module for this. Instead of using hook_form_alter(), I'd suggest doing things the "cck way". CCK provides hooks which allow modules to provide custom widgets for CCK fields. You can create a module to provide a new Widget option for multi-value fields that doesn't use an HTML table, and doesn't allow for reordering. There's a great article on Lullabot about this. It also talks about creating your own fields and formatters, but you can skip down to the widget part at the end. The sample code is very well documented and should help you understand what's happening. At the very least this will be a great starting point. If something in the article doesn't make sense, feel free to ask for clarifications and I'll add what I can.


How does caching work for blocks? Say I have this type of code to build a custom block in Drupal 8.

 public function build() {

  //code that does a Guzzle call to retrieve data setting $links to contain that data

  $build['article_links'] = array(
    '#theme' => 'them_stuff',
    '#article_links' => $links,
    '#cache' => array('max-age' => 600),

  );

  return $build;
  }

Currently I don't have the '#cache' => array('max-age' => 600), and so every time to page loads the Guzzle call is run.  If I add '#cache' => array('max-age' => 600), does that mean that the Guzzle call won't be run until the cache is invalidated?

Blocks are cached by default, so not specifiying anything should mean your guzzle call should only run once.

max-age 600 then means that the cache is not valid indefinitely but only 600s.

Note that anonymous page cache currently doesn't respect that setting. You have to disable that if you need this to update every 600s.


How can I have different image size for a content type I have 3 type of products that I want to put their image in my site. I have define a content type for them. there is a field that I put the image of my products and I've use imagefield crop module to crop my images but the problem is I don't want any specific ratio for my pictures or at least I have 3 define ratio for my images(each for a product).
I would appreciate if you tell me how can I set the different image size for my product with just one content type?
TNX

Edit:
for example I have chosen the "Image with cropping" as a widget of my field in a content type and because in its option I should fill the blank of the "resolution of cropped image" I set 300x300 like this:

Then when I crop my product option it gave me this:
for 136x65

After Cropping

or for 170x300

After

And I should decide whether my image is square size or rectangular ??

The Image Style Selector module allows you to select a predefined image style and apply it to the uploaded image. In this way when you create a node (or any other fieldable entity), upload an image, you can choose which image style to apply to that image.


How do i post/donate a module in drupal.org? I have a module that i have developed, and I want to post it on drupal.org to be available for other developers to download. How do I do that?


How to display Block content on menu click? I want to display a block below a menu item (like a dropdown) when I click on the menu item. Specifically I want to use this way to display the search block when I click on the my search menu item.

Any suggestions about how to do this?

Install the Menu Attach Block module

  Menu Attach Block allows you to embed blocks in menu items. You may choose to
  replace a menu item entirely with a block, or keep the menu link and embed the
  block after it in the wrapper element.


Disable autocomplete entity reference field In my page content type, I've created an entity reference field that references another page content. When entering data into the entity reference field, it does a search of all the content on the site and returns a list of it. I want to be able to just enter in the node ID, instead of making it search for it.

Currently, you cannot just put in the node ID, as it will throw an error about content not existing.

Is there a way to just input just the node ID? Is there a special format?

There are a couple of options on how to do this.

1) switch the field settings reference method from "default" to "view", and create an entity reference view where the label is the nid

2) create a field widget plugin based on  EntityReferenceAutocompleteWidget.php in your custom module, and replace the form element

'#type' => 'entity_autocomplete',

with a text field.

 '#type' => 'textfield',

Below is a custom widget that does this.

Most of the changes are within the formElement method, but I added some validation to check if the entity is a valid entity of the correct type within the allowed bundles.

namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
 * Plugin implementation of the 'entity_reference_textfield' widget.
 *
 * @FieldWidget(
 *   id = "entity_reference_textfield",
 *   label = @Translation("Textfield"),
 *   description = @Translation("A text field for entity reference"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class EntityReferenceTextField extends WidgetBase  {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => '60',
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['size'] = array(
      '#type' => 'number',
      '#title' => t('Size of textfield'),
      '#default_value' => $this->getSetting('size'),
      '#min' => 1,
      '#required' => TRUE,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $operators = $this->getMatchOperatorOptions();
    $summary[] = t('Textfield size: @size', array('@size' => $this->getSetting('size')));
    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }
    else {
      $summary[] = t('No placeholder');
    }

    return $summary;
  }

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

    $values = $items->getValue();

    $element += array(
      '#type' => 'textfield',
      '#default_value' => isset($values[$delta]) ? $values[$delta]['target_id'] : NULL,
      '#size' => $this->getSetting('size'),
      '#placeholder' => $this->getSetting('placeholder'),
    );

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

  /**
   * {@inheritdoc}
   */
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {

    if (empty($element['target_id'])) {
      return FALSE;
    }

    // Do some validation, to make sure this a real entity within
    // the list of allowed bundles.

    $settings = $this->getFieldSettings();

    $storage = \Drupal::entityTypeManager()->getStorage($settings['target_type']);

    $entity = $storage->load($element['target_id']['#value']);

    if (!empty($entity) && in_array($entity->bundle(), $settings['handler_settings']['target_bundles'])) {
      return $element['target_id'];
    }
    else {
      $form_state->setError($element['target_id'], t('This is not a valid entity reference id.'));
    }

    return FALSE;
  }

}


How Can I display values of variables in a "PHP contextual filter code" to debug my code? I have to use PHP code in contextual filter code in a "Arguments/Contextual Filters" of a view:

global $user;
$uid=$user->uid;

$pid=db_query("select pid from profile where uid='$uid';")->fetchField();

$equipo=db_query("select field_equipo_proyecto_target_id from field_data_field_equipo_proyecto where entity_id='$uid';")->fetchField();

$num_equipo=db_query("select field_num_equipo_proyecto_value from field_data_field_num_equipo_proyecto where entity_id='$equipo';")->fetchField();;

printf("%02d",intval($num_equipo));
return sprintf("%02d",intval($num_equipo));

I think I have some error because I can´t get a correct value. I would like to know how display variables such as $num_equipo, etc to debug my code easier.

Install the Devel module with the Search Krumo module and you will be able to use the dpm() function.

  Devel

  Helper functions for Drupal developers and inquisitive admins.
  Enable the included Kint submodule as for pretty print of variables. kint($array) function is provided, which pretty prints arrays. Useful
  during development. Similarly, a ddebug_backtrace() is offerred.

You can read how to use the Devel module at: Debugging Drupal (a page which gives a brief overview of some of the tools you can use to make Drupal development and debugging easier).


How can I use the Date tools without requiring an end date? I used the Date module's Date Tools (admin/content/date/tools) to add a date field to an existing content type. When I go to create a new node, it displays both a From date and a To date. When I go the Manage Fields section for the content type, I only see one date field.

Is there any way to make it display only a single date field when creating new content? I don't want to allow users to choose a date range, rather only a single date.

It is an option to choose end date or only start date
try to make a new date field and in option before saving there is a check box if you want an end date or not


drupal_mail() and names with apostrophes When using drupal_mail to send an email, I get errors when display names (not emails) contain apostrophes in the "To" field.

For example, referring to drupal_mail() documentation, email addresses like "Another User <anotheruser@example.com>" are valid. "Another User <anotheruser@example.com>" validates perfectly, but "Another O'Neil <anotheroneil@example.com>" fails.

Do I need to change the last name to ONeil instead of O'Neil, or can escape it somehow?
I have also tried ""Another O'Neil" <anotheroneil@example.com>" without success.

Setup: Ubuntu 11.04 LTS
Drupal Version: 7.x
Mail Service: Amazon SES
Additional Mail Modules: "HTML Mail" and "Mail System"

I assume a few things:

You have no exotic mail transport installed, having Drupal fallback to phps' mail()
You deliver the mail trough a unix system. Windows deals differently with mail.

Digging into RFC2822 you will find about escaping " and some other characters.

The solution then presents itself as

$to = "\"Another O'Neil\" <anotheroneil@example.com>";
drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);

print $to; #=> "Another O'Neil" <anotheroneil@example.com>


After wrong submit redirects to wrong url I have my form on page at url alias http://mypage.com/services.
After wrong submission, form redirects me to http://mypage.com/services/formname - and every field is unordered, because Drupal doesn't read there template for this page.
I want to after wrong submit drupal redirect me to same page, and list fields names that are required (and aren't filled).

Changing form options (eg. custom url) doesn't work too. It concerns only the case when all required fields are submitted.

You can do this by using below ways :

Using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events.

Using Webform Rules module.

  This module adds rules integration on webforms.


How to run module code on a specific page/path? So, I'm working on an implementation where users will be redirected to a specific path on a Drupal 7 site with query parameters appended to the URL in an Oauth2 scenario (e.g. www.mysite.com/mypath&code&scope) which the D7 should process and respond to. How does one specify within a custom module to run the code a particular path? Would this be achieved through a code block?

You can use OAuth2 Authentication. Some details about it, from its project page:

... allows users to log into your Drupal site authenticating against a remote identity provider (IDP) via OAuth2.
That is, if a user's credentials can be used to retrieve a valid access token, he/she will be logged into the site with those credentials and the token will be added to his/her session. If the user doesn't exist yet, it will be created.


How can I translate the menu item? I have installed the Internalization module and after that edit the Main menu setting and select the translate and locale.

and add translate as per menu item. But when I switch the language its all the menu item still shows in english

Have a look I have only these options:

Below is how I resolved this before, for a multilingual D7 site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.

Step 1

Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only (e.g) FR menu items.

Step 2

Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be admin/structure/menu/manage/main-menu/edit.

For "Translation Mode", use the option "Translate and Localize". So that
menu items with language will allow translations, and menu items without language will be localized.

Step 3

Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for all languages, make sure such link is marked as "Language Neutral".

Summary

For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language.

Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...


Creating a "User edit path" menu I want to create a menu with title "Edit" and path "user edit path". I tried to put user/%user/edit; user/%id/edit but no success.
Any idea?

You can use user/[current-user:uid]/edit once you have the menu_token module installed.


How can I dynamically refresh the price on product page when changing quantity based on price table I'm currently building a web store with Drupal commerce and would like to get to price shown on a product page to asynchronously refresh when the user increases the amount in the quantity field, such as here.

How can I achieve this?

Commerce Cart Ajax

  Features

  The “remove” button on cart view removes the item from the cart
  immediately, without a page refresh. The row is removed from the
  table.
  The “Qty” is updated when the "update" button is clicked. The totals are recalculated. No page refresh.


add CSS programmatically for a specific page in .theme file I have a question about adding a CSS file programmatically depending on which site I visit. In Drupal 7 I could achieve this by calling the following line in the preprocess_html method in the template.php file:

function template_preprocess_html(&$vars) {

    $css_file_name = 'specific-page';
    drupal_add_css(path_to_theme() . '/css/pages/'.drupal_clean_css_identifier($css_file_name).'.css', array('group' => CSS_THEME));

}

But I can't achieve the same with Drupal 8. I tried the same like in 7 just with the new Drupal 8 way. So here are my tries in the template.theme file

use Drupal\Component\Utility\Html;

1.)

function template_page_alter(&$page) {

  $css_file_name = 'specific-page';
  $clean_alias = Html::cleanCssIdentifier($css_file_name);
  $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

  $page['#attached']['css'][] = $path_to_css;

}

2.)

    function template_preprocess_page(&$vars, $hook) {

      $css_file_name = 'specific-page';
      $clean_alias = Html::cleanCssIdentifier($css_file_name);
      $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

      $local_css = array(
        '#attached' => array(
          'css' => array(
            $path_to_css => array(
              'group' => CSS_THEME,
              'weight' => 9999),
          ),
        ),
      );

      drupal_render($local_css);

    }

Here I get the error: You are not allowed to use css in #attached

3.)

function template_page_alter(&$page) {

          $css_file_name = 'specific-page';
          $clean_alias = Html::cleanCssIdentifier($css_file_name);
          $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

          $vars['attached_css'] = array(
            '#attached' => array(
            'data' => $path_to_css,
            'options' => array(
             'group' => CSS_THEME
            ),
           ),
          );

}

In my template file:

{{  attached_css }}

None of my tries worked so far. I collect the information for the code from serveral tutorials and stackoverflow questions, but it looks like that many of them are very old comparing to the stable release date of Drupal 8. So maybe there are some changes which I forget.

I could solve the problem (thanks to @Eyal).

template.theme :

function template_preprocess_html(&$variables) {

    $css_file_name = 'specific-page';
    $clean_alias = Html::cleanCssIdentifier($css_file_name);

    $activeThemeName = \Drupal::theme()->getActiveTheme()->getName();

    //OR

    $activeThemeName = 'template';

    $variables['#attached']['library'][] = $activeThemeName . '/' . $clean_alias;

}

template.libraries.yml:

specific-page:
  css:
    base:
      css/pages/specific-page.css: {}