Taxes not updated after manually adding a product to an order. Drupal Commerce Using Commerce 7.x-1.10.

I created several tax rules to fit different countries. All of them works fine through the checkout process.

The problem is that if I (as admin user) manually add a product Line Item to the order at: admin/commerce/orders/ORDER-ID/edit, then the taxes are no re-calculated.

I already enabled the option: Enable the local action link on order edit forms to apply pricing rules. in this admin page: admin/commerce/config/order. Loop my capture bellow. I expected to see a link in the edit order form, but I see no link there. What's the goal of this feature??

To reproduce:
1) an order is created
2) as admin user I go to `admin/commerce/orders/ORDER-ID/edit`
3) add a new product to the order
4) save
5) the taxes are not re-calculated

UPDATE 2: changing the order status didn't work for me: https://www.drupal.org/node/1094266#comment-4269794, https://drupalcommerce.org/questions/4302/rules-not-firing-during-admin-order-editing

We ran into the same issue which we worked around by using the Drupal Commerce Point of Sale module to manage manual orders.

As of now, the button "apply pricing rules" is working for us in the order editing form to apply the taxes but we found it easier to use Commerce POS. Your mileage may vary...

Hope this helps!


How do I set a table header in Views 3? How exactly do I get a table header to appear above the table?
In views-view-table.tpl.php I can see a <thead> section, but what causes it to actually get rendered?
Where do I specify the column header text?
I tried various options in the settings page, but to no avail.

The title can be defined from the Main views form.  Each column of the table is associated with a field.  If you select the field you can "add label" by selecting the checkbox and providing a name.  The Label will appear in the header of the table.


How to add an extra field in file upload widget? I know that it is possible to enable a description field in the core file upload widget for Drupal 7.

However, I want to add an extra description field like the one already present. For this I've spent hours googling, but not found the perfect solution. Please, someone, help me to solve my problem

This module might be a great way to do what you want. The File Entity module is a module that creates fieldable files. Try to read the module description, hope it helps you.

  File entity provides interfaces for managing files. It also extends
  the core file entity, allowing files to be fieldable, grouped into
  types, viewed (using display modes) and formatted using field
  formatters. File entity integrates with a number of modules, exposing
  files to Views, Entity API, Token and

UPDATE now you want to add an entity reference field on your content type that references your custom file.


How to deal with files with %20 in name in Nginx I have imported a lot of files from apache staging to nginx live and the files that have been rewritten by apache (%20 etc) are not being read by nginx, although nginx has no problem with me uploading files with spaces in them it doesnt like files with %20 etc. in the title.

I am using Perusio's nginx config which works great but i cant tweak it to fix this.

Any ideas?

Think outside the box of web server configuration.

Install the Transliteration module:

  Provides one-way string transliteration (romanization) and cleans file
  names during upload by replacing unwanted characters.

And install the File Field Paths module:

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

  Features ...

  Retroactive updates - rename and/or move previously uploaded files
  (Use with caution)

With both enabled you can goto the Content Type's Manage Field page and edit the field with the file(s) and enable Transliteration on the file name to be retroactively assigned to all uploaded files.

This will change the space character ' ' to '_' for all uploaded files.

Then you don't need to worry about difficult server configuration issues. I've used File Field Paths to rename thousands of files successfully on production systems.


programmatically exclude new fields from render() I need to render a limited number of fields from a given content type, without exposing the new ones I may add some day in the future.

Now I have:

print render($page)

When a new field is added to the content type, I have that added to the render($page) as well. I don't want this to happen.
Aside hiding the field from "admin/structure/types/manage/CONTENT_TYPE/display", how can I programmatically exclude new fields from render.

A common way is to use hide() function in a preprocess hook as:

hide($page['field_machine_name']);


Advanced forum topic list pagination settings is not applied I tried to change the pagination settings (number of elements displayed) in the view corresponding to the topic list, but in the front end, this setting doesn't seem to be applied.
the original value was 20 elements displayed, but the value really applied is 25.
Does anybody know why is that and how can i set this setting properly ?

I found the solution :
The pagination settings in the view are ignored, instead the number of topics displayed on a page is set in the forums configuration in /admin/structure/forum/settings


How do you prevent twig variable from last instance of template overriding those that go before it? I am creating a module that will allow editors to display nodes as "cards" using the summary from the node for the card text and a field (field_hero) as a background image to the card, the user can then click-thru to the actual content from the card.  The editor can also define, via the layout builder the colour behind the text for the card and also where the text appears (top, left, right, bottom).

If I add several of these cards to a page using the layout builder, all of the cards use the values for position and colour from the last instance placed on the page.

My code block plugin code is:

  public function build() {
if ($entity_id = $this->configuration['entity']) {
  if (($entity = $this->entityStorage->load($entity_id)) && $entity->access('view')) {
    $render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
    $view_mode = isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : 'default';

    if (isset($this->configuration['card_colour'])) {
      $entity->card_colour = $this->configuration['card_colour'];
    }
    if (isset($this->configuration['card_layout'])) {
      $entity->card_layout = $this->configuration['card_layout'];
    }

    return $render_controller->view($entity, $view_mode);
  }
}

return [];

}

And my twig template is (ignore the empty url() in the style attribute):

{%
    set classes = [
        'node-card',
        'card-' ~ node.card_layout|clean_class,
        node.card_colour|clean_class,
        'clearfix'
    ]
%}
<article{{ attributes.addClass(classes) }}>
    <div{{ content_attributes.addClass('bg-img', 'clearfix') }} style="background-image: url()">
        <div class="summary">
            {{ content.body }}
        </div>
    </div>
</article>

$render_controller->view() invokes hook_ENTITY_TYPE_view() and this would be a better place to add custom values to the entity view.

Although probably not good practice you could get your approach working by cloning the entity before modifying the field values:

$entity = clone $entity;

In any case you need to adjust caching so that you store for each variant a different cache item in the render cache. For example by adding cache keys to the build array before returning it:

$build = $render_controller->view($entity, $view_mode);
if (isset($entity->foo)) {
  $build['#cache']['keys'][] = $entity->foo;
}
return $build;


hook_menu_alter not working I'm trying to alter tab names ("view current" and "edit current") but it is just not working.

function MY_MODULE_custom_menu_alter(&$items) {
    $items['node/%node/view']['title'] = t('View Event');
    $items['node/%node/edit']['title'] = t('Edit Event');
}

Module implementation is good. Cache is cleared. Tried it milion times, but still nothing!

Wondering is it possible that this code is being overriden somewhere, and how can I check that?

If your hook implementation is definitely being fired then it does seem likely that another module (or even a theme, potentially) is overriding your changes.

To ensure your module's implementation runs last, you can implement hook_module_implements_alter():

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

If that isn't the problem, it might be something simpler...if your code is copied verbatim then you're setting the title twice for the same path. You might have meant

$items['node/%node/view']['title'] = t('View Event');

Or it might even be a combination of both of those.


Why is my Rules page redirection based on data comparison not working? I have to redirect to specific page for article content based on the its entity reference field value
Eg : article content having field_test2(field_name) reference to sample / 10164( taxonomy reference field value ) should be redirect to events
I have done this in rules. But the page redirection is not working. I have printed all the variables in article twig all are same but redirection not working.
status: true
dependencies: {  }
id: test_workflow_rules
label: 'Test Workflow rules'
events:
  -
    event_name: 'rules_entity_view:node--article'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 48cf31fd-db17-4f6a-ad75-71e9ea7b6b06
  weight: 0
  conditions:
    id: rules_and
    uuid: 3c51e865-1f88-429d-b363-bd7ed62a018f
    weight: 0
    conditions:
      -
        id: rules_condition
        uuid: 45c0f11a-34a3-487d-9e1c-30b3300ee9bf
        weight: 0
        context_values:
          type: article
          bundle: article
        context_mapping:
          entity: node
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: 647b13df-27ec-4c53-88fb-aa010c9e0021
        weight: 0
        context_values:
          operation: '=='
          value: '10164'
        context_mapping:
          data: node.field_test2.entity.tid.value
        context_processors:
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: 2f6d63e8-fb96-4014-b504-900d4763aa08
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 48790fb3-7658-45df-8a8d-ecc6e0f83ff0
        weight: 0
        context_values:
          url: /events
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect

The module version - 8.x-3.x-dev
Removing the data comparison and entity is of bundle , the redirection works.

Your conclusion is wrong. You say that page redirection does not work, but what is really happening is that your conditions are configured wrong so the redirect action is never used.
For the rules_entity_is_of_bundle condition, you have:
      type: article
      bundle: article

But articles are node types, so the type: should be node. This condition will never be true because of the way you've configured it.
In general, you should debug your Rules one step at a time and use the rules_system_message action to display a message on the screen for debugging. First use just the event and the system message action to ensure the message is shown when you expect them. Then add conditions one at a time to see if the conditions evaluate as you expect them to. You can use the system message action to display the values of data like {{ node.field_test2.entity.tid.value }}, which will help you see whether the values are what you expect. After you have the conditions working the way you want, then add the redirect action.
You can also turn on Rules debug logging to see what Rules are being triggered, by what events they're being triggered, and see the result of each condition evaluation.


How to setup cookie domain? I am trying to set $cookie_domain in my settings.php within Drupal 8.

In Drupal 7, I add this in settings.php to set it up, but I am not sure how to do it in Drupal 8:

  $cookie_domain = ".domain.com";

Thanks a lot

This is a container parameter now.

Put this in services.yml or another service definition YAML file:

