alter query view by adding fields in an andGroup within an orGroup I have a multilanguage site with two languages: English and Dutch.
Not all nodes are created in both languages. Some nodes even have no language ('und', 'zxx').
I want the default Drupal provided taxonomy view output all nodes of a taxonomy-term in the current and no node-language, AND, if present, other nodes of this term from the other language.
The Drupal provided sql is:
SELECT "taxonomy_index"."sticky" AS "taxonomy_index_sticky", "taxonomy_index"."created" AS "taxonomy_index_created",
"node_field_data"."nid" AS "nid", "node_field_data"."langcode" AS "node_field_data_langcode"
FROM {node_field_data} "node_field_data"
LEFT JOIN {taxonomy_index} "taxonomy_index" ON node_field_data.nid = taxonomy_index.nid
WHERE ((taxonomy_index.tid = '14')) AND (("node_field_data"."langcode" IN ('nl', 'und', 'zxx'))
AND ("taxonomy_index"."status" = '1'))
ORDER BY "taxonomy_index_sticky" DESC, "taxonomy_index_created" DESC
LIMIT 11 OFFSET 0

I want, if applicable, extend the where clause so it becomes by example:
WHERE (((taxonomy_index.tid = '14')) AND ((("node_field_data"."langcode" IN ('en', 'und', 'zxx'))
AND ("taxonomy_index"."status" = '1')))
OR (("taxonomy_index"."tid" = '14') AND ("node_field_data"."nid" IN ('43'))
AND ("node_field_data"."langcode" NOT IN ('en', 'und', 'zxx'))))

I wrote a function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) in which I found out which extra nodes should be added in the extra OR clause. By adding this code:
      $group_id = $query->setWhereGroup('OR');
      $query->addWhere($group_id, 'taxonomy_index.tid', $tid);
      $query->addWhere($group_id, 'node_field_data.nid', $missing, 'IN');
      $query->addWhere($group_id, 'node_field_data.langcode', $langcodes2, 'NOT IN');

But in the extended where clause I get OR instead of AND statements:
WHERE ((taxonomy_index.tid = '14')) AND ((("node_field_data"."langcode" IN ('en', 'und', 'zxx'))
AND ("taxonomy_index"."status" = '1'))
OR (("taxonomy_index"."tid" = '14') OR ("node_field_data"."nid" IN ('43'))
OR ("node_field_data"."langcode" NOT IN ('en', 'und', 'zxx'))))

But it should be an AND group within an OR Group, maybe like:
$query->setWhereGroup('OR');
$query->setWhereGroup('AND');
$query->addWhere(...

Who can help me out to achive this?

At first I found this function: $query->addWhereExpression(...) which allows me to write the query code myself.
I kept the problem the original, by views generated code, always results in this pseudocode:
cond1 AND (cond2 AND cond3)
The needed pseudoce shoudl be:
(cond1 AND cond2 AND cond3)
And I have to add an OR clause: (cond1 AND cond2 AND cond3)
In total giving this code:
(cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond6)
See my full working function below.
I hope others can benefit of this function and developpers will be inspired by the code. Currently there are only few examples and even less documentation.
<?php

/**
 * @file
 * example module file to alter the Drupal suuplied taxonomy_term view by adding nodes from the non-current language to the current language, avoiding duplicates based on the nid.
 */

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 *
 * Alters the taxonomy_term view.
 * Only valid for sites with two languages.
 * Add nodes of the other language to the view if they have a different nid.
 *
 * @param \Drupal\views\ViewExecutable $view
 * @param \Drupal\views\Plugin\views\query\QueryPluginBase $query
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
  if ($view->id() == 'taxonomy_term' && $view->current_display == 'page_1') {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    // If the view should not be modified for a specific language.
    // if ($language == 'en') {
    //   return;
    // }

    // Step 1.
    // Gather info about the current views query.
    // There are a lot of checks because we will be sure the information about
    // the current query can be interpreted and changed:
    // - an administrator can change the view
    // - drupal can change the implementation in a future version
    // - another hook_..._alter can change the query as well.
    $values = $errors = [];
    $in_operator = 'IN';
    $in_reverse = [
      'IN' => 'NOT IN',
      'NOT IN' => 'IN',
    ];
    $expected_conditions = [
      // fieldname => expected operator.
      'node_field_data.langcode' => 'in',
      'taxonomy_index.tid' => 'formula',
      'taxonomy_index.status' => '=',
    ];
    // Traverse through the 'where' part of the query and save relevant data.
    foreach ($query->where as $condition_group) {
      foreach ($condition_group['conditions'] as $condition) {
        // The $condition['field'] can contain several 'words'.
        $parts = explode(' ', $condition['field']);
        $fieldname = $parts[0];
        // Do we expect this fieldname?
        if (isset($expected_conditions[$fieldname])) {
          $parts = explode('.', $fieldname);
          // For our conveniance we use the short table names.
          $values[$parts[1]] = $condition['value'];
          if (strcasecmp($expected_conditions[$fieldname], $condition['operator']) != 0) {
            $error = TRUE;
            if ($expected_conditions[$fieldname] == 'in') {
              if (strtolower($condition['operator']) == 'not in') {
                $expected_conditions[$fieldname] = $condition['operator'];
                $error = FALSE;
              }
              $in_operator = strtoupper($expected_conditions[$fieldname]);
            }
            if ($error) {
              $errors[] = 'Unexpected operator ' . $condition['operator']
                . ' in field: ' . $fieldname
                . '. Expected: ' . $expected_conditions[$fieldname];
            }
          }
        }
        else {
          $errors[] = 'Unexpected condition field: ' . $fieldname;
        }
      }
    }

    // Step 2.
    // All values are transformed for the queries.
    // All expected conditions found?
    // Status may be absent / create the query part for status.
    if (!isset($values['status'])) {
      $values['status'] = '';
    }
    else {
      $values['status'] = " AND taxonomy_index.status = '" . $values['status'] . "'";
    }
    if (count($expected_conditions) != count($values)) {
      $errors[] = 'One or more conditions are missing.';
    }
    // If errors found, log these and quit. Better safe then sorry.
    if (!empty($errors)) {
      $message = 'Error in function example_views_query_alter() to alter view taxonomieterm.';
      foreach ($errors as $err) {
        $message .= '<br />- ' . $err;
      }
      \Drupal::logger('example')->critical($message);
      return;
    }

    // Get the current taxonomy tid value for queries.
    $values['tid'] = array_shift($values['tid']);
    // Substitute language placeholder with current language.
    foreach ($values['langcode'] as &$lc) {
      $lc = str_replace('***LANGUAGE_language_interface***', $language, $lc);
    }

    // Step 3.
    // Lookup if the other language has additional nodes.
    // Find all nids for the current node langages.
    $db = \Drupal::database();
    $current_lang = $db->query("SELECT node_field_data.nid AS nid
      FROM {node_field_data} node_field_data
      LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
      WHERE taxonomy_index.tid = :tid AND node_field_data.langcode "
        . $in_operator . " (:langcodes[])" . $values['status'],
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']])
      ->fetchCol();
    // Also for the other langauge.
    $missing_lang = $db->query("SELECT node_field_data.nid AS nid
      FROM {node_field_data} node_field_data
      LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
      WHERE taxonomy_index.tid = :tid AND node_field_data.langcode "
        . $in_reverse[$in_operator] . " (:langcodes[])" . $values['status'],
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']])
      ->fetchCol();
    // Get missing nids.
    $missing = array_diff($missing_lang, $current_lang);
    // No nodes to add?
    if (empty($missing)) {
      return;
    }

    // Step 4.
    // Change the where clause of the query.
    // We like to add only an OR group with the nids to add.
    // The current where clause creates the following pseudo code:
    // WHERE cond1 AND (cond2 AND cond3)
    // But we need:
    // WHERE (cond1 AND cond2 AND cond3)
    // No way was found to change the current query to the needed clause.
    // The goal is to expand the where clause with this result:
    // WHERE (cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond6)
    // So recreate the whole where clause.
    $query->where = [];
    // Create a new OR group using the original content.
    $group_id = $query->setWhereGroup('OR');
    $snippet = "taxonomy_index.tid = :tid AND node_field_data.langcode "
      . $in_operator . " (:langcodes[])" . $values['status'];
    $query->addWhereExpression($group_id, $snippet,
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']]);
    $snippet = "taxonomy_index.tid = :tid AND node_field_data.nid IN (:missing[]) AND node_field_data.langcode "
      . $in_reverse[$in_operator] . " (:langcodes[])";
    $query->addWhereExpression($group_id, $snippet, [':tid' => $values['tid'],
      ':missing[]' => $missing, ':langcodes[]' => $values['langcode']]);
    // An alternative is to combine the two $snippets.
    // But this works: the OR statments are more clear.
  }
}


How to make private (hidden) node path aliases? The site (Drupal 7) has regular nodes that are publicly visible via standard node alias (node/<nid>). I need to be able to create hidden (private) node aliases that are random (e.g., node/9s8d0a8z9d) which will allow the person who has the URL to access the node.

User who accesses the node via random node alias should not be able to see the node id in URL hence the required feature. The main purpose of private URL is to make them expirable. It's ok if user gets to know the node id by digging the site once it gets there, I need to make the node alias obscure just in the URL itself.

I can create multiple node aliases with path and pathauto modules but one of random aliases will eventually be set as default alias which will be visible as node URLs in views or in Content page which is not desired.

Are there Drupal modules that can provide this functionality?

There is different solutions

https://www.drupal.org/sandbox/ajlee/2109425 (disable access to nodes through the "normal" URL such as node/123)
https://www.drupal.org/project/access_unpublished (key to give view access to unpublished node)
https://www.drupal.org/project/node_authlink authorization key for every node and gives additional grants (view/edit/delete) to every user (anonymous too) who accesses page with correct key in URL


Can't save node using batch When I'm trying to save a node using batch processing, I'm getting this error:

  PDOException: in drupal_write_record() (line 7383 of C:\wamp64\www\drupal7\includes\common.inc).

Here is my complete code:

function custom_node_import_form_submit($form, &$form_state) {
  $csvFile = file_load($form_state['values']['csv_file']);
  $csvFilepath = drupal_realpath($csvFile->uri);
  $file = fopen($csvFilepath, "r");

  $batch = array(
    'operations' => array(),
    'finished' => 'node_import_finished',
    'title' => t('Node import'),
    'init_message' => t('Importing is starting...'),
    'progress_message' => t('Imported @current out of @total.'),
    'error_message' => t('Node importer has encountered an error.')
  );

  fgetcsv($file, 0, ",");
  while($line = fgetcsv($file)) {
    $batch['operations'][] = array('node_import_progress', array(array_map('base64_encode', $line)));
  }

  batch_set($batch);
  batch_process('admin/node/custom-node-import');
  fclose($file);
}

function node_import_progress($line, &$context) {
  $line = array_map('base64_decode', $line);
  saveNode($line);
  $context['message'] = t('Importing %title', array('%title' => $line[0]));
}

function node_import_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Node importing is complete!'));
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}
function saveNode($param = []) {
  global $user;

  $node = new stdClass();
  $node->title = $param[0];
  $node->type = "article";
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  $node->body[$node->language][]['value'] = $param[3];

  $node = node_submit($node);
  node_save($node);
}

I have debugged and found that the line which gives this error is the last line where the node is getting saved. i.e node_save($node);

The issue was with the non-English characters in the CSV file like ö, ä etc

So the solution was to use utf8_encode() for the values:

$node->title = utf8_encode($param[0]);
$node->body[$node->language][]['value'] = utf8_encode($param[3]);

Hope it helps somebody.


How can i set this redirect only for anonymous users? namespace Drupal\project_extras\EventSubscriber;

use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    // This announces which events you want to subscribe to.
    // We only need the request event for this example.  Pass
    // this an array of method names
    return([
      KernelEvents::REQUEST => [
        ['redirectMyContentTypeNode'],
      ]
    ]);
  }

  /**
   * Redirect requests for my_content_type node detail pages to node/123.
   *
   * @param GetResponseEvent $event
   * @return void
   */

  public function redirectMyContentTypeNode(GetResponseEvent $event) {

    $request = $event->getRequest();

    // This is necessary because this also gets called on
    // node sub-tabs such as "edit", "revisions", etc.  This
    // prevents those pages from redirected.
    if ($request->attributes->get('_route') !== 'entity.node.canonical') {
      return;
    }

    // Only redirect a certain content type.
    if ($request->attributes->get('node')->getType() !== 'specific_content_type') {
      return;
    }

    // This is where you set the destination.
    $redirect_url = Url::fromUri('entity:node/10');
    $response = new RedirectResponse($redirect_url->toString(), 301);
    $event->setResponse($response);
  }
}