parameters:
  session.storage.options:
    cookie_domain: '.domain.com'

Since it is in a yaml file, it can't easily be dynamic, one option you have is having multiple yml files, and you dynamically add the one for the right environment, or you have a services.local.yml, just like settings.local.php that you have on each environment and not in git.


How to add a cck email field as default value in webform I have a content profile type with a cck email field (this is not the user email and so is not the author's email field). I would like guests to be able to send a contact form (webform) to the email address in the cck mail field.

I have the field displayed via views in a panel so I can change the link to output the url to include the email address and use %get in the webform but that is obviously not the way to go as it exposes the email address.

So can it be done using %post or php in the webform?

Using D6 & webform 3

Many thanks

If you are using the Email Field module then it is possible.

In your view choose your email field , on Format option choose the Email contact form option.  It won't expose the email.


Can't add taxonomy term to node? This code saves the taxonomy term, but it doesn't add it to the node.
What is the problem?

             $node = new stdClass(); // Create a new node object
            $node->type = "article"; // Or page, or whatever content type you like
            node_object_prepare($node); // Set some default values
            $node->language = en; // Or e.g. 'en' if locale is enabled
            $node->title = $title;
            $node->field_image['und'][0] = (array)$file;
            $node->uid = '1'; // UID of the author of the node; or use $node->name

            $tags = explode(",",$sended_tags);
            $vid = 1;

            $term = new stdClass();
            $term->name = $tags[0];
            $term->vid = $vid;
            taxonomy_term_save($term);

            $node->taxonomy[] = $term;

            node_save($node);

You can do it like this:

if ($foo = taxonomy_get_term_by_name($term_name)) {
      $foo_keys = array_keys($foo);
      $node->your_taxonomy_field_name[LANGUAGE_NONE][]['tid'] = $foo_keys[0];
    }
    else {
      $node->your_taxonomy_field_name[LANGUAGE_NONE][] = array (
        'vid' => 1,
        'tid' => 'autocreate',
        'name' => $term_name,
        'vocabulary_machine_name' => 'machine_name'
      );


How to get the current viewed users uid If I am viewing a users profile page, how do I obtain and display (in a block) their uid? NOTHING to do with the current logged in user. I need to display the users id in a block on their page.

If you are showing a standard drupal user profile page this should get you going:

  $user = user_load(arg(1));
  $user->uid; // access user id

This assumes the path is user/uid. If your path looks different adjust the arg(position_in_path) to your needs.


Possible to use tags/buttons as exposed filters? I have a view that will be a grid of a dozen content types. I would like to have a tag-like button or text link above the view of content to allow the user to toggle / filter between what content type they wish to see. I know that exposed filters allows you to use a dropdown or auto-complete, but is this possible with using tags as buttons?

It sounds like you want to have something like this, what is provided by the Facet API module (Drupal 7) or Facets For Drupal 8.

Image copied from: https://www.webwash.net/drupal/tutorials/intro-search-api-part-2-faceted-search (explanation of Facet API combined with Search API).  It should however also work with the Drupal core search system. (I only used it with Search API)

  The Facet API module allows site builders to easily create and manage
  faceted search interfaces. In addition to the UI components that come
  out of the box, themers and module developers can build their own
  widgets that can optionally be contributed back to Drupal.org. Facet
  API works with the core Search, Search API, and Apache Solr Search
  Integration modules (including Acquia Search) meaning that code and
  configuration can be reused as-is with the most popular search
  solutions available to Drupal. Refer to the documentation for more
  details.

Each facet will be exposed as a block, that you can place anywhere in your site from the block administration page.


hook_user_update() is invoked before saving the user account, not after I created a module that implements hook_user_update().
As far as I understand this method is called once a user has edited his data and this has been saved to the database.

The problem I notice is that it is not what really happens with my code: The code is called before.

function mymodule_user_update(&$edit, $account, $category) {
  $username = "username";
  $password = "password";
  $database = "database";

  mysql_connect(localhost,$username,$password);
  @mysql_select_db($database) or die( "Unable to select database");
  $query = "select * from somewhere;";
  $result = mysql_query($query);

  $num = mysql_numrows($result);

  $myFile = "some_file.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");
  $stringData = "now: ".date('Y-m-d H:i:s')." Value is:".mysql_result($result,0);
  fwrite($fh, $stringData);
  fclose($fh);
}

When I check the result at this point, the values are still the ones before saving the user account.
I thought it would be some kind of database cache but this is supposed to be deleted once you edit the table.

Actually, in Drupal 7 user_save() first invokes hook_user_presave(), then saves the user account in the database, and invokes hook_user_update() or hook_user_insert().
It is not possible that hook_user_update() is called before the user account has been saved.
hook_entity_update() and hook_entity_insert() are invoked right after hook_user_update() and hook_user_insert(). Eventual field updates should be executed with those hooks.

// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

// …

if (is_object($account) && !$account->is_new) {
  // ...
  $success = drupal_write_record('users', $account, 'uid');
  if ($success === FALSE) {
    // The query failed - better to abort the save than risk further
    // data loss.
    return FALSE;
  }

  // …

  user_module_invoke('update', $edit, $account, $category);
  module_invoke_all('entity_update', $account, 'user');
}
else {
  // …

  $success = drupal_write_record('users', $account);
  if ($success === FALSE) {
    // On a failed INSERT some other existing user's uid may be returned.
    // We must abort to avoid overwriting their account.
    return FALSE;
  }

  // …

  user_module_invoke('insert', $edit, $account, $category);
  module_invoke_all('entity_insert', $account, 'user');

  // …
}

// …

In Drupal 6, user_save() invokes hook_user('update'), saves the user data in the database, and then invokes hook_user('afer_update'); if the user account didn't exist before, it saves the data in the database, and then invokes hook_user('insert').


Migration: the "csvrownum" should start from the second row I am importing some nodes from csv file in drupal.

I am assigning row number to one of the field of that content type.

The first row in the csv is the header which contains the column names only. The data start from the second row.

I am using the "csvrownum" for the csv row number. But it starts from the first row. It should exclude the first row as the data starts from the second row. How will I do this?

Here is my code:

$this->source = new MigrateSourceCSV($path, $columns, array('header_rows' => 1));
          //The destination CCK (boundle)
          $node_options = MigrateDestinationNode::options("en", "full_html");
          $this->destination = new MigrateDestinationNode('lot', $node_options);
          $this->map = new MigrateSQLMap(
              $this->machineName, array(
            "csvrownum" => array(
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'alias' => 'import'
            )
              ), MigrateDestinationNode::getKeySchema()
          );
          //Field mapping
          $this->addFieldMapping('title', 'Title');
          $this->addFieldMapping('field_number', 'csvrownum');

I think that's the expected behavior, you could use the prepareRow() method to increment csvrownum in whatever your header_rows is.


Change image extension on submission I am using D7.12 with webform 3.18. I want to change the image extension from png to jpg of the image uploaded through the form before saving it to database. I tried mytheme_webform_submission_presave() in template.php but didn't help me. How can I do this?

You need to use imagecache actions module to auto convert images from one extension to other.

Module Project page tells it provides

  File Format switcher - If you need tranparency in JPGs : make them
  PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is
  distributed as part of the color-actions submodule)


Views PHP: Getting field values and generating link I want to generate the RSS feed of my calendar as:

PHOTO (uploaded photo)

BODY

http:://www.example.com/content/the-title (Link of feed to the content page)

For this I use a "Global: PHP" field in the calendar view I created, entering code in "Output code".

I didn't succeed in printing the node body using:

<?php echo $row->body; ?>

With this, I get the ID.

The following gives no result:

<?php
$node = node_load($row->nid);
print_r($node);
?>

Using:

<?php print_r($row); ?>

I got:

stdClass Object
(
[title] => The title
[body] => 1311
[rendered_entity] => 1311
[php] =>
)

How to I get the real content of the body, image link (field_photo) and the content link?

Thanks,

Try using these code

$body = $data->_field_data['nid']['entity']->field_image['und'][0]['body'];

OR

$node = node_load($data->$nid);
$body = $node->body[0]['value'];

This may be because of the issue here


How can a user access only one specific node, and not all nodes of that type? I have a user with view and edit rights to a specific content type. This give the privilege to all users to view and edit all the nodes of that type. But actually, I want to create for each user a unique node, so that only that user may view and edit it. How can I do this in Drupal 7 ?

Using an existing module, you can do that with Content Access, which (when used  together ACL) allows to set the permissions to access a node for each user.
This means that you need to set the access permissions manually for each node.

If you manually create the nodes, and then you want to be sure that only the user who is set as owner of the node is able to view (and edit) it, then you can create a custom module (which means a module that is used for your site), and implement hook_node_access() as follows (the code has been written to make it easier to read):

function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $bool = (
      ($node->type == 'the node type you need to check') &&
      (($op == 'view') || ($op == 'update'))
    );
    if ($bool) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

Using this hook implementation, you don't need to manually edit the access permissions given  for each node of that content type you create. Changing the owner of the node would also be easier, as you don't need to change the access permissions of that node; the code would automatically grant the update and view permissions to the user set as owner (or author) of the node.


Error during "composer drupal-update" for Drupal 8.0.5 I've been running a Drupal 8 site since 8.0.0, using the Address module. As this required some CommerceGuys dependencies in the /vendor folder, I've been using the following commands to load dependencies (and update to newer versions of other components):

php sites/all/modules/composer_manager/scripts/init.php
composer drupal-update

However when I run this for 8.0.5, I'm getting the following error (not all output included):

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup

  Removing guzzlehttp/promises (1.0.2)
  Installing guzzlehttp/promises (1.0.3)

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup

  Removing guzzlehttp/guzzle (6.1.0)
  Installing guzzlehttp/guzzle (6.1.1)

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup

  Removing symfony/browser-kit (v2.7.6)
  Installing symfony/browser-kit (v3.0.3)

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup

  Removing fabpot/goutte (v3.1.1)
  Installing fabpot/goutte (v3.1.2)

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup

  Removing behat/mink (v1.7.0)
  Installing behat/mink (v1.7.1)

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  Script Drupal\Core\Composer\Composer::vendorTestCodeCleanup handling the post-package-update event terminated with an exception

  [RuntimeException]
    The directory 'tests' in package 'behat/mink' does not exist.

The CommerceGuys modules components are not getting loaded. I'm not sure if this is because of the above exception.

This has worked for every previous Drupal 8 update, so I'm not sure what's different this time.

There is a patch available here - https://www.drupal.org/node/2664274#comment-10954323, which is RTBC.

I can confirm it's working :)


custom block menu path returns json Ok, but a 404 status header I created a custom path via hook_menu with a page callback to a function that prints json.

It all works in the sense that requesting: http://cms.tripchi.com/tripchi/getme returns my JSON, but the header says it's 404 which is throwing off everything in the app. This only returns the 404 status on the client's godaddy server (PHP Version 5.4.19 w/ CGI/FastCGI), but returns 200/Ok on my local PHP Version 5.3.5 w/ Apache 2.0 Handler. All Drupal configurations and databases are equal.

hook_menu

function tripchi_menu() {
    return array(
        'tripchi/getme' => array(
            'title' => 'My Profile',
            'description' => 'mobile test for user status and object',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'page callback' => 'tripchi_getme')
    );
}

callback function

function tripchi_getme(){
    $user = $GLOBALS['user'];
    $json = array();
    // ... a bunch of stuff to construct a special array;
    drupal_add_http_header('Status', 'Ok');
    drupal_add_http_header('Access-Control-Allow-Origin', '*');
    http_response_code(200);
    //echo json_encode($json);
    drupal_json_output($json);
    drupal_exit();
    //die();
    // i've tried all combinations of commenting/uncomming the above...
}

below screenshot of the requests locally (right) and remotely (left):

why does this always return 404 but also give me my perfectly json encoded data?

First of all, for JSON output use drupal_json_output as a delivery callback in your menu. It will make thinks much easier:

function tripchi_menu() {
    return array(
        'tripchi/getme' => array(
            'title' => 'My Profile',
            'description' => 'mobile test for user status and object',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'page callback' => 'tripchi_getme',
            'delivery callback' => 'drupal_json_output'
         ),
    );
}

Then in your menu callback just return array. You don't need any other fancy stuff. I also faced 404 issue, but with this solution AND explicitly set response code 200 everything worked fine.

function tripchi_getme(){
    global $user;
    $json = array();
    // ... a bunch of stuff to construct a special array;

    // Only this was needed to make the stuff work.
    http_response_code(200);

    return $json;
}

I couldn't tell if the cause of my trouble was drupal or apache or both, but this certainly helped. Note that Access-Control-Allow-Origin was not needed to make this work (and I didn't plan to use cross domain calls either).


Get drupal breadcrumb by providing nid? How can I get a breadcrumb path by providing $nid?

Example

$nid = 116;
$breadcrumb = breadcrumb_get_crumb($nid);

I have a node type that is always associated with another node, and I want to use that node's breadcrumb trail for this node too.

You could use Crumbs module.
Now, if you say these nodes are "associated", I wonder how exactly? With an Entity reference field? Or just that you know the parent? Is this for all nodes of this type, or just for this specific one? Are these nodes somewhere in a menu?

If you can arrange either of the criteria above, you can use existing Crumbs plugins. Otherwise, you could do a custom module..


Mapping roles to users while migrating Following [this][1], I have  done migration for users from Drupal 7 to Drupal 8, but I got stuck with assigning roles to the specified users.

In user.php file, my code for mapping roles to assigned users is the following.

public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');
    // user_role

    $result = $this->getDatabase()->query('
      SELECT
        r.rid, r.name, ur.uid
      FROM
        {role} r, {users_roles} ur
      WHERE
        r.rid = ur.rid
      AND
        ur.uid = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      $row->setSourceProperty('roles', $record->name );
    }

    // local_market field of type entity_reference
    $result = $this->getDatabase()->query('
      SELECT
        fld.field_local_market_target_id
      FROM
        {field_data_field_local_market} fld
      WHERE
        fld.entity_id = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      if (!is_null($record->tids)) {
        $row->setSourceProperty('local_market', explode(',', $record->tids) );
      }
    }

    return parent::prepareRow($row);
  }

Except roles and custom field, field_local_market, all users migrated from Drupal 7 to Drupal 8.

destination:
  plugin: entity:user

process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  changed: changed
  access: access
  login: login
  timezone: timezone
  langcode: language
  preferred_langcode: language
  preferred_admin_langcode: language
  init: init
  field_local_market: local_market
  field_user_role: user_role

What's the right way to assign roles to the users?

Migration of roles is done from Drupal 7 to Drupal 8 by using drush migrate_upgrade; the only task left is assigning/mapping these roles to certain UIDs or users.

You can migrate users with roles without migrating roles using migrate static_map

In migrate set

  process:
  uid: null
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  access: access
  login: login
  roles:
    plugin: static_map
    bypass: true
    source: roles
    map:
      5: new_role_name
      3: editor

and in the source plugin you have to set the roles in prepareRow

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');

    $query = $this->select('users_roles', 'r');
    $query->fields('r', ['rid']);
    $query->condition('r.uid', $uid, '=');
    $record = $query->execute()->fetchAllKeyed();
    $row->setSourceProperty('roles', array_keys($record));

    return parent::prepareRow($row);
  }


Getting different results for admin versus non-admin user on view when there is a relationship I have a view that shows the two newest articles with specific taxonomy rules. We got a new requirement to now exclude articles that are linked via entity reference.

So I added the relationship for referencing entities. With just the relationship in place and no filters added, non-admin users only see articles that are related (the relationship is not set to required).

When I add the filter that node ID of the related (referencing) articles should be NULL, non-admin users see nothing, but admin users see the results as they should be.

What can explain the discrepancy and what can fix it?

Drupal 7

Seems like this problem is related to this drupal bug https://www.drupal.org/node/1349080 .

Solution: Edit your view > Right column "Advanced" > Query settings: check "Disable Query Rewriting"

Simple explanation for the bug and the solution https://www.drupal.org/node/1276450#comment-10451305, quote the comment below

  Actually, this is a bug, in Drupal core, and there is a fix, in
  #1349080: node_access breaks any query that has node table appearing twice with a left join. It just has not been committed to Drupal core
  yet, because the fix is a bit brittle and may not work in all corner
  cases. It has to do with the node_access system, and any view that
  connects the node table or an entity table multiple times (e.g. via a
  relationship), when there is any access module enabled on the site,
  will trigger it.

  Disabling SQL rewriting will bypass the issue, and should be entirely
  safe to do, unless you have some access rules you want to enforce
  (such as products in an OG group that only members of that group
  should be able to see) -- in which case you can usually address that
  by adding your own explicit filter to the view instead of relying on
  the core node access to filter it out for you.

  If all your products are public, there's no need for this node_access
  check.

Cheers


How can I add a new value for a multi-value field programmatically? If there is a unlimited user text field named "user_log_field", How can I add a new value for it?

I'm planning to log the IP and location for each user every time they login. Is using an unlimited user text field a good idea for this purpose?

Architectually speaking, it would be much better if you use custom table for this functionality.You can take a look for inspiration (or even use) the following module:

https://www.drupal.org/project/uiplog

From the description of the project:
User IP Log is a simple module that logs the IP address of users on login event to table {uiplog}.

Updated answer:
Since you want to do it yourself. You can implement a hook_user_login in your custom module.
https://api.drupal.org/api/drupal/core%21modules%21user%21user.api.php/function/hook_user_login/8.2.x

Inside you can just paste the following code.

Assumptions/ notes :

This is simple text field is from the type: "Text (plain)". If
you choose any other option I am not sure if this snippet would work
for you.
The machine name of the field is field_field_1. Not the best name but
you could quite easily change that on line 5.

I have added quite a few sanity checks that I think would be helpful on the long run.

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// The machine name of the field.
$field_name = 'field_field_1';
// Sanity check against the machine name of the field.
if ($user->hasField($field_name)) {
  $field_config = \Drupal\field\Entity\FieldStorageConfig::loadByName('user', $field_name);
  // Checks if has unlimited cardinality, otherwise the appendItem will throw
  // weird error.
  if ($field_config->getCardinality() == '-1') {
    // This is a fancy way to return $_SERVER['REMOTE_ADDR'].
    // Keep in mind that on localhost, this will return ::1.
    $a = \Drupal::request()->getClientIp();
    $user->$field_name->appendItem(\Drupal::request()->getClientIp());
  }
  $user->save();
}

Regards,

Oleg


Use one textfield for searching in two or more fields in Views I have a simple content type in Drupal 7 with title and body (and other fields). I've defined a view with exposed filters.

I want just one text field that searches in title or body. So, if I search for 'foo' both nodes with 'foo' in their body or/and title will be matched.

One solution is to use "Global: Combine fields filter" and combine title and body, but Views then uses a CONCAT function in where clausule, something bad for performance.