You can load a user and check for authentication

$currentUser = \Drupal::currentUser();

// Do nothing if the user is authenticated.
if ($currentUser->isAuthenticated()) {
  return;
}


How do I change the default '- Any -' option in views exposed filter? I have exposed filters in a view as select lists. How can I change the text for the default filter option of "- Any -"? In previous versions it was suggested to use a preprocess function like this:

if($form['#id'] == 'views-exposed-form') {
      foreach ($form['FIELDNAME']['#options'] as $key => &$option) {
        if ($key === 'All') {
          $option = 'All';
        }
      }
    }

But in Drupal 8, instead of a modifiable key/value, it is stuck inside a protected class.

protected string -> string(7) "- Any -"

How can I modify this?

Note: I also tried Better Exposed Filters, but it is unable to rewrite the "- Any -" option.

Better Exposed Filters works for me well in my Drupal 8. The only thing what you have to do is follow this path.

Better Exposed Filters > Settings > More Options > Rewrite results.

Then you have to replace the any text using this format in Drupal 8. I think what you missed is this one. Replace using this token

- Any -|your replacement


Table not creating while installing a custom module in Drupal 7 I am creating a simple module. In that module I need to save the values in a table and I have created an .install file to create the table when the module is installed.

While installing the module, it is not creating the table and it gives a PDOException Error. I am unable to find the issue with my code.