I've a solution, but there're drawbacks and I'm not sure if it's optimal.

Using Vies or/and funcionality I set (using more fields not related to this question):

filed1 AND
 field2 AND
 ...
 fieldN
AND
 title OR
 body

title is not expsed, but body is.

My solution is to implement hook_views_pre_build(&$view).

if ($view->name == 'my-view') {
  // Look for the search string, is it present?
  if (!empty($_GET['search'])) {
    $view->filter['title']->value = check_plain($_GET['search']);
  }
}

I've renamed body key in GET to be search.

This way search is performed as I want. The drawback is I can't position search element anywhere becasue it must be in its own group, but I can live with it.


Changing size of user avatar in template file In node.tpl I currently display a users avatar' using this code

theme('user_picture', $account)

My avatars are currently set to 85x85px but when they are displayed in nodes I want them to be smaller. How can I change the size for just this inclusion of user avatars?

This is definitely the command you want to run

theme('imagecache', 'your_custom_preset', $picture, $alt, $alt);

You will have to install imagecache module for Drupal 6.  Its in core for Drupal 7.   You have to define 'your_custom_preset', in the imagecache profiles.

The other place you can theme the avatar is inside the function
[YOUR_THEME_NAME]_preprocess_user_picture(&$variables)  and again use the same line as above. for more information checkout the api.drupal.org documention on this issue


how theme/template connected/related to each other for example, I have:

module id: module_id (file: module_id.info.yml)
FieldType ID: FieldTypeID (file: /src/plugin/Field/FieldType/FieldType.php)
FieldWidget: FieldDefaultWidget (file: /src/plugin/Field/FieldWidget/FieldDefaultWidget.php)
FieldFormatter: FieldDefaultFormatter (file: /src/plugin/Field/FieldWidget/FieldDefaultFormatter.php)

and inside my field formatter:

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#theme' => 'my_field',
        '#type' => 'markup',
        // etc...
      ];
    }

    return $elements;
  }

I have file: my_field.module

with function:

function my_field_theme() {
  return array(
    'location_field' => array(
      'variables' => array(
        'x' => NULL,
        'y' => NULL,
        'z' => NULL,
      ),
      'template' => 'my_field',
    ),
  );
}

and I have template file: /templates/my_field.html.twig

as simple as:

name

content

with that, seems like i can't see my template, which i don't have any idea why?

how is theme or template name relate with the filename (or ID or anything)? - how are they connected each other?

what is the rule for that?

Thank you,

AnD

If your code is only in one module with the name module_id, then in
5. the file should be named module_id.module and the function module_id_theme()


Render menu item children without being 'expanded'? In Drupal 8, how can I render a menu links children without checking 'expanded' on the menu link? I am building a drop down that displays on hover, the links need to render.

My code so far:

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <ul>
    {% for item in items %}
      {% if menu_level == 0 %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}
      {% endif %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

When a parent link has children, they are not rendering unless 'expanded' is checked, which breaks the menu.

I was able to do this by adding a macro for children below the main one in my template.

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}

          {% if item.url.options.attributes['data-icon'] is defined and item.url.options.attributes['data-icon'] is not empty %}
            <svg class="icon"><use xlink:href="/themes/custom/pncb/build/img/svg-sprite.svg#{{ item.url.options.attributes['data-icon'] }}"></use></svg>
          {% endif %}

          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}

      {% endfor %}

  {% endif %}
{% endmacro %}

{% macro submenu_links(items, attributes, menu_level) %}
  {% import _self as menus %}

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

            {{ link(item.title, item.url) }}

        {% endfor %}

    {% endfor %}

{% endmacro %}

I split this out due to scoping, different markup for sub menu, and I needed to use the batch filter. Works great.


How to create a search box bloc with search API I'm using Drupal 8 and i've installed search API and Search API Solr Search.

I followed this great tutorial

How can I display a search box on all of the pages of my website ?

Although you can expose the views form as a block and you can add it twice to a page, the issue is that you may just want a keyword search form in the header but on the actual form you want something more. An additional peculiarity was that the infinite scrolling plugin makes the form ajax, and when exposed as a block it fails to submit.

My solution was to create a new form + block and place the block it where I needed it:

my_search.module:

<?php
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
 */
function my_search_form_header_search_alter(&$form, FormStateInterface $form_state) {
  // NB so that these are not added to the get query params
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}

HeaderSearch.php:

<?php

namespace Drupal\my_search\Form;

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

/**
 * Class HeaderSearch.
 *
 * @package Drupal\my_search\Form
 */
class HeaderSearch extends FormBase {

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

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

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['k'] = [
      '#type' => 'search',
      '#title' => $this->t('Keyword'),
      '#maxlength' => 64,
      '#size' => 15,
      '#title_display' => 'invisible',
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      // Prevent op from showing up in the query string.
      '#name' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Form is redirected no need for anything here.
  }
}

MySearchBlock.php:

<?php

namespace Drupal\my_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'MySearchBlock' block.
 */
class MySearchBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\my_search\Form\HeaderSearch');
  }

}


Permissions problem with OG group pages I can't see why it's the case, but one of my site editors cannot edit the content on OG group pages.

Our groups are private, but that users is a member of all the groups in the site and the "site editor" role should allow him to edit any content anywhere on the site.

There are two kinds of groups, which each have their own content type (because they are subtly different), but the role's permissions settings are identical and the "site editor" role has all boxes ticked in the role based access control settings for both the content types. For both the content types, the "site editor" role also has the create, edit (own/any) and delete (own/any) permissions.

The main problem seems to be that the edit menu isn't appearing for that user.

I'm evidently overlooking something somewhere, but I can't just see where. Surely the role doesn't also need "administer Organic groups permissions" granted.

Is anyone able to point me to the obvious mistake I'm making?

Take a look at Configuration -> Organic Groups Global Permissions (drupal/admin/config/group/permissions). There you will find really fine grained controls over who can view and edit nodes and fields on your group pages.


How to stop CKEditor 3.6.3.7474 from stripping  tags With Full HTML enabled and related filters off, CKEditor will strip any <script> tags from content it is editing.  The editors who create content for this particular site need to be able to embed things like this in the content they are creating:

    <img src="http://s2.thingpic.com/images/TD/zKWJQJiFBsp3oP1etNC1.png" width="560" class="alwaysThinglink"/>
<script charset="utf-8" src="//www.thinglink.com/jse/embed.js#286861458501795840"></script>

In theory we can make this work by disabling CKEditor and working directly with HTML, but in practice it doesn't work: the editors are not HTML-savvy.  They know enough to temporarily drop out of rich-text mode, paste in the above, and then switch back to rich-text mode.  But if they go to edit that content again, CKEditor strips the <script> tags when opening the content.

How can I stop that behavior and have CKEditor leave the <script> tags in place?  Is there a hidden setting somewhere for that?

BTW, we are using CKEditor in conjunction with Wysiwyg 7.x-2.1 module.

And yes, in general allowing <script> is very bad, but in this case the only people who have access to the Full HTML format are the editors (who are trusted).

Thanks!

You can resolve this by going to the "Advanced Options" section of your CKEditor profile and adding the following string into the text area:
config.allowedContent = true;

This resolved the issue for me.


How to display vocabulary? I want to display all the vocabulary that i've created in the /fr/admin/structure/taxonomy page and each vocabulary linked to the list of terms it containes.

How can display them in a page ?

I've done this by creating a view only. Please find the attached screenshots.


How to show, in a view, content depending on user language or default? In one of my Views, showing a preview of some nodes, how can I set the nodes to be shown to be the ones in the user language or, if the user has no language set or is anonymous or the language is not set for the node, the ones in the site default languages?

I can do the two thing with 'filter criteria' separately but not together...

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Notes:

The above may turn out to NOT be the complete answer. You may use the Entity Translation module and, in that case, there is not this option if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.
The Internationalizations Views module only has a DEV version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +31K users can't be wrong, right?


How to select a view inside a custom module form I would like to have "select" with some views so I can chosse one of them and the submit the selection to display the result. something like this:

And this is close to what I want :

  $form['title'] = array(
'#type' => 'select',
'#title' => t('Display amount'),
//'#required' => TRUE,
'#options' => drupal_map_assoc(array('1','2', '3', '4', '5', '6', '7', '8')),
'#default_value' => 5,
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
   ),
    );

 $form['content'] = array(
'#type' => 'select',
'#title' => t('Content'),
'#options' => array(node_type_get_names()),
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
),
);

$form['views'] = array(
'#type' => 'select',
'#title' => t('views'),
'#options' => array(),
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
 ),
);

Thanks

As Views is a CTools Export UI based module, the correct way to load all views is by using the CTools Export function: ctool_export_crud_load_all()

Example

ctools_include('export');
$views = ctools_export_crud_load_all('views_view');
$options = array();
foreach ($views as $view_id => $view) {
  $options[$view_id] = $view->human_name;
}


Theming views page and pagination I am new to drupal and views. I have successfully created views page and understood some basics of it and views theming. I have created a views page for content type(products) listing. Now on the views page i have successfully listed the products. and now i want to theme it and also would like to know how to do pagination for it?

You have to be a bit more concrete when you ask for how to theme a view. One thing to note is that views help you with template suggestions (names for templates) which is one of the most common and easiest ways to alter the output of Views.

Pagination can be setup from within the interfacer. There is a pager link you can click on to set that up, if you look around a bit I'm sure you'll find it. The location depends on the Views version you use.


Display newly added form element at the bottom I altered a form, and I added a $form['priorities'] form element.

Why is it appearing right after the title form element, and not at the bottom of the form? How can I make it at the bottom?

Like KrishaWeb said you need to add a #weight attribute to your new element.

It would look like:

$form['priorities'] = array(
  ...
  '#weight' => 99,
  ...
);

You can also set weights on the other form elements so the form is explicitly in order.


Form rebuild without using buttons I'm trying to figure out how to rebuild a form without using a button click trigger. Instead, I'm looking to rebuild whenever a blur event occurs on a textfield. All non-button form types lack the #submit value. It doesn't seem possible to trigger a form rebuild with $form_state['rebuild'] = TRUE; unless the submit callback is triggered. Demo code below.

function test_form($form, &$form_state) {
  $form['form_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (isset($form_state['textfield_vale'])) {
    $textfield_vale = $form_state['textfield_vale'];
  }
  else {
    $textfield_vale = 'not set';
  }

  //will not trigger page rebuild
  $form['form_wrapper']['test_textfield'] = array(
    '#type' => 'textfield',
    '#value' => 'Value = '.$textfield_vale,
    '#ajax' => array(
      'callback' => 'test_result',
      'wrapper' => 'form_wrapper',
      'event' => 'blur',
     ),
  );

  //will trigger page rebuild, changing the textfield value
  $form['form_wrapper']['trigger_rebuild'] = array(
    '#type' => 'submit',
    '#value' => 'I don\'t want to press it',
    '#submit' => array('submit_rebuild'), //has #submit value unique to buttons
    '#ajax' => array(
      'callback' => 'test_result_with_button',
      'wrapper' => 'form_wrapper',
    ),
  );

  return $form;
}

function test_result($form, &$form_state) { //unable to set $form_state['rebuild'] = TRUE
  $form_state['textfield_vale'] = 'textfield trigger'; //TRUE;
  $form_state['rebuild'] = TRUE;
  return $form['form_wrapper'];
}

function submit_rebuild($form, &$form_state) {
  $form_state['textfield_vale'] = 'button trigger'; //TRUE;
  $form_state['rebuild'] = TRUE;
}

function test_result_with_button($form, $form_state) {
  return $form['form_wrapper'];
}

Is there a way to trigger a form rebuild without clicking a button (perhaps with an ajax command)? Alternatively, how can I change my code to allow an ajax callback to change $form_state values?

I've always handled changing form values in the form build or form_alter function itself. I can't remember where I saw to do this, but I've never been able to alter the form in the ajax callback itself.

Have your form trigger an ajax callback. This should return the form or piece of the form in question, like your test_result_with_button() function.

When an ajax callback is triggered, the build method and alters are run again. Add logic in your build / form_alter to make updates to the form or form_state based on whichever action was triggered. Information about how the rebuild was triggered will be available in $form_state['triggering_element'].


Shopping cart contents section is empty for anonymous users there is a problem in my eshop (build with latest D7 and commerce 1.14)  in checkout page where the "Shopping cart contents" section is empty for anonymous users.

I checked the permission "View any type of products" for anonymous users but didn't fix the problem

Any ideas?

Thanks

This is almost always due to some sort of relationship in the View's configuration linking from the cart order's line items to some other entity the user doesn't have direct access to view. Rather than try to find the right permissions, the easiest thing to do assuming you have other filters (or contextual filters) on the View to ensure the customer doesn't see other data is to disable SQL rewriting under the advanced settings for the View.

On a hunch, though, you should also make sure anonymous users have access to view their own orders. We have special code in the cart module to ensure access control works in that situation, and it could be the entire order is inaccessible and not just some related entity.


Manual per-instance cropping I have tested tried out a couple of image-cropping modules listed here. None of them seemed to meet my expectation, but chances are I was doing something wrong. That's why I'm looking for your experience.

What I want is to enable the admin-to-be to manually select the area and crop uploaded images to a square based. I don't want to rely on automatic scale-and-crop effect provided by Drupal as it may trim the image inappropriately. So, I'd expect the module to offer a per-instance cropping.

Has anyone encountered that kind of capabilities?

The Manual Crop module does the best job.

To quote the project page:

  The Manual Crop module exposes a set of image style effects that
  enables users, if enabled in the widget settings, to crop (and scale)
  an image after uploading.

Essentially this means you can choose a different crop area for each image style used.


How do I create additional fields in module.install? I am creating a module in the ".install" file, using the following code:

// if not exists, create new content type
if (!node_get_types('type', 'houses')) {
  $info = array(
    'type' => 'houses',
    'name' => t('Houses'),
    'module' => 'node',
    'description' => t('Manager Houses'),
    'locked' => FALSE,
    'custom' => TRUE,
  );
  $info = _node_type_set_defaults($info);
  node_type_save((object)$info);
}

It creates a new content type, but how do I create additional fields (e.g. text, nodereference)?

Instead of creating the node type and fields by hand in code, you should use the features module which does the same thing, but has support for a bunch of other things as well, like reverting changes made to what is saved in code.


How to create sub-directory based multi-site? I want to create subdirectory based multisite, for this I roamed full day in internet but nowhere I found how can do the symlink in a proper manner. I will divide my requirement below:

Site name I have is: capacad(accesible by url: localhost:81/capacad/)

I want multisite url should be: localhost:81/capacad/subsite

So to achieve this I created a folder named subsite in C:\xampp\htdocs\capacad\sites\subsite.

Later this step I have to do symlink. So how can I achieve that.

I tried this command: C:\>mklink /d C:\xampp\htdocs\capacad\sites\subsite C:\xampp\htdocs\capacad

This is creating multiple loops inside the subsite folder.

I am not getting the what path names where to link. Can anybody please explain me elaborately how can I achieve this in windows.

Thanks for any suggestions.

I followed some below links:

link1

link2

link3

You can modify the site names in the file sites/site.php

$sites = array(
  'site1.your-multisite.local' => 'website1',
  'your-multisite.local.site2' => 'website2',
);

Also update the settings.php file of each subdomain with the credentials of respective sites.

Also need to update the site url from the host settings.

 ServerAlias    *.your-multisite.local your-multisite.local.*


Prevent trigger of other hook_preprocess_HOOK() Is there a way to prevent other preprocess hooks from being triggered?

I have a Drupal 8 hook_preprocess_HOOK() implementation, and I'm doing some alterations. There will be other modules with same hook, and I need the other preprocess hooks not to alter my changes to $variables.

The only options I have are:

Rely on weights system, which still could cause problems
Set a value inside $variables and prevent other modules from doing their thing if the variable is set

You can disable hooks via hook_module_implements_alter().

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_page') {
    unset($implementations['module_foo']);
    unset($implementations['module_bar']);
  }
}


Install Drupal with MS SQL Server 2008 R2 Is it possible in any ways to connect Drupal 6.x to MS SQL Server 2008 R2 on Windows Server 2008? I am really struggling to find a way out.

please let me know. Any help would be greatly appreciated!

The requirements clearly states that the supported databases in Drupal 6 are "MySQL 4.1 or higher, PostgreSQL 7.1."

You would have to write the database support yourself to get this working.

Drupal 7 does support MS SQL Server however.


How do I hide the core version to the outside world? I was bothered in knowing with whatcms.org a version can be given for drupal 8, even a minor version - no minor version, instead, when I tried with a drupal 7.
Curiously enough in my case, I got a version slightly newer (just one minor version ahead), but I'm concerned anyway, should I not?
I'm thinking of every situation where a security update cannot be performed right away.
I don't even know how can the version be guessed from outside.
I issued a tail -f on the access log while pressing the Detect CMS button on whatcms.org, but, mysteriously, I got no log entry from there. Perhaps they cache the previous results on the same site not to perform a fetch each time the button is pressed with the same domain string input?

If you want to hide the Drupal version then you can use the following module:
https://www.drupal.org/project/remove_http_headers


Migrating files with descriptions I'm currently migrating PDF files into a content type. I would like to know how to populate the file information description field with a more meaningful link (e.g. give a description to each imported file).

$arguments = MigrateFileFieldHandler::arguments(drupal_get_path('module', 'my_migrate').'/docs', 'file_copy', FILE_EXISTS_RENAME);

$this->addFieldMapping('field_publication_download', 'files')
  ->arguments($arguments);

Here is a link that shows all the arguments you can pass to MigrateFileFieldHandler. As you can see description is the 7th argument.

If you don't want to specify any of the arguments before description, you still have to pass NULL to them e.g.:

$arguments = MigrateFileFieldHandler::arguments(
  drupal_get_path('module', 'my_migrate').'/docs',
  'file_copy',
  FILE_EXISTS_RENAME,
  NULL,
  NULL,
  NULL,
  array('source_field' => 'migrate_source_description_field'), //Can also pass a string here
);


how to add username and password field in commerce order I am new with Drupal and I am willing to learn more.

now, I am creating a project and I am using the drupal commerce.

In the check-out process, In default, for unregistered users, it has the email field and others field. I just want to add username, password and password confirm fields so that the anonymous user will register then he can pay for the item he cheked-out.

but the problem is I don't know how to add those fields.

I have also checked the Checkout Rules (Create a new account for an anonymous order), I think the process of creating the user is done here, but I don't know how.

Does anyone can help me in my case?
any help will be appreciated...

thanks in advance ...

This is currently being handled via the Rules module. The rule that is enabled by default creates the user via the "Create a new account for an anonymous order" rule. There is no way to insert a password in here but is up to the user to open the link in their email and set their password manually.