The error message:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned NOT NULL COMMENT ' AMOUNT', rate unsigned NOT NULL COMMENT 'R' at line 3: CREATE TABLE {sampletest} ( id INT unsigned NOT NULL COMMENT 'My unique identifier', amount unsigned NOT NULL COMMENT 'AMOUNT', rate unsigned NOT NULL COMMENT ' RATE', time unsigned NOT NULL COMMENT '  TIME', PRIMARY KEY (id) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT ' table'; Array ( ) in db_create_table() (line 2717 of H:\xampp\htdocs\drupal7\includes\database\database.inc) ;

Content of the .install file :

<?php
/**
* Implements hook_install().
*/
function sampletest_install() {
 drupal_install_schema('sampletest');
}
/**
* Implements hook_install().
*/
function sampletest_uninstall() {
  drupal_uninstall_schema('sampletest');
}
/**
* Implements hook_schema().
*/

function sampletest_schema() {
  $schema['sampletest'] = array(
    'description' => t('EMI table'),
    'fields' => array(
      'id' => array(
        'description' => t('My unique identifier'),
        'type' => 'int',
        'unsigned' => true,
        'not null' => true,
      ),
      'amount' => array(
        'description' => t('AMOUNT'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
      'rate' => array(
        'description' => t('RATE'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
      'time' => array(
        'description' => t('TIME'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

I can see 2 problems with in your code:

You should not call drupal_install_schema() from hook_install() in Drupal 7. hook_schema() will be called and the table will be automatically created/dropped on installing/uninstalling. See here: https://drupal.org/node/224333#install-schema
As @Ollie also stated, there's no field type named bigint. You should use int and set its size to big.

Like following:

'amount' => array(
  'description' => t('Amount'),
  'type' => 'int',
  'size' => 'big',
  'unsigned' => TRUE,
  'not null' => TRUE,
),


Access node fields in hook_node_grants In hook_node_grants() I want to check if user ID is equal to a node's field value, But there is only two arguments: $account and $op

How can I access the node object that is being checked for grants?

A better approach to this would be to implement hook_node_api that checks the current $user's permissions to the loaded field then does something.

function custom_module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  //get the current user
  global $user;

  switch ($op) {
    case 'load':
      //do some logic with $node and with the current $user's roles
    break;

    //(optional)add other cases for other operations

    default:
    break;
  }
}

alternatively you can try template_preprocess_node

function theme_name_preprocess_node(&$variables) {
  global $user;
  $node = $variables['node'];

  //do some stuff with $node and $user
}


How to change the saving order of field_collection fields I have a node with field1 and field2 (field_collection)

I am using hook_entity_presave($entity, $type) like this:

function txs_entity_presave($entity, $type)
{
    if ($type == 'field_collection_item') {
      ...do some stuff
    }
}

For now, this hook is called firstly for field1 and, only after field1 is saved, this hook is called for field2.

I would like the opposite because I need to retrieve the value of field2 to handle the "field1_presave".

Here are the details:

Here is the code inside the hook_entity_presave, when field1 is being presaved. This code is showing why I need that field2 must be saved before field1

if ($entity->field_name == 'field1'){
    $entity_w = entity_metadata_wrapper('field_collection_item', $entity);
    $node = $entity_w->host_entity->value();
    $node_w = entity_metadata_wrapper('node', $node);

    //HERE I NEED THAT field2 was already saved...
    //This is not the case...
    //the following line does not works in all cases
    $used_value=node_w->field2[0]->myfield->value();
    //as field2 is not yet saved, $used_value could be wrong
    if ($used_value=='something'){
        ...change something in field1
    }
}

The only way I could solve my problem was to handle the logic in the form_validate function.
Unfortunately, I couldn't update the field collection from there... this is why I added a validation function for my field collection:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add custom validation hooks for Field Collections.
  if ($context['field']['field_name'] == 'field1') {
    array_unshift($element['#element_validate'],
'MYMODULE_field1_validate');
  }
}

Then I could insert my logic there:

/**
 * Custom validate function for field_assignments.
 *
 *  @see MYMODULE_field_widget_form_alter()
 */
 function MYMODULE_field1_validate($element, &$form_state, $form) {
    if (...){
       form_set_value($form["field1"][LANGUAGE_NONE][0]['field_to_change'], array(LANGUAGE_NONE => array(0 => array('value' => 123.456))), $form_state);
    }
  }


Term name of current node in title I'm trying to echo out the current term name that my node is inside of into my function, but it only keeps echoing out 1 and not the name. This is what I have.

function bartik_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);

    if (drupal_is_front_page()) {
      $variables['head_title'] = implode(' - ', $variables['head_title_array']);
    }
    elseif (node_is_page()) {
      $terms_name = print $term_name->name;
      $variables['head_title'] = implode(' - '.$terms_name.' - ', $variables['head_title_array']);
    }
  }
}

can anyone help?

Your code is using the following line:

$terms_name = print $term_name->name;

You are assigning to $terms_name the value returned by print $term_name->name, which is 1.
If you try executing $var = print "ciao";, you will notice that the value assigned to $var is 1.

The other issue with that code is that $term_name is not a variable defined from the code you showed; executing that code, you get an "access to a not defined variable" error.


Is there a way to change edit link for Nodes? Is there a way to change edit link for Nodes?

Currently Edit looks like this: [node/node_id/edit]

I required to look like this: [node/edit/node_id]

Try out this code. add it to your module

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    if ($node->nid == $matches[1]) {
      $path = 'node/edit/$node->nid' . $matches[2];
    }
  }
}


Print Media CKeditor images correctly custom code How can I show an image that I uploaded with de CKeditor Media browser on my page? Now I use this code:

    case 'black_box_with_image':
        $black_box_with_image_image = '';
        if (!empty($content['settings']['black_box_with_image_image'])) {
            $fid = $content['settings']['black_box_with_image_image'];
            $file = file_load($fid);
            if ($file) {
                $image = array(
                    'path' => $file->uri
                );
                $black_box_with_image_image = theme('image', $image);
            }
        }

        $black_box_with_image_title = !empty($content['settings']['black_box_with_image_title']) ? $content['settings']['black_box_with_image_title'] : '';
        $black_box_with_image_link_name = !empty($content['settings']['black_box_with_image_link_name']) ? $content['settings']['black_box_with_image_link_name'] : '';
        $black_box_with_image_link = !empty($content['settings']['black_box_with_image_link']) ? $content['settings']['black_box_with_image_link'] : '';
        $black_box_with_image_description = isset($content['settings']['black_box_with_image_description']['value']) ? $content['settings']['black_box_with_image_description']['value'] : '';

        $black_box_with_image = '

' . $black_box_with_image_title . '

' . $black_box_with_image_description . '

                    ' . $black_box_with_image_link_name . '

                    ' . $black_box_with_image_image . '

        ';

        $content['content'] = $black_box_with_image;
    break;

The variable $black_box_with_image_description is the field with the CKeditor Media browser image.

Now it shows like this:

  [[{"fid":"8","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"field_file_image_title_text[und][0][value]":"","field_folder[und]":"6"},"type":"media","attributes":{"height":"480","width":"388","style":"width:
  150px; height: 186px;","class":"media-element file-default"}}]]

In the editor, the image is displayed, but when I save the node it shows the plain HTML.

  Convert Media tags to markup

I checked the covert media tags to markup in the format section. When I use a default CCK field the images shows correctly, but not with my custom code..

Problem solved.

$black_box_with_image_description = isset($content['settings']['black_box_with_image_description']['value']) ? $content['settings']['black_box_with_image_description']['value'] : '';
if (isset($content['settings']['black_box_with_image_description']['format'])) {
    $black_box_with_image_description = check_markup($black_box_with_image_description, $content['settings']['black_box_with_image_description']['format']);
}


List of people who flagged me since my last login I've created a Like flag using flag module and a page view to list all people who like the currently logged in user. The views works good and am getting a list of users who like me (the currently logged in user). I want to filter the list of people who've liked me since my last login.

Been messing with the user:last login and user:last access filters. Can't find to make it work. Can anyone please help me with this?? (edit: I realize that the user:last login and user:last access filters is for filtering the list of users so no luck yet)

In the filter criteria add flaggeds time filter.
An operator with is greater than or equal to and write a date whatever you want, doesnt matter wich one, because where are going to modify programmatically later.

Then in your module we have to rewrite that filter to put the last login from the user.

/**
 * Implements hook_views_pre_view.
 */
function YOUR_MODULE_views_pre_view(&$view) {
  if ($view->name == 'VIEW_NAME') {
    global $user; //Load user
    $view_filters = $view->display_handler->get_option('filters');
    // Put the user last login in the flag filter we created before
    $view_filters['timestamp']['value']['value'] = date('Y-m-d H:i:s', $user->login);
    $view->display_handler->override_option('filters', $view_filters);
  }
}


I have installed contact module and SMTP Authentication Support but do not appear in Structure tab I have Drupal 7.22 installed, I have installed some modules, but there are two modules that appear correctly installed but I cannot see their configuration in structure.
These modules are Contact and SMTP Authentication Support.

Previously I had some issue with the cache in Configuration tab, and I empty the cache, and it worked, but in the Structure tab even if I do it, I don't solve it.

You should install the devel module from http://drupal.org/project/devel and after that you can select rebuild menu or flush all cache function. (From the devel menu)
If i doesn't work, maybe there was some problems with your installation. You should disable and enable these modules again or run update.php script.


How to assign roles in my own registration form I know about assigning roles and permission in DRUPAL admin login where admin can add user and even add new roles (check here) to the new users.

I have a basic registration form in my page and while user register I want to assign roles to them for example - employee, superuser and admin roles.

How do I do it, do I have create a new module and may be use the ROLE module functionality in Core DRUPAL.

I have also checked this Link which explains about basic Users, roles and permissions in DRUPAL but it does not answer my question.

So

I need to create new user in Drupal from my own Registration form.
I need to have my own custom roles (eg. employee, superuser and admin roles) - This Link might help me in this
This new user which are registering from my own custom registration form, should be assigned with this custom roles(eg. employee, superuser and admin roles).

Can some please tell me how do I do this in Drupal 7 or Does anyone knows any Drupal modules which can help me do this efficiently or should I go with own PHP code.

which will be more efficient way for doing this.

Thanks in advance :)

function company_form()
    {
         $form['company_username'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-username',
          '#default_value' => '',
              '#required'=>'true'
      );
          $form['company_email'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-email',
              '#required'=>'true',
          '#default_value' => '',
          '#element_validate' => array('generate_special_form_validate'),
      );
           $form['company_password'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-password',
               '#required'=>'true',
          '#default_value' => ''
      );

      $form['submit'] =  array(
          '#type' => 'submit',
          '#title' => '',
          '#value' => 'Submit',
          '#default_value' => ''
      );
      return $form;
    }
    function company_form__validate(&$form_state,$form) {

         if (!valid_email_address($form['input']['email'])) {
         form_set_error($form['input']['email'],'Please enter a valid email address.');
       }
    }
    function company_form_submit($form, &$form_state)
    {

     global $user;
        $company_username = $form_state['input']['company_username'];
        $company_email = $form_state['input']['company_email'];
        $company_password = $form_state['input']['company_password'];
         $fields = array(
              'name' => $company_username,
              'pass' =>$company_password,
              'mail' => $company_email,
              'init' => $company_email,
              'status' => 1,
              'access' => REQUEST_TIME,
              'roles' => array(
               4 => 'company',
                ),

        );
        $account=user_save('', $fields);

    if($account->uid)
    {
     drupal_set_message('User Created SuccessFully');
    }

}

Firstly you have to create roles from backend.
and then You can Assign as many roles by passing role id and role name in array.

'roles' => array(
               4 => 'company',
                ),

Hope this code helps you.


WHERE can I change the notification email message for role assigments? I'm using Ubercart 2 and Drupal 6 and I cannot find the place where I can change/customize the notification email that's sent out for new and/or expiring role assignments.
Here is the generic message:

The role, member, you acquired by purchasing a product at our store has expired. Any special access or privileges that came with it are now gone. You can purchase it again by going to MY WEBSITE
Thanks again,
MY WEBSITE

I've looked under conditional actions, and while that helps me understand how and when emails are sent I cannot change the message text from there. Neither can I change the message text in admin/store/settings/checkout/edit/messages.

Per TR on the Ubercart forums:

"You may change this text under the Conditional Actions settings:
/admin/store/ca/uc_role_notify_revoke/edit/actions"

http://www.ubercart.org/forum/support/32739/where_can_i_change_notification_email_message_role_assigments#comment-70607


Drupal 7 Internationalization - why are my admin menus still in English? I'm trying to make a fully bilingual website that will be administered by French and English users.

I've installed the internationalization module and all its dependencies and the localization update module, which claims to have installed French language support. I've successfully got all the front-end content, menus and views translated and language switching working, but no matter what I do, the admin menus remain in English. It doesn't matter whether I change my default language in the user preferences or set the site to French with a url parameter, I can't get the admin menus to change language. Many of the tutorials I've seen online seem to gloss over this as though it happens automatically.

Is it possible to display Dashboard, Content, Structure...etc in French as well as the default English or am I going nuts?

If you swap from french to English the admin menu should also switch from french to English (Drupal 7).

In the tag "detection and selection" of Admin/Configuration/Regional and language/Languages" click the "Default" checkbox in order to use the default site language.

The "Localization update" module also helps you keep your interface translations for core and contributed modules up-to-date :

Enable the Locale (core) module
Download and enable the "Localization update" module
Go to the configuration page at admin/config/regional and language/translate interface/update
Wait as the module looks for translation updates
Click Refresh information button at the bottom of the page
Wait as the module gets all translations
Disable the Localization update module when finished to improve site performance.


Theme Views exposed filters, how to add count? For example in the case of filtering by taxonomy terms, I would like to add the node count next to each term in the exposed filter block. Already using Better Exposed Filters module as it allows to use checkboxes instead of select list.

Is there a way to do this? I can make a nice list of the terms with node counts using aggregation, but I can't think of an easy way to use ajax that way. :-)

What you are asking for is what is called faceted search.

If you want to have this feature you should think about using a search database that supports this, like Apache Solr. The problem is that it otherwise is going to be very heavy and complex to make, especially with views making the query for you. If you were to make this feature yourself with MySQL, it would probably be easier to code the entire page yourself, and add the facets for the terms in your custom form.

In Drupal 7 the search api module comes with support for Apache Solr and can do facets on both MySQL and Solr. It also have views integration.

For Drupal 6, you can use the Apache Solr Search integration module, which creates an API integration with Solr, making it easier to create facets with Solr. Use this would probably require that you custom made the entire form.


Image generation in progress. Try again shortly. (503 service unavailable) I have two exact copies of the same code installed in the same server running a common AMP stack (I am using bitnami). One copy is named as 'dev' and another one is 'prod'.

Only they have their own database & files (which are clones as well).

In dev, Image styles work just fine. I do drush if - it deletes the styles and creates when viewed.

But in prod, drupal throws 503 service unavailable with a Image generation in progress. Try again shortly. content on the first hit (or until the image is generated).

Of-course that comes from image.module line 858, when drupal finds a lock. And somehow setting image_allow_insecure_derivatives to TRUE might solve this issue.

What I don't understand is why its happening! And whats the remedy?

Thanks!

I managed to fix it!

It was a server configuration issue (PageSpeed (bitnami) to be specific).

I tail -fed the access log and saw

xxx.my.ip.xxx - - .... "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.102 Safari/537.36"

xxx.server.ip.xxx - - .... "Serf/1.1.0 mod_pagespeed/1.6.29.2-"

Figured out definitely something is wrong with server (why is it hitting twice!).

Disabled and it worked fine

# Include conf/pagespeed.conf
# Include conf/pagespeed_libraries.conf

This issue was not happening in the dev site maybe because I have apache basic http authentication enabled (hence pagespeed was not caching it, just guessing).


Create a dynamic Tabbed View from Group By I created a View which show all the content tagged with user flagged terms and group the content by Term Name.

Right now I am trying to make each group appear in a tab, I don't know how to achieve it.

For example if the user "X" flagged terms "A", "B" & "C", Currently, The view come back with all content tagged with terms "A", "B" & "C" and group them by Term Name in this case "A", "B" & "C". I want these groups "A", "B" & "C" to be tabs. I need to auto generate them because I don't know either the number or which terms are flagged by the current user.

If I can't achieve it with views only, Is their anyway to achieve it with another modules e.g. Panels.

At the same time, I will try to trace the views template files to see If I can do it with jQuery Tabs and views template files. If you have any other suggestion please feel free.


field is Integer and I am getting PDOException error thrown I have a field called "blog_post_guid" and it is set as Integer.

Recently, it is throwing this error:

  PDOException: SQLSTATE[22003]: Numeric value out of range: 1264 Out of
  range value for column 'blog_post_guid_value' at row 1: INSERT INTO
  {field_data_blog_post_guid} (entity_type, entity_id, revision_id,
  bundle, delta, language, blog_post_guid_value)

Running a search revealed this article.

Based on this information I thought I should install and enable BigInt.

Is there any other relevant solution to this issue for Integer field and Drupal 7?

Using bigInt module is the best way for achieve this job, there is another solution like altering database table but it not recommanded


How can I display more than 5 nodes on a taxonomy view for one vocabulary? I have a web site where videos are posted and each video is a part of a series. The series name is a taxonomy term in a vocabulary. Many of the series have more than 5 parts and I cannot figure out how to have the taxonomy view page for these to either add a "more" link, use a pager, or display all nodes referenced by the particular taxonomy term within that vocabulary.

You can see an example of this at http://www.clctc.org/discussion-series/desperation

There are 6 nodes tagged with the "Desperation" term from the "Discussion Series" vocabulary. The page only shows 5 and there is no pager or more link.

Thanks for any help you can provide.

There is two things you should check.

Re-check if the taxonomy(tags) are referenced correctly in each content.
Secondly check the pager section in views, for pages, offset and more link settings.


Disable double confirmation for Simplenews I have a simplenews registration block on my site. If people sign up for a newsletter, they receive a mail with a confirmation link. When they click on the link they come to a page with another confirmation button, which must be clicked if you realy want to register.

Thats the default behavior called Double-Opt-In in simplenews.

What I want for registration ist that you receive a mail with a confirmation link, if you click it you come to the page which says something like 'You are registered!'. I want to disable the need of this second button, any ideas?

Thanks in advance

There's a considerably easier way to do this, which is also documented in the README.txt for 6.x-2.x, but apparently not in 7.x-1.x.

In short, just change the confirmation mail templates and append /ok to the URL token.


How to render a poll within a node? I'm trying to embed a poll into the body of a node with PHP code:

$node = node_load(123);
print node_view($node, 'full');

That won't work. What's the trick?

I would add a node reference field to the content type you want to add a poll to, and choose the formatter that renders the referenced poll node (instead of rendering just a link). I must add that I never tried this with poll nodes, but I expect it to work just like it does with other nodes.


Reference to parent node on entity form type I have a "Request more info" Entity Forms Type form that is accessed from basically every content type in the website, with a Menu Tab link created via Views. I attempted at adding both a NodeReference and Entity Reference with Prepopulate without successs. The closest I get is having a Select List displaying all Nodes from all referenced Content Types (Hundreds). Is it possible to have this field pre-populated instead of the user having to choose from a long list of Node Titles?

Prepopulate works by lifting values from the request url and inserting them into the rendered form. If it is not in $_GET it will not appear. Using views with a menu tab will mean that you will have to add parameters to the url whether you use Prepopulate or not. I think you should back up and reconsider your approach.

I would suggest exposing the form as a block right on the pages you want. That way the page is easier to identify. If you use Bean it is a simple matter to create a block for your Entity Form Type.

Enable the Bean and Bean UI modules.
Go to /admin/structure/block-types and click 'Add new block type'.
Give the block type a name (eg Entity Form Type Block).
Under 'Manage fields' add an 'Entity reference' field. Select box widget is fine.
Under 'Manage display' select 'Rendered entity' and 'Render as full content'.
Go to /admin/content/blocks and click 'Add new block'.
Give the block a Label (eg. Request more information block) and a title.
Select your form from the dropdown, and save.
Go to /admin/structure/views/add and create a view called 'Node List' showing 'content' of type 'all'. Uncheck the 'Page' display. You are creating the master only. Click 'Save and Continue'.
In the view edit screen, Add a display -> references.
Configure the 'Title' field and uncheck everything (no label, no link).
Under 'Advanced' configure a contextual filter in Content:NID. Check 'Provide default value' and select 'Content ID from URL'. Save your view.
Go to /admin/structure/entityform_types and click 'Manage fields' for your entity form. Edit the nodereference field and set it to required, number of values = 1, and at te bottom under 'Views - Nodes that can be referenced' select your 'Node list - references' view.
Go to /admin/structure/block and set your block to display on the nodes you want, and for the roles you want. It is important to note that the block permissions will override any access permissions you have set on the form.

The entity form will now display on the selected pages, and the user will be required to select the node reference to submit the form. The list presented will be limited to the current page.


how to make term reference field choose term from a multi level taxonomy vocabulary I have a taxonomy voc 'area' that has three levels, region > province > town and city.

I then have a content type 'members' which has these three term reference fields that retrieve region, province and town and city respectively from the area vocabulary.

I used feeds to transfer a csv file of members with one member per row, each with region / province / town city. The result after the feed upload looks great.

Using views to make a block and page I have contextual filters show those same terms and they expand quite nicely via a block from region to a province page, each showing how many 'members' there are per page in parenthesis, drilling down to a town and city page. It's all very nice.

However when I try to manually enter a Member I need to enter region, province and town city using a a select field each time. Using hierarchical select doesn't work because I think it doesn't know which level to choose a term from. The result always skews the view, because for example, province field is choosing a town city, or vice versa, or a region. I do not know how to make it choose the level in the select field i want.

I am clueless. I do not even know if I am asking the correct question because I do not know if my error lies elsewhere.

Try Simple Hierarchical Select, it is less buggy than the more complex one.


Specific user role can't log in I'm having a very strange problem:
Most user roles can login without a problem (administrators, clients, etc...).

But users with the 'registered user' role can not login through the form. The login form does not respond. In the log messages the failed login attempts are not logged.

The only way the users (with role 'registered user') can login is through the request new password link.
So the user clicks on the link, receives an email with a login link, and when they click on the link in the email they are logged in. So than they can edit their account and even change the password.

However, when they log out again and try to login with the new password it does not work anymore, the form does not respond again.

The only way that user can get logged in again is through the request new password procedure.

Anyone have any idea what could be causing this?

I suspect it has something to do with some kind of permissions.
Some of the modules i installed who could maybe give a conflict:
Logintoboggan, Registration role

Any help would be greatly appreciated.

Greetings

Thanks for the help.

I did try to login with an email and username, same results for both.

But very strangely everything works now...
And i have no idea what i did to fix it.

Last thing i did was update every module and the Drupal Core.
And today the login form works again as it should...

I would love to give more information for future people experiencing this problem but frankly i have no clue what solved it.

Thanks again for all the help!

Greetings


Can I control which database Drupal uses for certain data? It is of course possible in a custom modules to use two different databases (and I mean different databases not different RDBMSs!), but is there a way to use two different databases, and then force Drupal to keep certain data in one and other data in the other?

For instance, keep nodes (and closely related tables) in one, and all site configuration in another.  (Perhaps, while sorting it out, it might be useful to have a third as the default.  That way everything that's not sorted into either the content or the configuration database would remain in the default until you decided where it best fit.)

How can this be done, without major hacking of Drupal's core?

If it's not possible at the Drupal level, this might be possible at the MySQL level using the FEDERATED storage engine.  This is a thoroughly untested solution, however, and it might not play nice with Drupal.


how to give edit permission content to new user in drupal? I have a content type called "company." I have uploaded a lot of company details to the site by myself.

Now I want that people employed by these companies create new accounts in my site, and they should be allowed to edit the details for the company where they work.
I need to give the permission for editing the "company" nodes in my site to new users.

Can you tell me how to implement this?

If there is only a single user that will have permission for a given company node, you can assign them as the author of the company node and give them the "edit own company nodes" (or similar) permission.

If there are multiple, it's going to be trickier, you could for example add a hidden user reference field to the company node (which only you can edit, with a field permission module) and use http://drupal.org/project/nodeaccess_userreference. Or use http://drupal.org/project/content_access, which allows to configure permissions for single users directly.


Execution of complex db Queries in tpl What is performance cost of executing queries like EntityFieldQuery directly in tpl.php files ?

I have some situations, where i have put db queries and more complex php logic in various tpl.php files.

It works, but my concern is performance.
What are best practice ? Should i move those queries somewhere else and what are advantages ?

Thanks!

To be honest you should never, ever run an SQL query inside a template file. This sort of thing should be handled either at the preprocess level, or even better, at an earlier stage in the page build (usually in a custom module file). There are good reasons for this:

Putting business/application logic inside a template file is never a good idea. Literally reams of volumes have been written on the subject; over the past few years MVC has been the 'it' pattern so I'd recommend reading up on that to understand the reasoning behind this kind of separation.
If you execute queries in your template files they will run even for pages for which the rest of the page content has been cached, which is a definite performance no-no.

I imagine there are other good reasons not to do it as well, suffice to say these are two quite strong arguments for moving the logic out of your template files.


Error : Only variables should be passed by reference I get this error Strict warning:

  Only variables should be passed by reference in include() (line 20 of
  ...)

Can anybody see what is wrong here?

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
          <?php print t('Toggle navigation'); ?>

        </button>
        <a class="navbar-brand" rel="home" href="<?php print url('<front>'); ?>" title="<?php print variable_get('site_name', ''); ?>">
          <?php print isset($logo) && $logo ? theme('image', array('path' => $logo)) : '
' . variable_get('site_name', '') . '
'; ?>

          <?php print drupal_render(menu_tree_output(menu_tree_all_data('menu-top-menu'))); ?>

The error is because you're trying to directly pass menu_tree_output() function return value to drupal_render() function. Which is not allowed because drupal_render() accepts $element as call by reference. When accepting arguments as call by reference those must be passed as variable (preferred).

So your code should look like below:

        <?php $menu_output = menu_tree_output(menu_tree_all_data('menu-top-menu')); ?>
        <?php print drupal_render($menu_output); ?>


How add conditional required field Need:

If we select a value in a drop-down list field(A), then we need to display and set as required field(B).

Note: the field(B) is a date range.

I tried to add states with a hook form alter

$form['field_b']['#states'] = [
      'visible' => [
        ':input[name="field_a"]' => ['!value' => '_none']
      ],
      'required' => [
        ':input[name="field_a"]' => ['!value' => '_none'],
      ],
  ];

As you see I use: '!value' to negate a value and '_none' for no value. So, It will not be required if there is no value selected

This code didn't work. It display the field B, but it is not mandatory.

We found that there is an issue with core
https://www.drupal.org/project/drupal/issues/2855139

At the end issue was closed, but it didn't work for us. It worked with texte fields but not for our rage date.

So, if dont want to use conditional_fields module and only conditional fields core
You can do it, but required field have sometime a little bug.

In the issue someone take some code from conditional_fields that fix this issue, and use it.

your_module/js/conditional_fields.js

(function ($, Drupal) {

// Fix core's required handling.
$(document).bind('state:required', function (e) {
  if (e.trigger) {
    var fields = $(e.target).find('input, select, textarea, fieldset');
    fields.each(function() {
      var label = 'label' + (this.id ? '[for=' + this.id + ']' : '');
      var $field_labels = $(e.target).find(label);
      var $fieldset_legends = $(e.target).find('legend span.fieldset-legend');
      var $labels = $field_labels.add($fieldset_legends);
      if (e.value) {
        $(this).attr({ required: 'required', 'aria-required': 'aria-required' });
        $labels.each(function() {
          $(this).addClass('js-form-required form-required');
        });
      } else {
        $(this).removeAttr('required aria-required');
        $labels.each(function() {
          $(this).removeClass('js-form-required form-required');
        });
      }
    })
  }
});

})(jQuery, Drupal);

In your_module.module in a form alter add:

$form['#attached']['library'][] = 'your_module/conditional_fields';

$form['field_b']['#states'] = [
      'visible' => [
        ':input[name="field_a"]' => ['!value' => '_none']
      ],
      'required' => [
        ':input[name="field_a"]' => ['!value' => '_none'],
      ],
  ];

Don't forget add the js code in your_module.libraries.yml file

Adding JS to a Drupal module

With our above code it worked!.


node_view does not show the comments box I am using node_view(node_load($nid), "full") and I print(render()) the result in a template. But the content of the node is appearing but not the comments nor the comments form. How can I display them ?

You probably need to use the node_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node_show() relies on node_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that also call it in Drupal core.


Wrong URL being generated in a view I have a very strange issue with a Drupal 8 install. My production setup is running on NGINX in a subdirectory - something like www.example.com/abc.

The site is running great, but I have seen an error occur that I can't pinpoint. One page that I setup as the frontpage (ie, /abc/index.php) is made with a view that uses the Slick Carousel module to show a carousel of nodes of a certain content type (news).

Here's what's going on:

sometimes the URL on an item of the carousel loses the /abc part of the path, effectively sending users away from the site (ie, /node/123 when it should be /abc/node/123).
this happens when the user who created the node has a certain role (lower than admin). If admins create the node it doesn't happen.
it is only visible/only affects anonymous (not logged) users. If a user is logged in, be it either admin or otherwise (including the role for who this happens), the page shows up the correct URL (ie, /abc/node/123).
it only happens on that page/view. In other pages/views which list the news content type, the same node shows the correct URL for all users, either anonymous and/or logged in.
I (admin) can solve it in at least 2 ways:

unpublish/publish the problematic node;
clearing the cache

the problematic role has no way of solving this using the above methods.

Now, to add difficulty to the whole process, I have no control over the NGINX configuration, although I was told it was setup according to NGINX's Drupal recipe.

Also, in my dev environment this doesn't occur, even though the configuration settings are the same (it's exported every time I deploy to production). The only thing that might be different is the settings.php file.

Obviously, I have no debug facilities in place for the production website, so there isn't much I can do to trace the issue. Also, there are no log messages indicating something might be wrong with this page.

I'm now trying to find a way to replicate the production environment in a VM, but even so, I'm not sure where to start looking for the problem.

Can anyone share any thoughts on this?

EDIT: I have replicated the production environment with Docker containers and I can't replicate the bug.

Meanwhile, I have seen some even weirder things happening: sometimes (again, fixable by clearing cache), the menus also get the wrong URLs - I have a block menu holding a link to the login page that instead of going to www.example.com/abc/user/logingoes to www.example.com/user/login.

I guess clearing the cache forces the URLs to be rebuilt and apparently it gets fixed. But aren't URLs rebuilt anyway when you publish content? Why can this affect the menus as well?

Perhaps it is a NGINX config problem? Running Drupal in a subdirectory under Apache normally requires you to alter .htaccess and RewriteBase. I am not a NGINX admin but I would start by getting a copy of the running config. It might need stuff along

location ~ \.php$ {
        fastcgi_split_path_info ^(/abc)(/.*)$;
}

To avoid loosing in base directory.


Pitfalls when updating a site without entering maintenance mode? Assuming there are no module updates that require doing a database update, if it's just an update to a newer minor release of Drupal core, as well as of contrib and custom modules, what potential pitfalls should I watch out for when updating without entering maintenance mode?

We have 3 load-balanced web servers that all point to the same database and file server. The updates are generally done by first putting all the 3 Drupal instances into maintenance mode, waiting for a minute or two (not sure if this is necessary), then literally overwriting the entire application root directory with the newer version on each server, then clearing the caches on each of the servers, then exiting maintenance mode.

Is it safe to do this overwriting of the files while the site is live, without entering maintenance mode? I've heard of people doing this, but they have brochureware sites with not a lot of traffic and not a lot of logged-in user sessions (which we do have). Does doing so become more or less safe if you have multiple load-balanced web servers, use APC, use Varnish in front of the web servers, use nginx, use Memcache (which also stores sessions) between the web servers and the DB, have all pages using SSL, etc?

It would be great to seamlessly roll over to a new version without having to enter maintenance mode, but it feels risky to me. Are there edge cases where if your new files take a couple of minutes to overwrite the old files in the application root, then maybe some users are getting loading one module from the old set of files and one module from the newly-copied set of files, leading to strange and non-reproducible errors?

As you said there:

  but they have brochureware sites with not a lot of traffic and not a lot of logged-in user sessions (which we do have)

If accessibility is very important to your website I would suggest you do NOT take the risk to directly overwrite files for upgrading while the website is still up and serving. It may lead to corrupt data or broken response.

One approach could be take one web server out of the load-balance group, upgrade it while your website is still up and serving. After upgrade and test, put it back then upgrade another one, until all are done. In this way you can seamlessly upgrade without shutting down the service. It may sound complicated and boring, but it could be highly automated by writing some scripts I think.


How to place an image on a specific page I have created a page, page-5. I want to insert an image only on this page through .tpl.php not through the CMS itself. I have created an empty document page--page-5.tpl.php.
What content would go in there and how would I place my image?

For the front page, I was able to do with the following code:

<?php if (drupal_is_front_page()) {?>

<?php }?>

How to do for a specific page?

You can check template suggestions in the documentation.

  The list of suggested template files is in order of specificity based
  on internal paths. One suggestion is made for every element of the
  current path, though numeric elements are not carried to subsequent
  suggestions. For example, "http://www.example.com/node/1/edit" would
  result in the following suggestions:

  page--node--edit.tpl.php
  page--node--1.tpl.php
  page--node.tpl.php
  page.tpl.php

The template name started with "page--" is an override of page.tpl.php for a particular node or whatever.

Find out what is the node ID of your "page-5", let's say it is node ID 1.
Copy page.tpl.php and rename to page--node--1.tpl.php
Then you can update it as you need ( print your image like you did in the front page ).


Filter nodes based on active context Is it possible to filter nodes based on whether a certain context (defined by context module) is active? I can't find a way to do this. I'm using Drupal 6 and context 6.x-3.0.

Let's say we have a certain menu path that activates a context. In this context I have a view and I need to filter nodes that belong to the context (that is they belong to the menu, that activates the context).

Making context aware Views is not something you can easily do with Context module. That is I'm sure it would be possible, but it would require a lot of work.

Panels is designed to accomplish such tasks, with it's tight integration to views, it can pass arguments to views that you can use to determine what to display.


MAMP Pro with PHP 7 OPcode caching I installed Drupal 8 on MAMP Pro with PHP 7. I am getting this warning in my Drupal reports page:

  PHP OPcode caching Not enabled
      PHP OPcode caching can improve your site's performance considerably.
      It is highly recommended to have OPcache installed on your server.

I looked in MAMP's PHP 7 ini file and I see this code which seems to be related to OPcode caching.

[OPcache]
MAMP_OPcache_MAMP
  opcache.memory_consumption=128
  opcache.interned_strings_buffer=8
  opcache.max_accelerated_files=4000
  opcache.revalidate_freq=60
  opcache.fast_shutdown=1
  opcache.enable_cli=1

So I am not sure if I need to do anything else to enable it, it seems to be enabled based on the code above. I googled around and could not find any specific documentation with regard to MAMP and PHP OPcode caching.

Just make sure that the OPCache is selected as caching mechanism in MAMP preferences.

Click on "Preferences".
Click on the "PHP" tab.
Select "OPcache" under "Cache" field.


hook_permission and control access [how to redirect to the login page if user not logged in] How does one limit "what" can access a page. I have little understanding on how to use hook_permission() to set user permission based on a role to control access to hook_menu() items. However, what if I have a hook_menu() item that is to be used solely by the system itself? For example, say I have a registration page in a custom module: module/register - Anyone can access that page. Then, say I have an another page which is only for admin. So, I register another item in hook_menu(), call it module/register/reg_user_details - I do not want anyone to be able to browse to module/register/reg_user_details

Instead I want page to be visible only when user is logged in, I have already created a hook_permission

/**
 * Implements hook_menu()
 *
 */
function video_subtitles_menu() {
  $items = array();
  $items['video_subtitles/upload'] = array( //this creates a URL that will call this form at "video_subtitles_test/upload"
    'title' => 'Upload Subtitle', //page title
    'description' => 'Uploading subtitle for videos',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, drupal_get_form need to be used
    'page arguments' => array('video_upload_subtitles_form'), //Name of the Uplaod Form
    'access callback' => 'user_access',
    'access arguments' => array('administer video_subtitles module'),
  );

  $items['player/video_subtitle_status'] = array(
     'page callback' => 'video_subtitle_status',
     'access callback' => 'user_access',
     'access arguments' => array('administer video_subtitles status'),
  );
  return $items;
}

/**
 * Implements hook_permission.
 */
function video_subtitles_permission() {
  return array(
    'administer video_subtitles module' => array(
      'title' => t('Administer video_subtitles module'),
      'description' => t('Access the video_subtitles upload module Page'),
     ),
    'administer video_subtitles status' => array(
      'title' => t('Administer video_subtitles module status'),
      'description' => t('Access the video_subtitles module status Page'),
  ));
}

So User is not able to access my page unless user is logged in, but
what I need user should be redirected to the login page when he is not logged in as admin , if he successfully login it should be redirected to my page.

visit url d-7/example/my-module
if already logged in show the page
if not logged in redirect to the login page
if user logged in successfully redirect to d-7/example/my-module page

What is best way to achieve this

Similar Question

using-hook-menu-with-hook-permission-access-denied

using-hook-menu-and-hook-permission-to-control-access

can-someone-explain-access-arguments-in-drupal

Easiest way will be specifying this logic in page callback function. example:

function SOME_PAGE_CALLBACK($someArg) {
  if(user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }

  // do_something();
}

another way is checking the user in hook_preprocess_page function:

function MY_THEME_preprocess_page(&$variables) {
  if(curent_path() == 'SOME_PATH' && user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}

Access callback function checks the user's access to the request and returns boolean value, TRUE or FALSE, if you want to check if the user has an access to the page, you can do somthing like this:

$path = current_path();
if ($router_item = menu_get_item($path)) {
  if (!$router_item['access']) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}


How to I change the blogger's name button from all lower case to proper case in Omega 3.1 subtheme? I want firstname lastname's blog to be Firstname Lastname's blog

You could always use mb-convert-case, or you could just target it with css and use text-transform: capitalize.


Driver not specified for this database connection I want to connect to external database:

$old_database = array (
        'default' =>    array (
                'database' => 'grantexpert_registration',
                'username' => 'grantexpert_usr',
                'password' => 'xxxxxx',
                'host' => '62.168.127.59',
                'port' => '5432',
                'driver' => 'pgsql',
                'prefix' => '',
        ),
);

Database::addConnectionInfo('olddatabase', 'default', $old_database);
db_set_active('olddatabase');

But Im getting an error:

  Driver not specified for this database connection: olddatabase in Database::openConnection()

All the examples show exactly this structure of array, but it's not working. Is smoething wrong here?

You've already provided the target DB name with the second param to addConnectionInfo(), so you just need to remove the 'default' element from the array, and shift the connection params up:

$old_database = array (
  'database' => 'grantexpert_registration',
  'username' => 'grantexpert_usr',
  'password' => 'xxxxxx',
  'host' => '62.168.127.59',
  'port' => '5432',
  'driver' => 'pgsql',
  'prefix' => '',
);

Database::addConnectionInfo('olddatabase', 'default', $old_database);
db_set_active('olddatabase');


Create many to many Relationship with a specific fields in a Content type to taxonomy I am currently encounter a problem, I have one content type (Type) and two taxonomy needed to be link up, in that content type, I need to apply a many to many relationship among a field (Name: Core) and two taxonomy Terms (Such like below image), I would like to ask is there any method to implement this idea??

You will have to use entity_reference.

Add a field "Core" to your content type of entity reference.
Then under "target type", choose "taxonomy term"
Under "entity selection" choose your vocabularies
On the next page set "Number of values" to "unlimited"


Automatic username generation How do I create a user registration form where username field cannot be modified by the user and is auto-generated on the basis of two other fields in form (dynamically).

I know there are some modules available for the task in Drupal 7, but how do I achieve this in Drupal 8?

This is pretty simple. Create your module, then create a form "MyRegForm" where the user can input her email and (if needed) password (twice with the '#type' => 'password_confirm'). Then, in the submit() method create your user like this:

\Drupal\user\Entity\User::create([
            'name' => 'hGzfT54re39OpLLLk',
            'pass' => 'hGzfT54re39OpLLLk',
            'mail' => $data->mail,
            'status' => 1,
            'init' => $data->mail,
            'created' => time(),
            'changed' => time(),
            'login' => 0,
            'access' => 0,
        ])->save();

The change the username and add whatever roles you need with code like

    $tuser = user_load_by_name('hGzfT54re39OpLLLk');
    $tuser->setUsername('My super name logic');
    $tuser->addRole("whatever");
    $tuser->save();
    $rc = $tuser->id();

If you don't want to create your own form for registration, go for hook_form_alter and set the #access to the "name" field to false and add a #default_value.


How to make a discount on specific products quantity that have specific fields I'm a bit lost with a workcase.

I'd like to apply a discount to a few line items depending on their quantity and if the product if the line items have some specific fields.

An example will be a bit clearer:
If the user orders at least 10 differents product that share the same field value (let's say 5 different tshirt with the same color), the 10 corresponding line items in the order get a 5% discount.

I'm not familiar with rules.
I tried to make some loop on line items but i'm really in the dark here.

Some advices?
Thanks!

Hopefully you're using taxonomy fields for your color on your shirts. If you are, then your solution is easy because Commerce Taxonomy Conditions will do the job. You can have it set to a quantity of a particular taxonomy field being present in an order and have it apply some discount.


How do I disable the user login block I think I might found a bug(?)

Only administrators can create content on my site, so I am trying to
remove the login form from the front page, its okay that the login page
can be accessed at site/user/login, but not on the front page, I have tried quite a few things.

I have followed the guide in https://www.drupal.org/node/13777

Im using the bartik theme, I have sub-themed it, but I have barely changed anything in it, basically just a little css.

And I have tried the following:

admin/structure/block and hide the user login block.
admin/structure/block and completely removed the block.
admin/structure/block and moved it to a specific location and then hiding it based on page.
admin/structure/block and moved it to a specific location and then hiding it based on role.
admin/config/people/accounts and disabled register/login for anonymous users, which I guess works as they can't register, but the login form is still on the front page.
Hide the block with CSS, which works, but then I can't ever login before I change the CSS back.

Adding some images + github link:
Github link: https://github.com/DenLilleMand/christianssite
Imageone(frontpage):

Imagetwo(structureblock):

Imagethree:

I had a similar problem.

As described in the issue, we had the same problem in Drupal 7 with the "No front page content has been created yet" message. In Drupal 8, if you have no content on the page the default is to display the user page. If the user is not logged in, it defaults to the login page.

The best solution to this is to have content on the front page. However, assuming you want a blank front page except for some custom blocks, you can remove the Login Form by either creating or editing the existing
page--front.html.twig file in your theme.

Since you don't have any content on the front page, you can remove the "Content" region and then remove the "Header" region to remove the tabs.

EDIT: I just found that if you do remove the "Content" region from the page--front.html.twig file, this will also remove it from the login page, which is a problem. Not sure why this is. Still working on a solution.

Finally, make sure that you leave the "Front Page" setting blank = 'Manage > Configuration > System > Front Page'

These are the two blocks I removed from my theme

   {# Content #}
    {% block content %}

      {{ page.content }}
    {% endblock %}

  {# Header #}
  {% if page.header %}
    {% block header %}

        {{ page.header }}

    {% endblock %}
  {% endif %}


How can I use Mootools with Drupal 6? I am looking for a way to use Mootools with Drupal 6, without disabling jQuery, of course.

You will need to load JQuery in "noConflict mode" or MooTools in "Dollar Safe mode"; your best bet is to use "Dollar Safe mode" to avoid effecting Drupal.

See MooTools, Framework Compatibility, and Dollar $afe Mode, and The Dollar Safe Mode.


Where do you put your template override files? I am trying to get Drupal to recognize a template override that is a theme hook suggestion.
However, I don't know how to get Drupal 7 to recognize it.

Specifically, Drupal commerce allows for the override of a customer order using the template file
commerce-order--commerce-order--customer.tpl.php

I don't know where to put this.

I tried putting the file in my own theme directory, and clearing the cache. But it didn't recognize it.  Do I need to add something to the .info file of my theme?

I DID GET THIS TO WORK when I put the template in the main theme of the site, namely the omega_kickstart template directory. But this is not ideal for upgrading.

Finally, I tried making my theme a sub theme of omega_kickstart thinking it would override then, but that didn't work.

When creating new templates for your theme you need to name it to match your theme.

You'll want something like:

YOURTHEMENAME--commerce-order--customer.tpl.php


Access field value in template_preprocess_views_view_field function? I have a client with a Drupal 8 site who prefers curly quotes to straight quotes. I have successfully made this change for node titles using a regex replacement in template_preprocess_page_title. Now I am trying to accomplish the same thing for a different text field that is rendered by a view, using template_preprocess_views_view_field or template_preprocess_views_view_fields, but for the life of me I cannot figure out how to get individual field values using this function. Am I even trying the correct preprocess functions?

I have also tried rewriting the output of the field by accessing the variable in a custom twig template, with poor results.

It depends how you have your view set up.

If you have your view using the format 'Fields' then you can override the content with template_preprocess_views_view_field() like you say, like this (although you might want to target individual fields with some if statements):

/**
 * Implements hook_preprocess_HOOK() for views-view-field.html.twig.
 */
function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      // Replace characters in the field output.
      $variables['output'] = Drupal\Core\Render\Markup::create(str_replace('find', 'replace', $variables['output']));
    }
  }
}

If you are using the format 'Content' then you could do it at the field template level or node template level instead, since in that case it doesn't use the views field templates.


display views3 output at page--mypage.tpl.php Using drupal7 views3 i created views(products) to display an image and relevant title of my content. I selected in products to display content as block not page. I created an overriding page template page--mypage.tpl.php, where i impose my own html-css layout. My question is, that i want to display the content of newproducts block at page--mypage.tpl.php:

[title] [image], [title2][image2], [title3][image3]

I have created the html/css in page--mypage.tpl.php for the above layout. Now, i don't know how to retrieve the produts output to populate the above layout. For example, I used , or content);?>, but i couldn't accomplish my objectives. Someone who knows this theming could let me figure out this issue please![my html/css layout][1]!


Create / Edit node and continue editing on same page after submit D7 has module "Save & Edit".

There are any solutions for D8?

The Save & Edit module is a very basic module. It comprises of 6 total functions, so a port could be done less than a day.

Alternatively, if the your requirement is to just save editing progress while keeping the editor window up, the Autosave form module does that.

If you're looking to go the custom code route, some simple jQuery form manipulation can add a button which can trigger a form redirection & submit. For example:

// Set the form destination to the edit form and submit it.
jQuery('form.node-form').attr('action', '/node/<NID>/edit?destination=node/<NID>/edit');
jQuery('.node-form').submit();


Drupal 6 CCK fields export/import in between environments I have a Drupal 6 website that uses a lot of custom content types and along with a lot of CCK fields. Now with each new hotfix/patch/amendment new content types and CCK fields are added. Once the new code is developed in DEV Server it is moved to another to test. Then again after testing it is moved to QA then to the Production.

But with the increasing Content Types and CCK fields we are finding very hard to manage all those in moving to server to server.
So I googled and found
http://www.lullabot.com/articles/moving-cck-field-changes-from-dev-to-live
But the problem is, this tutorial is based on Drupal 5 and an older version of devel module packaged with macro module.
Now a days, macro is a separate module and it is not working as expected, its giving a lot of errors and the available patches are not able to solve it.

So is there any way to track all the Content Type Addition or Changes and the New Field or Existing Field addition or changes?

It would be really helpful if any solution is provided. Thanks!

Take a look at the Features module. Exporting your CCK fields as a feature set creates a new module in which the fields are defined in code. You can then deploy the code to another server and enable the feature there. Every time you make a change you export the feature again to update its code, deploy it, then revert it on the other server.

Features is very useful, but takes some practice to get used to its limitations and quirks. Once you get past that point it'll save you a lot of time.


Why is there a hash value at the end of this element ID? I've created an entityreference to a content type that is just a title and an image, and set the storage settings to unlimited.  Now, when I'm on the edit form and I click the "Add Another Item" button, the ID of the input that appears is: edit-field-photo-1-target-id--nOP2UjZ0zuI

Why is that --nOP2UjZ0zuI at the end, there?  It makes it annoying to select, even though I'll be able to search for an ID that starts with edit-field-photo-X-target-id as a workaround, but what does it do?

Here is my guess:

In HTML ID's are suppose to be unique. Since you're adding another item, the ID cannot be the same. Thus, the --nOP2UjZ0zuI is probably some random generated string so the ID is unique.


Bulk move content from one category to another - Drupal 7 I have a lot of content that I've imported into Drupal 7.  Unfortunately it imported to the wrong category.  Is there a way in Drupal or drush to bulk move that content from one taxonomy term to another?  Or is it a simple matter of assigning the new taxonomy term to the content?

Have you checked out Views Bulk Operations? How to batch assign taxonomy terms to nodes using Views Bulk Operations is a good blog post about how to accomplish this. Basically, make a view that displays the nodes you want to edit. Add a VBO field to this view (using the instructions in the above blog post) and then go to the page you created with the View to do bulk operations on the desired nodes.


How to execute javascript from within an ajax request OK, I'm doing some basic validation inside of an ajax form callback. I'd like to use the result to execute some javascript. What I've tried looks something like this:

inside my form alter:

if (isset($form_state['values']['field_temp_age'])) {
  if (validate())
  {
    //...return product information
  } else {
    drupal_add_js('alert("Validation fails!");', 'inline');
  }
}

This doesn't work. In this case, nothing is returned.

Also, tried this from inside the ajax callback:

function my_ajax_callback(&$form, &$form_state) {
  if (!validate()) drupal_add_js('alert("Foo!");', 'inline');
}

Not sure what's the approach here. How can I execute arbitrary javascript based on information returned from an ajax request?

Thanks.

Not sure of how you are making the AJAX call, but jQuery AJAX calls such as $.ajax let you execute a callback after the result has been returned. I recommend returning FALSE or a code indicating an error to your calling function and placing your "validation failed" logic inside of that in the success handler.


How to efficiently divide entities into groups based on field values Problem

I'm trying to create job alerts. So every user will select certain filter criteria on their account, which will then be used to perform a search api query returning the relevant new jobs.

To my inexperienced programmer brain this sounds like a lot of queries that will scale terribly.

So I'm trying to construct something which will organise the users into groups who have the same criteria thus avoiding repetition of queries.

(i.e. divide a set of entities into groups based on field values).

My question is, is there a function or commonly used set of procedures for doing this? (Perhaps a module which I could look to for the design?)

Or another option, would the performance change be minimal, because of things like memcache and APC which would cache the queries which repeated?

My current design

In order to do this, my current thinking revolves around creating a branching set of queries.

First divide users by field a options, then divide each sub option into field b options and so on.

Each time you'd check to see if you ended up with 0 or 1 users in which case you could stop the tree.

Because I already use SearchAPI and have indexes running for users and nodes I would use this to query. (I'm assuming it would be faster than pulling from the database).

As it turns out implementing the Search API Saved Searches modules is pretty much as easy as turning it on and it works great... No great insights here, just an excellent module.

It allows you to save searches with full facet information (i.e. filter search with 4 different facets and then save that.)


Contact form is not being translated I have a multilingual Drupal 7 site with following languages enabled:

Dutch (default)
French

Now when I enable my sitewide contact form, and navigate to it using Dutch (http://www.mywebsite.com/nl/contact) it is in Dutch (as it should be).

However, when I navigate to what is supposed to be the French version (using http://www.mywebsite.com/fr/contact), it shows me the English contact form ...

I have downloaded & imported the French .po file for the contact form to no avail , the contact form stays in English.

Does anyone know a solution to this problem?

Instead of using .po-files, install the Localization Update module.  It provides a much better interface for downloading, updating and managing translations.


How to proceed after update.php fails due to memory limit? Sometimes i have a "Fatal error: Allowed memory size exhausted" on certain drupal installations with low php memory limit during module or core updates. After such an error i regularly increase this value with the help of my webhoster to avoid this for future updates...

But on the drupal side i'm lost a bit. The system report shows no indication that the update has to be done again and doing it manually shows that there's nothing to update. But this process failed before...

How do i find out if something went wrong during the update.php process?

Short Answer
You can't. Though comment F0ns's comment is a good start, depending on your PHP skills you may find this frustrating to impossible.
Long Answer
I am not sure that the easiest resolution is to deal with the (possible) problem after the event.
I would not normally suggest this as an answer except that you begin your question with 'Sometimes', implying that this a is a workflow consideration rather than a specific bugfix.
You should consider your upgrade process in general. Ideally you would put the site into maintenance mode if you absolutely must perform the upgrades on a live site, so there would be no changes to the site during the process. You should always take a database backup before performing core or contrib updates, and this is made easy using backup_migrate module. If you are updating core backup the files as well (if it is contrib simpler to just download previous version)
As long as you know which updates you are applying (I do not recommend applying many at the same time), and what version of core/module you are upgrading from, then you can now easily return to your pre-upgrade state by overwriting the db and files, rather than trying to pick apart potential problems caused by a failed upgrade.
Depending on the usage of your site, it might be preferable preferable to limit administrative access to the site temporarily (or put it into maintenance mode), perform updates on a local clone of the site, and overwrite the live version with the tested, working local version, restoring administrative access.


How to customize the xmlsitemap? I installed the xmlsitemap module and would like to customize the sitemap.

For example, I would like to exclude some nodes that have a certain term reference field.
I would also like to be able to create separate sitemaps for each content type.

Is there a way to do that?
Otherwise I could probably generate the xml sitemaps with service_views module.

You can do the same with xmlsitemap modules

Enable XML sitemap node, XML sitemap taxonomy submodules.

After that you will get these options.


jQuery is not working for inserting data I want to save data from a textbox on a button click. I am using jQuery AJAX for this task. Please note that I made this tags inside theme function.

function theme_user_post_block($vars) {
  $themeUserCommentInput = '';
  $themeUserCommentInput .= '<textarea id="txt_1" rows="1" cols="50"></textarea>';
  $themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center" class="btnPostComment" id ="btn_1" / >';
  return $themeUserCommentInput;
}

This shows me the textbox and the button inside the page. This is my JavaScript code.

(function($) {
  Drupal.behaviors.PostComment = {
    attach: function(context, settings) {
      $('.btnPostComment', context).click(function(event) {
        var post = "&newcomment=Comment1&logid=log1";
        jQuery.ajax({
          url: 'postcomment',
          type: 'POST',
          dataType: 'json',
          data: post,
          success: function(data) {
            alert(data);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + errorThrown);
          }
        });
      });
    }
  }
})(jQuery);

Next I create a custom page as follows.

function postcomment_menu() {
  $items = array();
  $items['postcomment'] = array(
      'title' => t(''),
      'type' => MENU_CALLBACK,
      'page callback' => 'user_comment_post',
      'access arguments' => array('access content'),
  );
  return $items;
}

function user_comment_post() {
  global $user;
  $cid = db_insert('user_comment')
          ->fields(array(
              'comment_user_id' => $user->uid,
              'reference_id' => $_POST['logid'],
              'comment_desc' => $_POST['newcomment'],
              'createdon' => REQUEST_TIME,
          ))
          ->execute();
  if ($cid != 0) {
    //GetUserComments($i);
    drupal_json_output("success");
  }
}

So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.

I added 'async': false to the jQuery.ajax call as follows.

jQuery.ajax({
  url: 'postcomment',
  type: 'POST',
  dataType: 'json',
  'async': false,
  data: post,
  success: function(data) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert(textStatus + errorThrown);
  }
});

The code is now working.


Add stock field to product display containing multiple SKUs I've been trying forever to create a stock field for a product display that contains multiple product skus. I want to do this so that when each variation is purchased, it is subtracted from the total number of items in stock. Commerce Stock seems to let you track stock for individual skus, but not for one product with multiple skus. For example, I have a total of 100 shirts, but 10 shirts are pink, 10 are red, 10 are blue (hence, the different SKUs). That said, when 2 blue shirts have been purchased, I want the stock to drop from 100 to 98 on the product display. Out of the box, this isn't possible.

I tried using the answer in Synchronize commerce stock for product variations, but I'm unable to achieve the same result. I created a master stock text field on the product display, but I can't seem to set rules to subtract from the new field. Does anyone have clear instructions for doing this via rules?

In short: I am looking for a simple way to synchronize all product variant's stock in a single product display.

** UPDATE

I have SUCCESSFULLY obtained the nid of a product display, and then, fetched Product Display by that nid with the below rule settings. That said, when I try and add an action to set data for my custom stock field (product_stock) located on my content type Product Display, rules can't seem to find it? How is this happening?

FETCH ENTITY BY ID SCREEN

THE SELECTORS I DO GET WHEN I DO FETCH ENTITY BY PROPERTY:

First, you will need to add an entity reference field to your line items. This will reference the product display node.

Then using Views Rules create a line item view with a "Rules Display"

For "contextual filter" add Order ID.
For "fields"

Add the quantity
Add Node ID (nid) of the referenced Product Display Page.

Now in your rule simply add a view loop and pass the Order ID as a parameter.

Inside the View loop:

Fetch entity from ID, pass the NID from the view result.
Do Calculate a value. Get the fetched entity quantity -  view result quantity
Set a data Value for fetched quantity field, calculated value.


How can I create a custom ajax callback command? I found different type of ajax commands like htmlCommand, invoke command etc. I want to create a custom ajax command that sets the response of ajax callback as the value of specifying markup in the callback argument. Is it possible? I created one as per this tutorial.

    public function ajax_call_back_function() {
       $response = new AjaxResponse();
       $element  = $form_state->getTriggeringElement();
       $returnDelta = $element['#array_parents'][2]; // get levels
       $delta = $element['#value']; // eg : 944 THis is the ata i want to set as the value of markup
       $response->addCommand(new ReadMessageCommand($delta, $returnDelta));
       return $response;
    }

The ReadMessageCommand class is the following.

    class ReadMessageCommand implements CommandInterface {
      protected $message;
      // Constructs a ReadMessageCommand object.
      public function __construct($message,$level) {
      $this->message = $message;
      $this->level = $level;
      }
     // Implements Drupal\Core\Ajax\CommandInterface:render().
    public function render() {
       return array(
      'command' => 'readMessage',
      'message' => $this->message,
      'level' => $this->level,
     );
   }
  }

I include a JavaScript file.

    (function($, Drupal) {
      Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
      $('#edit-field-region-management-'+response.level+'-valueregion').val(response.message);
     };
    })(jQuery, Drupal);

The controller class is the following.

   class AjaxCommandsAddController extends ControllerBase {
     public function messagesPage() {
       $page[] = array(
         '#type' => 'markup',
         '#markup' => $content,
     );
// Attach JavaScript library.
       $page['#attached']['library'][] = wms_ajax_commands/wms_ajax_commands.commands';
       return $page;
      }
    }

But when executing, I get the following error.

  Fatal error: Class 'Drupal\Core\Ajax\ReadMessageCommand' not found in Path-to-module/src/Plugin/Field/FieldWidget/RegionWidgetType.php

It seems like you have a namespace error(s). The error happens in a file you didn't mention RegionWidgetType.php. It's trying to use Drupal\Core\Ajax\ReadMessageCommand which as I understand it is something you made. Which means that the namespace should definitely not be \DrupalCore\... for the auto load to work.

The name space of your custom files should be Drupal\MODULE_NAME\folder\structure


How does AccessResult::neutral() work? I have seen in code:

AccessResult::neutral()
AccessResult::allowed()
AccessResult::forbidden()

allowed() and forbidden() are pretty obvious, but how does neutral() work?

I have been debugging and sometimes neutral() allow access and sometimes it doesn't.

“Neutral” basically means “I don’t care” in this context.

Returning it means you’re saying that your code has no opinion on whether access should be granted or not, and that other methods/modules should make the decision.