Share a value between two different hooks I have 2 hook functions in my module: hook_views_pre_render() and hook_form_alter(); in hook_views_pre_render(), I retrieve some data about what nodes that are available that I need in hook_form_alter().

I'm looking for a way to pass the data from hook_views_pre_render() to hook_form_alter(). It seems simple, but I can't get it to work. Does anyone any idea?

What works for the moment is to add global $aVariable to both the hook functions, but I believe there should be a better way.

In Drupal 7, drupal_static() could be used too, if the stored value doesn't need to be persistent between different pages.

drupal_static() is normally called as drupal_static(__FUNCTION__, $default_value), but if you use the name of the function, you can access the same value accessed from the function that calls drupal_static().

Using variable_set() and variable_get() the value is persistent between different pages, and it is not automatically removed. If the first hook execute code similar to the following one, then the second module would get an older value.

if ($condition) {
  variable_set($variable_name, $value);
}

Rather than using such code, the first hook should execute code similar to the following one.

if ($condition) {
  variable_set($variable_name, $value);
}
else {
  variable_del($variable_name);
}

Whatever method you choose, be sure the hook reading the value is effectively running after the hook setting that value.


Pass additional variable into existing twig template (Book module) I use the Drupal 8 Book module for books where each chapter has a different author.

The Book Navigation block uses book-tree.html.twig (core/modules/book/templates) to generate a book tree showing chapter titles. I want to show author names also.

I can subclass and edit book-tree.html.twig, but I don't know how to get the author name passed in so I can use it. How do I go about this? Only the title, the url, and some flags are passed in now.

As an alternative, I can get the id for each chapter node from its url as a string. Can I use this id to load the chapter node from within the twig template? If so, I can get the author name from the node directly.

Drupal offers preprocess functions where additional variables for templates can be set up.

The naming convention is THEMENAME_preprocess_THEMEHOOK(). In your case, you want to add a variable for book-tree.html.twig. The machine name for this is the first part of the template, with underscores replacing hyphens. In this case it would be book_tree. So your function would be THEMENAME_preprocess_book_tree().

Preprocessors receive a single argument, an array. The keys of this array become the variables available in your twig template.

THEMENAME_preprocess_book_tree(&$vars) {
  $vars['book_author'] = some_function_that_gets_the_author();
}

Now the variable book_author will be available to your template.


MYSQL date in views not working I am connecting views to an external database and everything works fine if my views handler is a string but not as a date, here is my view definition:

$data['Punches']['Punch_Date'] = array(
   'title' => t('Punch Date'),
    'help' => t('Employees Punch Date'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_date',
    ),
  );

If I change views_handler_field_date to views_handler_field I can see the records in my view. The date coming from mysql looks like

2013-08-27

I would also like to format that date to look like

08-27-2013

The biggest problem is that I want to be able to filter between dates, thanks for any help that can be given.

To set the date format used when dates are displayed on your site, navigate to Home » Administration » Configuration » Regional and language, and set date format.


Calling function from other module does not work with module_load_include I'm building a custom module that uses functions from other modules. Specifically the node_clone module. I'm building a custom module to clone a certain content type from a selected user to another selected user.

In my custom module I'm adding those lines:

module_load_include('inc', 'node_clone', 'clone.pages');
clone_node_save($nid);

The function clone_node_save is defined in the module "node_clone", in the root folder of that module,

function clone_node_save($nid, $account = NULL) {
//Function Content
}

inside a file called clone.pages.inc

yet those 2 lines of code give me the error Fatal error: Call to undefined function clone_node_save()

I also tried making a function inside node_clone.module that calls clone_node_save but that gets the same error.

This is drupal 7

You don't include the file extension in the third argument.

So this:

module_load_include('inc', 'node_clone', 'clone.pages.inc');

Should be this:

module_load_include('inc', 'node_clone', 'clone.pages');


How do I clean up image uploading by removing the additional upload fields? I am running a Drupal 6 site, and I have a content type in which the user can upload a maximum of 6 images. The problem I am having is that I don't like the fact that Drupal displays all 6 file upload slots. I would prefer that it would just display one upload slot and then display the add additional image button like it does when it is configured to upload unlimited images.

Is it possible to configure Drupal to do this? I have searched high and low, and I can't find anything.

Can anyone point me to a module or to some code to accomplish this?

You can do this. Although it may not be what you exactly want. I'm not going to write all the code for you, but can push you in the right direction:

Make the field accept unlimited values. That will add your "Add another" button, and will only show 1 image upload field initially.
Make a small module which implements hook_form_alter and modify the node_form of the content type which has the image. You need to add an extra validation function.
Write the validation function to check the number of values supplied in the image field. And set form error if more than 6 images uploaded.


Number of users registered daily in table format using views I need a views in table format which show number of daily registered users.

Here are the steps to create a 'view' to display users details in table format.

1) Add new view and select  Users from Show option

2) Select Format as Table and Add user fields whatever you want to display at output.

Note: If you want to display all users (including blocked) just remove User: Active(yes) from Filter Criteria.


How to pass variables to a theme template file from EntityAPIController::buildContent() I may be going about this incorrectly, if so please point me in the right direction.

I currently have a custom entity type and I'm adding the display fields via a controller class that extends EntityAPIController. I want to attach some content from elsewhere (non-entities) to the display of this custom entity.

I have an implementation of hook_theme:

function module_theme($existing, $type, $theme, $path) {
  return [
    'module_plugin_instance' => [
    'template' => 'module-plugin-instance',
    'path' => $path . '/templates',
      'variables' => [
        'instance_id' => NULL,
      ],
    ],
  ];
}

Then, in EntityTypeController::buildContent() I have:

$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance'
];

Where I'm failing is I can't figure out how to pass variables to the theme template here.  The dummy html I'm putting in the template renders fine, just no variables.  I've tried several different things, but I can't seem to get $instance_id to my template - what am I doing wrong?

You can provide theme variables through properties, e.g.:

$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance',
  '#instance_id' => 'foo',
];


add_relationship and views_join In hook_views_query_alter(), I am trying to add a join to the user role of the author of the node and filter basing on the role.

        $query->add_relationship('user_role_join', new views_join('users_roles', 'uid', 'users', 'uid','INNER'), 'node');
        $query->add_where(1,'user_role_join.rid','4' ,'=');

It is something like this, but I am missing something. When I run this query the result is always empty. If I create the condition using Views UI, I do get the correct and expected result. So the data is okay, but my code is the problem.

How do I setup this join correctly in hook_views_query_alter()?

Also the following code doesn't work.

$join = new views_join();
$join->table = 'node';
$join->field = 'uid';
$join->left_table = 'users_roles';
$join->left_field = 'uid';
$join->type = 'INNER';
$join->extra = array(
            array(
                'field' => 'bundle',
                'value' => 'node',
            )
        );
$query->add_relationship('user_node_role', $join, 'node');

$query->add_where(1,'user_node_role.rid','4' ,'=');

I found the solution

        $join = new views_join();
        $join->table = 'users_roles';
        $join->field = 'uid';
        $join->left_table = 'node';
        $join->left_field = 'uid';
        $join->type = 'left';

        $query->add_relationship('users_roles', $join, 'node');
        $query->add_where(1,'users_roles.rid','4' ,'=');

This works


Slideshow module in D7 Is there any slideshow module in D7 similar to this one - http://www.cnngo.com/shanghai/life/facekini-woman-chinas-latest-beach-sensation-680659

In D6 the Views Slideshow can do this but not sure in D7. Any ideas?

The views slide show in Drupal 7 in my opinion is even better than in 6 as it start right of the bat with the jQuery Cycle library and that alone will give you a lot of nice effects plus all the extra tools like pagers, counters and controls.

Check the last tutorials on the modules pages page to learn more about the installation and configuration including the thumbnail pagers.


What is the correct way to translate variable_get string values entered in admin input fields? I'm developing a simple module with and admin page, where admin can fill some textfields with custom strings that will generates a piece of html to be used later.

So for example I have fields like this in admin page:

function MYMODULE_admin_page_arguments() {
  $form = array();

  $form['MYMODULE_link'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link path'),
    '#default_value' => variable_get('MYMODULE_link', 'conditions'),
  );
  $form['MYMODULE_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link text'),
    '#default_value' => variable_get('MYMODULE_link_text', 'conditions'),
  );
  $form['MYMODULE_link_target'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link target'),
    '#default_value' => variable_get('MYMODULE_link_target', '_blank'),
  );
  $form['MYMODULE_prefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link prefix text'),
    '#default_value' => variable_get('MYMODULE_prefix', 'I agree to the '),
  );
  $form['MYMODULE_suffix'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link suffix text'),
    '#default_value' => variable_get('MYMODULE_suffix', '.'),
  );

  return system_settings_form($form);
}

Then the above values are managed after by my module to compose an output like:

// Create label
$prefix = variable_get('MYMODULE_prefix', 'I agree to the ');
$suffix = variable_get('MYMODULE_suffix', '.');
$path = variable_get('MYMODULE_link', 'conditions');
$text = variable_get('MYMODULE_link_text', 'conditions');
$target = variable_get('MYMODULE_link_target', '_blank');

$label = $prefix . l($text, $path, array('attributes' => array('target' => $target))) . $suffix;

Now I need that all these values are available for string translation, so the first think I thought was to pass all of them through t(), for example:

$label = t($prefix) . l(t($text), $path, array('attributes' => array('target' => $target))) . t($suffix);

but I read here https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7 that I should never pass variables directly to t(), so for e.g t($prefix) is a bad stuff.

So, what is the correct Drupal way to accomplish this?

You should use the Variable translation module, part of Internationalization.

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Then, you'll be able to select language for which you are configuring your variable:

Advice taken from this community documentation.


Storing third party passwords What is the standard or recommended way to store third party passwords in Drupal? Specifically, I want to use oAuth to authenticate a user to Google, and do not want to ask users to type in their passwords each time they access their accounts.

You don't store 3rd party passwords - nor should you get them.

The whole idea behind oAuth is that you will never get the email and password of the user that signed in with google. What you get instead is a token that is valid for a specific period of time for that user. It depends on the provider how long the token is valid, but it could be indefinitely. The smart thing about oAuth is that if you user has an active session on the site you are accessing and have granted your site access, he wont need to do anything. The browser will use his cookie for access and the site will allow you to do what you need since the user already has granted you the access.

So what you need to do is to store the token, typically something that looks like a md5 hash, the username and the site. This can be stored in the database, I would use a custom table unless you have a module that handles this for you.


Node Langauge needs to be undefinde by default my website (Drupal 7) is available in German (?q=de) and English (?q=en) (i18n Module). Users can create own pins (nodes) (similar to pinterest). The default language of the website is set to german. So everytime somebody creates a new pin (node) the language of the pin is set to german.

The problem is, if somebody is using the english (?q=en) version and clicks on a pin he gets redirected to the german version (?q=de).

I can manually set the language of each pin to undefined. Then everybody stays on the right version, but this would be to much work to do, to change the language of each pin all the time.

I can't let the users chose the Language, because every pin needs to be set to undefinded.

How can I achive, that with every new pin the language is set to undefined automatically?

In the "Structure" > "Content types" editing page (/admin/structure/types/manage/article — replace article to your pin content-type), you can switch on (=tick) Set current language as default for new content in the Extended language options sub-section in the Multilingual settings tab (near the bottom-left).  Then when a user visiting your website is in the English mode and creates a new node (pin?), the language of the node will be English.

It is not Language neutral, but that may be what you can accept?


Notice: Undefined index: und in include() I'm having an issue with an undefined index I really could use some help with.

This is the error I get:

Notice: Undefined index: und in include() (line 15)

This is what my line 15 looks like:

  <a href="
      <?php print $node->field_house_coupon_link['und'][0]['url']; ?>
    " style="color:#
      <?php print $node->field_house_coupon_link_hex_code['und'][0]['safe_value']; ?>
    ">
      <?php print $node->field_house_coupon_link['und'][0]['title']; ?>

I know the error is happening because sometime the field is not given a value and allowed to be blank. I'm using Drupal 7.23 and I've tried using the isset method mentioned elsewhere on this site but it's not working and I'm out of ideas

Thanks!

Before assigning the values to the field directly you must check if it contains any value or not otherwise you will get the notice like above, try to check the value something like below (the below code is for reference only, you can modify it as per your requirement):

<a href="<?php
print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link[LANGUAGE_NONE][0]['url'] : ""; ?>"
style="color:#<?php print isset($node->field_house_coupon_link_hex_code[LANGUAGE_NONE]) ? $node->field_house_coupon_link_hex_code['und'][0]['safe_value'] : ""; ?>">
<?php print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link['und'][0]['title'] : ""; ?>

Also it is recommended to use LANGUAGE_NONE instead of und: The language code used when no language is explicitly assigned. Defined by ISO639-2 for "Undetermined".


Is there a way to pop form errors off the display stack and/or prevent their display? I have a Drupal 7 form which I'm allowing the user to submit via AJAX. If the user does not fill out required fields, or enters invalid information, I can return that and alert the user via the form_get_errors() function. The problem is that these values are still on the "display stack" (not the correct term, I'm sure) - when the user refreshes the page, or navigates to another one, these previous errors are displayed.

Is there a way to set these errors not to display once I've grabbed them with form_get_errors()?

EDIT: The session variable 'messages' is set at $_SESSION['messages']['error'], which is where the display of the errors is driven from. I could wipe this out by doing something like unset($_SESSION['messages']['error']), but I feel like this is very hacky. The drupal_static_reset() function also will not help, since it doesn't eliminate the values in the messages array.

If you know the message was the last one set, a  simple hack is to just:

array_pop($_SESSION['messages']['error']);

Just be aware this only removes the message, your form will still be in error state.


What is the CCK module? Is it a core module in drupal 7 or do I have to install it? When I go to download the CCK module I see that it is available for Drupal in the recommended release. I want to know why it is not available for Drupal 7 or whether I can use the development release.

Most of the CCK code is part of Drupal 7. Actually, the code in Drupal 7 is quite different from the code used from the CCK module in Drupal 6. That is the reason why there is a Drupal 7 version of CCK; the other reason is that not all the code that is part of the CCK module was ported to Drupal 7 core.
In short, you need CCK for Drupal 7 to upgrade a Drupal 6 site using CCK to Drupal 7.

As for using the Drupal 7 development snapshot, the usage statistics say there are 36007 sites using CCK for Drupal 7 out of 222100 sites using CCK, while 3081 sites are using the Drupal 5 version.


Passing an array stdClass Object from custom module to template I’ve created some D8 custom modules which call rest API and and it’s working fine when I get simple array in my $response.

In my controller, this is working :

return [
            '#theme' => 'webservices_client',
            '#id' => $infos_clients->body->id,
            '#nom' => $infos_clients->body->nom,
 ];

But when I receive that kind of array $response->body :

Array
(
    [0] => stdClass Object
        (
            [numero] => 625
            [dateDebut] => 2018-09-27T09:21:54.5746973
        )

    [1] => stdClass Object
        (
            [numero] => 468
            [dateDebut] => 2018-05-17T16:50:33.6357383
        )

)

I don’t how to send my array from the controller to the twig template and assign variable in my-module.module

Could you explain how to this ?

I've tried this kind of thing :

in controller :

return [
            '#theme' => 'webservices_informations',
            '#myvariable' => $response,
       ];

in my-module.module :

function webservices_informations_theme(array $existing, $type, $theme, $path) {
    return array(
        'webservices_informations' => array(
            'variables' => array(
                'myvariable' => NULL,
            ),
        ),
    );
}

In twig template :

{% for key, value in myvariable %}
            Key : {{ key }}

            Name : {{ value.id }}

{% endfor %

I don't know why it was not working because after I've done a simple

    {{ dump(myvariable) }}

In order to check if the array was passed to the twig template, everything is working.

So the solution is in my-template.html.twig

{% for key, value in myvariable %}
    Key : {{ key }}

    Date: {{ value.dateDebut }}

    Societe : {{ value.societe }}

{% endfor %}


Add an image to a line item in drupal commerce my client ask a site to sell printed canvas so I need to allow site users to add at least one image to every drupal commerce line item.

There is easier to start from a drupal kickstarter installation or a clean installation od drupal + commerce module?
There is some module to achieve this with drupal commerce?

Thank you

It's easier to start with kickstart, but there are alot of things in there you might not need and confuse you in the process of setting up your store.

I would suggest just going as minimal as possible and add in what you need for the site as needed. I'd say just go with the core Commerce module and work your way up and add in the things as you need it to reduce all the bloat. Then you will have nice clean installation and also know where everything is as you will be done building it up from the ground up.

I was attempting to go the kickstarter route in the beginning just as you would because I saw that it was easier, but its really not i feel as there are certain modules you just dont need.


Don't know how to add title_suffix I am working on existing Drupal project. I am begineer at Drupal and I need a help with something. In one node I've got title with title_suffix. This node is a view. I want to edit this title_suffix, but I don't know how and where to look at it. Could anyone help me please? Where do I have to looking for? UI or template files or where? Thanks.

Use a preprocess function to populate $title_suffix. It belongs in a file called template.php in your theme folder.

Here's a primer: Setting up variables for use in a template.

A basic example that populates the variable $foo and makes it available to page.tpl.php (Drupal 7.x):

<?php
function THEMENAME_preprocess_page(&$variables) {
  $variables['foo'] = 'bar';
}
?>

The core module Contextual links populates $title_suffix in its implementation of hook_preprocess(). View source at modules/contextual/contextual.module for an example of how it is done.


Drupal 8 function from controller returns html markups only I have been creating a table from mysql result , but its printing the html markup only and says controller must return a response . what may be the reason ?

  LogicException: The controller must return a response ((5
  rows)group_nameparent_nameEditDeleteSelect
  itemsL2V9http://192.168.1.236/mailusers/usergroup/edit/6>edithttp://192.168.1.236/mailusers/usergroup/delete/6>delete

    L3v3http://192.168.1.236/mailusers/usergroup/edit/7>edithttp://192.168.1.236/mailusers/usergroup/delete/7>deleteAdminsV6http://192.168.1.236/mailusers/usergroup/edit/8>edithttp://192.168.1.236/mailusers/usergroup/delete/8>deleteL4Vodafonehttp://192.168.1.236/mailusers/usergroup/edit/9>edithttp://192.168.1.236/mailusers/usergroup/delete/9>deleteVCNONetworkhttp://192.168.1.236/mailusers/usergroup/edit/12>edithttp://192.168.1.236/mailusers/usergroup/delete/12>delete given). in
    Symfony\Component\HttpKernel\HttpKernel->handleRaw() (line 157 of
    vendor/symfony/http-kernel/HttpKernel.php).

The error message is not pointing in the right direction. It should say:

"The controller must return a render array"

For example the most basic one:

return array(
  '#markup' => '
This is html markup
',
);

The error message is from symfony, and from the stand point of symfony this is correct. A controller must provide a response, but drupal has extended the response handling to look for render arrays, that are then used the generate a response with the rendered html. If you don't provide a render array, then there is no response and then this error message will come up.


How to make a content visible only in the corresponding language it has been created on a multilingual website I am buiding a website on drupal 7 in french and english.

I made french the default language because most users are french speaking at first. So English became the second language.

I am using Entity Translation.

In that website, people who have an account can create content. But I want the content not to be translatable apart from menus and some other stuff.

What I want is the content that is writen in french (in the french version) to be displayed only in the french version. And the content that is written in english (in the english version) to be displayed only in English.

I've tried that for days. But all the content is still showing in both languages.

Can you help me please ?

Entity Translations can be configured so that when it doesn't find content for a field in a language, it uses the content of the default language if any is available. If you're in an English page and a field is missing content, it may pick up the French content.

This can be disabled in /admin/config/regional/entity_translation by unchecking the "Enable language fallback" checkbox. When disabled, fields that have no content will simply not appear and won't fall back to the default language's content.


Views Search Terms not working correctly for taxonomy terms with multiple words I'm having a bit of an odd issue. I have a Search Terms filter set up on a view and it's not working quite correctly for taxonomy terms in the view.  For example, if one of the Terms is 'International Harvester' and it returns the correct results if I enter International or Harvester or "International Harvester", but if I put in International Harvester without quotes then no results are returned. Any ideas?

using Drupal 7.41, Views 7.x-3.7

This turned out to be a bug with the search score feature discussed here https://www.drupal.org/node/1615438.

This comment details that checking the "Remove search score" checkbox under the Search: Search Terms filter fixes that problem.


How can I create a programmatic Search API query which uses a date field I'm trying to create a programmatic Search API query. I've successfully created one which looks for all nodes which are published:

  $index = search_api_index_load("node_index");
  $myQuery=new SearchApiQuery($index);
  $myQuery->condition('status', '1', '=');
  $data=$myQuery->execute();
  $results=$data['results'];

However the condition that I want to search for is to find all nodes with a certain date on a date field.

The problem is I can't work out how the Search API stores dates. I've tried UNIX time stamps:

  $myQuery->condition('field_application_end_date', '1411084800', '=');

And the PHP date format that is stored on the nodes however neither returns any results.

  $myQuery->condition('field_application_end_date', '2014-10-01T00:00:00', '=');

Can someone explain how the Search API stores dates?

I've been digging through the module to try and work out how it's done, but it's a little out of my league.

Try

$myQuery->condition('field_application_end_date:value', '1411084800', '=');

Search API stores the dates as timestamps, so you're right there, but you forgot the 'value' after the field. If you want to use the 'to' date, use 'value2'.


Install Webform on Drupal 8 : checkboxes greyed out (Pretty much a Drupal newbie here)

I'm having difficulty completing he installation of "Webform version '8.x-5.0-rc3 released 4 February 2018'" on Drupal 8.4.5 on a development box running Windows 10.

My Webforms installation is in my htdocs\modules\custom\contrib\webform folder, and 13 modules are showing up in Drupal admin/modules. But I can’t click on the checkboxes to install any of these modules because they’re grayed out. I’ve been able to intall other modules successfully, both homebuilt and contributed ones.

Any thoughts on how to proceed? Thanks in advance…..

The new webform 8.5 versions requires the "Contribute" module. If you click the little expander next to webform you'll see its a dependency. Have a look on the webform project page for more info
https://www.drupal.org/project/webform

Also just as a tip as I noticed from your question you've got your modules as /custom/contrib/webform its better if you do your module file structure as:

/modules/custom/

/modules/contrib/

with your own build modules in custom and anything from drupal.org in contrib.


using a custom module, how to add a  tag after the theme's css files I use Drupal 6.

Everytime I use drupal_set_html_head, my <style> code is being added before my theme's <link> entries.

Basically, I want to override the theme's css files with internal css, so I need my <style> to appear at the very end of <head>

I hope it is clear. Thanks!

Everything you add with drupal_set_html_head() is added before the CSS styles added with drupal_add_css(). In fact, the page template outputs them using the following code.

<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

$head and $styles are initialized in template_preprocess_page() with the following code.

$variables['head'] = drupal_get_html_head();
$variables['styles'] = drupal_get_css();

As drupal_add_css() is used to add all the CSS styles used by a theme, including the ones defined in its .info file, you can change the order the CSS styles are added by changing the page template. If it would contain the following code, everything added with drupal_set_html_head() will come after everything added with drupal_add_css(). I would not suggest doing this, if not after verifying it doesn't cause any problem.

<head>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $head; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

Notice that with Drupal 7, you can use drupal_add_css() to use inline CSS style too: Just pass the CSS styles as first argument, and pass array('type' => 'inline', 'weight' => 100) as second argument. You need also to use the group property. In that way, you don't need to alter the template file just to add your CSS  styles after the ones added by Drupal.
Generally, it is preferable to add the CSS styles in a file; in that way, they can be aggregated/compressed.


MailChimp Error: API Key cannot be blank I'm trying to install the mailchimp addon but are stuck on getting the error message above.

So far:

I've installed/enabled the module with version 7.x-4.0
Loaded the PHP Library to /sites/all/libraries/mailchimp
Added the API Key to /admin/config/services/mailchimp
Enabled the MailChimp Signup module

The error occurs after enabling the signup module and freezes the whole website with a blank screen even though error messages are being fully displayed. When I uninstall the signup module via drush and check the admin page for the service my API key is still set.

Any pointers what I'm doing wrong?

Mistake: I've not correctly installed the mailchimp php library. Instead of showing this in the status report page the module crashes the website.


Downloading custom module with drush make I am trying to download a custom module from a private repo using drush make.
This is the make file:

core = 7.x
api = 2
projects[cs_all][type] = "module"
projects[cs_all][subdir] = "contrib"
projects[cs_all][download][url] = "git@bitbucket.org:myrepo/cs_all.git"
projects[cs_all][download][branch] = "master"

I run the following command:

drush -d make --no-cache --no-core my.make build

The output is as follows:

Starting Drush preflight. [0.46 sec, 2 MB] [preflight]
Cache HIT cid: 7.0.0-commandfiles-0-4ea41d3d78dd4cb8ebf6ca2ee09bd808 [0.61 sec, 2.05 MB] [debug]
Bootstrap to phase 0. [3.31 sec, 8.02 MB] [bootstrap]
Bootstrap to phase -1. [3.35 sec, 8.03 MB][bootstrap]
Found command: make (commandfile=make) [3.36 sec, 8.03 MB] [bootstrap]
Bootstrap to phase -1. [3.36 sec, 8.03 MB][bootstrap]
Loading release_info engine. [3.38 sec, 8.03 MB][notice]
Calling hook drush_make_validate [3.42 sec, 8.23 MB][debug]
Returned from hook drush_make_validate [3.42 sec, 8.23 MB][debug]
Calling hook drush_make_pre_make [3.42 sec, 8.24 MB][debug]
Returned from hook drush_make_pre_make [3.43 sec, 8.24 MB][debug]
Calling hook drush_make [3.43 sec, 8.25 MB][debug]
Beginning to build my.make. [3.44 sec, 8.27 MB] [ok]
Downloading release history from https://updates.drupal.org/release-history/cs_all/7.x [3.45 sec, 8.35 MB] [notice]
c:/Users/myname/.drush/cache/download/https---updates.drupal.org-release-history-cs_all-7.x retrieved from[notice]
cache. [3.45 sec, 8.35 MB]
No release history was found for the requested project (cs_all). [3.46 sec, 8.36 MB][error]
Returned from hook drush_make [3.46 sec, 8.35 MB][debug]
Command dispatch complete [3.46 sec, 8.32 MB]

Basically drush looks for the module release history file on drupal.org.

I have not found any specific documentation regarding downloading from private repos. However various snippets taken from presentations show the same make parameters that I have used.

I am using drush 7.0.0., php 5.5.26 and Windows 7.

How to fix the issue?

Add a line to the make file to make it look like so:

core = 7.x
api = 2
projects[cs_all][type] = "module"
projects[cs_all][subdir] = "contrib"
projects[cs_all][download][url] = "git@bitbucket.org:myrepo/cs_all.git"
projects[cs_all][download][type] = "git"
projects[cs_all][download][branch] = "master"

So add the line to indicate 'type = git' . That would make it look closer to what is documented on https://www.drupal.org/node/1432374 ...

Curious to hear what results you'd get then.


How to handle refunds / returning goods with drupal commerce i'm just trying to figure out whatcould be the bestway to handle "refunds" and the return of the shipped goods with Drupal Commerce.
Is there some custom modules for that?How would you handle this case?

There hasn't been created any module that handles this. How to approach this also depends a lot on the custom logic in your store like

How are payments created
How should payments be refunded
What happens if returned goods has damage
...

Anyways, what you could do for starters, is to create a custom order status to mark that the goods have been returned. Most of the rest is most likely custom store logic anyways.


Migrating Users with Migrate D2D when/if they already exist How does Migrate D2D module handle the migration of users if the matching users already exist in the database? I did a user import with MySQL different way earlier, but I want to do it through this module in order to scoop up a few missing pieces, such as the user avatars.

Thanks!

If Migrate and Migrate D2d modules are installed with the UIs, go to Content > Migrate tab. Once you get the migration set up, there is an option under "options". Check "update" and it will just update the existing users with any information that is new or not matched, keeping the UIDs, etc. It will also update with any new users. It's a long process if you have a lot of users, but so far so good.