Selecting English from language selector fails I have setup a multilingual website using the i18n and domain access modules. Each country has its own domain and on a few of these domains multiple languages are available. eg. fr.domain.com has the available languages French, English, German and Dutch with French being the default. When selecting English as a language from the language selector on this French domain the translation fails and instead either loads the domains default language or I receive a 'Page Not Found' error. I have checked that all English content is available on this domain. All other languages translate correctly when selected from the drop down.

I'm really not sure where to go from here as I'm not too familiar with i18n modules so any help would be appreciated.

Go to Configuration and choose Languages.
Edit 'English' language
Add 'en' in 'Path prefix language code' filed
save and flush all cache


Deleting a node just after it has been added I want to delete a node after it has been added (or modified), if certain conditions happen.

Is it possible to do that with hook_node_insert? (Considering hook_node_insert  will actually be executed just before the node is added to the database.)

I think Rules module will be helpful for you in this kind of scenario. Rules module help us to define actions on different events(like user creation, node creation/updation/deletion). It is a very powerful module.


Is it possible to use rules to set user profile pictures? I would like to use the rules module's Set a data value action to set a user's profile picture whenever that user uploads an image of an "image" content type that I have created.

However, the user profile picture does not appear as an option in the data selector for site:current user.  Is there another way to set the user profile picture using rules or am I out of luck?

Create a componnent in rule with this ! On the componnent you have 2 parameters. One for the user and another one for the file you want to use ! I use Drupal 7.

$uid = $user->uid;
$account = user_load($uid);
$thefile = file_load($file->fid);

$edit['picture'] = $thefile;
user_save($account, $edit);

Call the componnent from the rules you want. On my side i'm using a flag to trig the rules. The user mark an image to use it has a profile picture and it work.

I use this link has a starter to create the rule. http://taggartjensen.com/code-snip/drupal-7-set-user-picture-programmatically

Good luck !


Hook for URL admin/people/create What is the hook to alter the form that appears for the URL admin/people/create?

I tried hook_form_alter(), but that's not the right one.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case "user_register_form" :
      //Your Logic
    break;
  }
}

But for performance issue use hook_form_FORM_ID_alter()


Make search page with Taxonomy I am fairly new to Drupal and i'm working on a already existing site, so i'm facing a lot of issues. I need to make a page that shows nodes of a certain type, it has to contain the following features:

It has to show a search form on top of the page (the site is using the Apache Solr module) to search only content of one type
It has to show nodes grouped under their taxonomy fields. There are 3 vocabularies and nodes have to be listed for each vocabulary, for example:

Vocabulary 1

Term 1

Node 1

Node 2

Vocabulary 2

Term 2

Node 1

Node 3

Nodes can be shown more than once for each Taxonomy term

I know i'm asking a lot and probably the question is borderline with the stackexchange rules, but i have tried a lot of modules and solutions (for example using the Views module) but i just can't get what i want no matter how i try

to reduce results by the content type, when you set up the view, filter by content-type, and select the appropriate content type. If it already exists, use a FILTER CRITERIA and use content-type (I believe this can also be accomplished through the search settings)
to group: set format to fields, add the taxonomy term to the fields list to group by (you can hide from display if desired), click on Settings under FORMAT. There you can group by any field currently in the view
for Solr, take a look at Apache Solr Views Module and the related documentation for implementing this functionality.

Apache Solr Views:

  This module provides a Views integration to the Apache Solr Search
  Integration project. It provides the views plugins and handlers needed
  to be able to create a view that fetches its results from Apachesolr
  index, without hitting the database.


Display the title of related nodes from taxonomy in block How can I display the title of related news in a block shown in node page?

For example, I create the content type "news", and add "news" nodes that have taxonomy terms taken from the same vocabulary; now I want to show the list of the related node basing on the taxonomy terms associated with the nodes.

How can I display this bock only for "news" nodes?

If I understand your question correctly, you can just use Views to accomplish this.

To display a block that lists other node titles with related taxonomy terms:

Create a Block View
Add the field Node:Title (make it link to its node)
Add the argument Taxonomy: Term ID
Configure this argument as follows:

  Check Provide default argument
  Select PHP Code
  Add the following code:

$node = node_load(arg(1));
  if($node) {
    if ($node->taxonomy) {
      foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
      return implode('+',$terms);
    }
    else {
      return;
    }
  }
  else {
      return;
  }

  Check Allow multiple terms per argument
  Check Reduce duplicates

Now you need to add the second argument in order to exclude the current node from the list. Click [+] button of the arguments section.
Select Node:Nid
Set the "Action to take if argument is not present" to Provide default argument
Set the "Default argument type" to Node ID from URL
Check Exclude the argument
Save your view

You can customize this however you like, such as filtering to a specific content type (ie "News"), can filter by post date, sort by: post date, random, etc.

For a whole discussion on this see http://drupal.org/node/65375

(Sorry for the poor code formatting, not sure how to format code inside a blockquote and list)


How to remove language indicator in content region? It took me a while to figure out how to remove the language switches from the bottom of each page. Eventually the switch was in a somewhat logical location (Multilanguage settings > Article options). (Oh, new question. I translated those menu items myself, because - mysteriously - my "backend" is in German. I don't remember how that happened. Everything I can find, default language, user language, is set to English. Where can the "backend" language be set?)
But what I've come here for:
There still is a language indicator at the bottom of each page ("Language: English"), and I cannot find how to get rid of that. CSS would be fine, but it does not have a specific class/id, so I cannot grab it.

Home » Administration » Configuration » Regional and language »
  Multilingual settings

then

go to the "Node Options" tab

check

  Hide content translation links


Node tagged with more than one taxonomy, how to keep expanded the specific taxonomy menu the user has used to reach a node I have nodes associated to more than one taxonomy vocabulary, so the same node can be listed/reached in different ways, for example:

Brand > Family line > model > NODES

Veicles > category > NODES

e.g.

Ferrari > Top-Luxury > Testarossa > NODES > NODE-A

Cars > Supercars > NODES > NODE-A

By Design every node can have only and only one URL: it's ok for me (and for SEO)

Now I have created different taxonomy menus (based on the above taxonomies) to retrieve nodes in different ways:

TAXONOMY MENU A: Ferrari > Top-Luxury > Testarossa > NODE-A

TAXONOMY MENU B: Cars > Supercars > NODE-A

The question is: is there a way to keep expanded the specific taxonomy menu the user has used to reach the node?

So:

if user has reached NODE-A trough MENU A then MENU A is showed and expanded in the page

if user has reached NODE-A trough MENU B then MENU B is showed and expanded in the page

Is there a way to accomplish this?

May be using SESSION variables? (ref: http://drupal.org/node/1443210 )

Thank you very much for any help

I've done this in my modules hook_init() implementation by using sessions, menu_get_object and menu_tree_set_path(). Here's some example code showing my general approach:

function mymodule_init() {
  // Save the active path for users when on taxonomy term pages.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
    $_SESSION['mymodule_path'] = $_GET['q'];
  }
  // The user is on a node page.
  if (arg(0) == 'node' && arg(1)) {
    $node = menu_get_object();
    // Assuming all the nodes in the taxonomy menu are of the same specific type.
    if ($node->type == 'mynodetype') {
      if (isset($_SESSION['mymodule_path'])) {
        menu_tree_set_path('menu-mymenu', $_SESSION['mymodule_path']);
      }
    }
  }


Content type always use view So I have a content type called MyContentType and two views: mycontents and mycontent/%.

mycontents shows all MyContentTypes with a pager. mycontent/% shows a single MyContentType based on node id.

How do I make it so when clicking on a content's header in mycontents (or any other way of displaying MyContentType) takes it through to mycontent/[nid]?

Use Views 'rewrite output' feature for the Field: Title field on your mycontents view.

First, make sure you have added the Content: NID field to your view.  If you don't want this to be visible on your View, you can 'Exclude it from display` as noted in the graphic below.

You will also need to reorder your views fields to ensure Content:NID is listed before your title so you can access it in the next step.

It's very important to to note that the Content: Nid field is above the Content: Title field.

Next, edit Content: Title and scroll down to and open the 'Rewrite Results' section.

Note: You may need to uncheck the 'Link this field to the original piece of content' checkbox for the Content: Title field.

In the 'Rewrite Results' section, check the box titled 'Output this field as a link.'  In this section, if you scroll down, you will see a link titled 'Replacement Patterns.'  This is where we will get the variables we need for our URL.

In the 'Link Path' box, enter your destination URL: mycontent/[nid]

Don't forget to save your view, but your titles should now be linked properly.


Resolving internal image paths? Inside my template.php I am populating a custom variable to be used inside my views-view-unformatted--latest_stories.tpl.php

The image data associated with the content type has the structure:

[field_photos] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 4
                        [uid] => 1
                        [filename] => DSCF2639_0.jpg
                        [uri] => public://story/photos/DSCF2639_0.jpg
                        [filemime] => image/jpeg
                        [filesize] => 129245
                        [status] => 1
                        [timestamp] => 1397504538
                        [alt] =>
                        [title] =>
                        [width] => 800
                        [height] => 600
                    )

                [1] => Array
                    (
                        [fid] => 5
                        [uid] => 1
                        [filename] => DSCF2657.jpg
                        [uri] => public://story/photos/DSCF2657.jpg
                        [filemime] => image/jpeg
                        [filesize] => 89144
                        [status] => 1
                        [timestamp] => 1397504538
                        [alt] =>
                        [title] =>
                        [width] => 800
                        [height] => 600
                    )

            )

    )

How do I translate the path to a URI which a browser will be able to resolve?

Do I simply strip the public://

What if I move my files to AWS at a later date? Is there a function in drupal API that will handle this for me???

You can use the handy file_create_url() function:

  Creates a web-accessible URL for a stream to an external or local file.


Ajax HTTP error occured. HTTP Result code: 200 I get Ajax error when I click next button. You can test it here.

I have found out the problem. It is due to the custom module which I have made.

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<?php

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function custom_module_block_info()
{
    $blocks['tag_cloud'] = array(
        // The name that will appear in the block list.
        'info' => t('Custom Moudle'),
        // Default setting.
        'cache' => DRUPAL_CACHE_PER_ROLE
    );
    return $blocks;
}

When I remove the first two line (Doctype and meta). It works fine. But If I remove first two lines. It doesn't work on IE. I had to insert these two statements to get it working on IE. Now If I keep these two lines, it causes Ajax error, and if not It doesn't work on IE.

Can anyone help?

You can't just add arbitrary HTML at the top of a module file - Drupal runs through a process to theme the page, and you need hook into that.

You have a couple of options:

Override html.tpl.php in your theme, and add the tag to the <head> section manually. This is probably the easiest way.
Use drupal_add_html_head() in your module, e.g.

$tag = $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' => 'IE=edge',
  ),
);
drupal_add_html_head($tag, 'mymodule:ua_compatibility');

Make sure you pick an appropriate hook to do this in (preprocess_page, etc), don't just add it to the top of the file or it won't work.


Is there a way I can set access to specific form elements? I'm writing a custom ticketing system module for my company and I would like certain form elements disabled based on permissions. Is there a way I can do this without needing to make two separate forms (ex: user form, admin form)

I know for the items array in a menu hook, you can just set 'access arguments.' Preferably I'd like to just use the existing permissions I've already created for my module or even make it role specific.

You can use the FAPI #access property:

$form['some_element']['#access'] = user_access('some permission');


Strip out MS Word html tags on migrate I've got a migration set up whose source was apparently filled out using MS Word. The JSON source for the migration looks like this in places:

{
    "field_courses": "
Courses Taught (selected)
\r\n...
"
}

When the migration completes and I open the resulting node, the field is rendered like this:

The field in question is allowed to use everything from Plain Text all the way to Full HTML. When I save the node manually, not making any changes, all the nonsense is stripped out and I'm left with relatively sane HTML when I check out the source of that field.

I thought maybe it would be as simple as loading the entity by its pathauto alias (eg. /people/[person_id]) and running $entity->save() on it as soon as it's been imported, but that's not removing the formatting. Any way that I can get it to display correctly without requiring a content manager to manually save 500+ nodes?

Found a great way to do this automatically after comparing the Devel tab on a node before and after manually saving it. I realize this is a somewhat narrow use case, but I think it's pretty strong nonetheless.

Create a CKEditor profile (I called it "Bio Cleaner", machine name bio_cleaner) and limit it to the tags and attributes you want. In my case, it's <a href hreflang> <ul type> <ol start type> <li> <br> <p>.
For any "formatted" text field in your content types, add the new CKEditor profile as an allowed profile.
In your migration, rather than just dumping the raw contents into a field name, set it up like so:

(Sorry for the image - Stack Exchange apparently can't format yaml?)

Anyway, the secret sauce is to to set the /value key of the target field to the value pulled from the migration, and to set the /format key to the new format you created. Drupal will automagically clean up whatever tags aren't included in your profile when it saves the data.

NOTE: this relies on having the Allowed Formats module installed.


Organic Groups - How to view articles in the context of the group I have OG setup on a site I am developing. The configuration is set to remove the main sites side bars when a Group is viewed. If an article that is only published in that group is viewed, it is opened in the context of the main Drupal site (All side bars are visible from the main site)

Is there a way to view the article so that it appears the user feels they are still in the group?

You can adjust Group context detection at admin/config/group/context when you have Organic groups context enabled. This will add the appropriate css classes in the body element, which will allow you to theme the rest of the page.


Is flush and clear cache the same? I know this is a very basic question. Is flush and clear cache the same in Drupal 7? How will I flush cache in DRupal 7? It seems like the only available option for me is clear cache. But I saw a video tutorial which uses flush cache in Drupal 7. What will I do to avail this option?

In this context, the English verbs "flush" and "clear" are equivalent.

However, I've never seen a command named "flush cache" in Drupal 7.  Not having seen the video tutorial you mention, it is impossible to tell what was ment.  In the standard GUI, the button "Clear all caches" (under Home » Administration » Configuration » Development » Clear cache) is (AFAIK) the only way to do it.

If you have Drush installed, you can do more or less the same thing using the CLI with the following command:

drush cache-clear all

The difference is that the command drush cache-clear all also clear its internal cache, and there may be subtle differences because the drush user and web-server user are different, and may therefore interact different with file permissions to caches in the file system, such as the css registry.

However, Drush also allows you to make more targeted cache clears, see: Making Targeted Drupal Cache Clears using Drush.


How to get a variable from FieldWidget in the same modules Template I have module that is currently setup like this

module
  -signature.module
  -signature.info.yml
  -src
    -Plugin
      -Field
        -FieldWiget
          -SignatureWidget.php
  -templates
    -signature.html.twig

Everything in the module works correctly as is. I'm trying to pass a variable $field_name = $items->getName(); from SignatureWidget.php to signature.html.twig (or signature.module so that I can then pass it to signature.html.twig). I'm trying to do this in order to apply ids generated from a variable in the widget to some of the markup in the template. How would one do this?

I understand how to do this from the .module file (Use a twig template instead of a render array in a custom module admin page), but can't seem to figure it out when it comes to plugin variables.
The hook_theme in module associated with the widget looks like this.

function signature_theme() {

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

The widget code from SignatureWidget.php looks like this

<?php

namespace Drupal\signature\Plugin\Field\FieldWidget;

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

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

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

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

    $file_upload_help = array(
        '#theme' => 'signature',
        '#sign_src' => $value,
      );
     $sign_thumb = array( '#type'   => 'html_tag',
                          '#tag' => 'img',
                          '#attributes' => array('src' => '', 'id' => 'signature_thumb', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

$field_name = $items->getName();

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

$text_area_id = 'signature_field_' . $field_name;

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

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

}

The template from signature.html.twig looks like this.

    <canvas width="450" height="200" class="sign-canvas">SIGNATURE CANVAS</canvas>
{% if(sign_src != '') %}

{% endif %}
     <button type="button" id="clear-sign" class="button clear" data-action="clear">Clear</button>

I'm trying to return the string value from $text_area_id in SignatureWidget.php from within signature.html.twig

You already pass the template variable sign_src to your template. Now you want to pass an additional variable. You can easily do this by extending your hook_theme implementation:

/**
 * Implements hook_theme().
 */
function signature_theme() {
  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => [
      'sign_src' => NULL,
      'text_area_id' => NULL,
    ],
  ];
  return $theme;
}

Then pass the ID into your template like this:

$value = $items[$delta]->value ?: '';
$text_area_id = 'signature_field_' . $items->getName();

$file_upload_help = [
  '#theme' => 'signature',
  '#sign_src' => $value,
  '#text_area_id' => $text_area_id,
];

And use it in your template like this:

{{ text_area_id }}

Edit: Some further suggestions for your code snippets:

Wherever possible, you should leave rendering to the theming engine and avoid manually calling the \Drupal::service('renderer')->renderPlain() method. Your description will do just fine with the render array. Your #suffix can be changed to a distinct child element of your widget element (note: there is no hash before):

$element['#description'] = $file_upload_help;
$element['suffix'] = $sign_thumb;

In your template, you can change the empty check to

{% if sign_src %}
  <img src="{{sign_src}}" class="sign-img" />
{% endif %}

And should wrap the src URL into quotes.

A final note about the URL itself: It seems to be a user given value. If so, consider using UrlHelper::stripDangerousProtocols before you pass it into the template.


how to get correct user id on page I've added two custom fields to my user form - field_license and field_download_date. In my preprocess_page function, I'm doing this:

if(isset($vars['user'])) {
   $user_data = user_load($vars['user']->uid);
   error_log("userdata");
   error_log(print_r($user_data, 1));
}

I'm not trying to get the current user info, but a specific user. When I look at the error log, though, $user_data is printing out the info of the user I'm logged in as, not the user that's displaying on the page based on the URL (mysite.com/user/2). How do I get the data for the user based on the url?

For getting user based on current page, you can try to use $account = menu_get_object('user') code.
Var $account will contain user object.
Read more about this function here: https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7


Alternate modules/themes directory I'm trying to setup an alternate modules and themes directory which I can track with GIT separate from the contributed modules directory.

Following this question, I created a directory in the following structure:

/var/www/Mysite
       -sites/samplesite/modules/mymodule

mymodule was working just fine when it was based in sites/all/modules/custom/mymodule but once moved it was no longer listing on the modules page, nor the features page - mymodule is features generated.

I attempted the following directory structure:

/var/www/samplesite
       -sites/samplesite/modules/mymodule

But it's still not working.

Can anyone please help me with this problem?

Putting modules in sites/samplesite/modules/mymodule is specifically for a multi-site setup.

Drupal won't just load all modules in all sites directories all the time, it will only load modules in the samplesite directory if you are hitting the samplesite domain (or you have an entry in the sites/sites.php file to tell Drupal which domains map to samplesite.

The other option from the page you link to is to make a directory in sites/all/modules that is a symlink to your custom module directory.
Then (assuming you're using Apache), make sure your server is configured to enable the FollowSymLinks option.

There are also a couple of other options:

Add a directory for your modules, eg. sites/all/modules/samplesite or whatever is logical to call it. Exclude that directory in your main .gitignore file. make that new directory a clone of your other modules repository. Alternatively you could not have the sub directory and have separate repositories for each module.
Using a similar directory structure as above, use git subtree to have a repository in a repository (or many individual module repositories if that is your requirement). This seems like a decent post to give you more information on git subtree: http://getlevelten.com/blog/tom-mccracken/smarter-drupal-projects-projects-management-git-subtree

Either method may be preferable depending on your situation however I would probably recommend the subtree method over the completely separate repositories. It would be easier to manage things like deployments, since with the subtree method the main repo still contains everything, even though the source repos are different.


How to migrate tables in nodes from D6 to D7, created with the tablefield module I am 90% done with my migration from D6 to D7. The last thing to figure out is how to map a table in certain nodes, created with the tablefield module in D6, into a table in D7, also created with tablefield. Just mapping the fields does not do the trick.

$this->addFieldMapping('field_D7_table', 'field_D6_table');

With the above mapping there are no error messages, the table is just empty after the migration. I can see that the data is stored in serialized form in the legacy database. Can anyone point me in the right direction?

Tablefield does not currently include migration support - there is a patch to add it at https://www.drupal.org/node/2317245. If you try out the patch and report on your results there, you may help move it forward.


Display a view in my frontpage I would like to display a view in one part of my page by code but i cannot figure it out why it doesn't work

In page.tpl.php i called the next function:

views_embed_view('name_of_view');

If i assigned it to a variable and execute this:

print render($x);

Then i get the html code of the view. Actually I would like to customize the view also. How could i do it ?

print views_embed_view('name_of_view','defaults');

no need of rendering also a second arguments are there  as display name

views_embed_view()

  Embed a view using a PHP snippet.

  This function is meant to be called from PHP snippets, should one wish
  to embed a view in a node or something. It's meant to provide the
  simplest solution and doesn't really offer a lot of options, but
  breaking the function apart is pretty easy, and this provides a
  worthwhile guide to doing so.


Custom create account form included in a create content form I am new to Drupal 7 ( 1 month ) and have to do a rather complex task.

I have a content type (lets call it MyContent) for which i tried to create a custom form (I imported the fields from the original add content form in my own custom module generated page) which contains, among other fields, an email field, and i need to add 1 more field called password. With these 2 fields , i want on form submit:

*IF the email & password combination does not already exist

-> first create a user account taking the email as username and password as password ,
-> then create the content(disabled),
-> then make the site visitor confirm his email to enable his account
-> and after validation make the content viewable by all

*IF the email&password combination exists then :

-> create the content viewable

all of this by clicking one button.
The general ideea is that i want visitors, who are not logged, to be able to create content but in the process , get a user account generated as well. Also if the visitor already has an account then the email&password will work as a validator for letting the user create more content.

Is it even posible? I saw that Drupal has a lot of configurable options for users but nothing close to such a crazy ideea.

All of this is possible, but you will need to write a bit more code for it to work.

First, I suggest you use LoginToboggan.  LT provides a workflow for validating a user's email address which you can hook into either by code or perhaps with the Rules module.  LT already has the framework for tracking if a user is verified or not.  It will be up to you to write the code to create the user (not too hard) and to create the node as published or unpublished depending on the status of the user.

Second, you will have to decide what to do for verification (what if they enter the right email but wrong password?).


How to add separator option in Form API 'select' element? Is there a way with the Form API to specify that one or more #options in a 'select' element should be disabled? I would like to insert a separator in my dropdown options that is not a selectable value.

If it's really a separator you're looking to add then it might make more semantic sense to use <optgroup>s to group your select options.

You can do this with the form API simply by wrapping each group you want in the <select> in an array, keyed by the title you want for the label:

$form['test'] = array(
  '#type' => 'select',
  '#title' => 'test',
  '#weight' => -10000,
  '#options' => array(
    'Group 1' => array(
      1 => 'Group 1 Item 1'
    ),
    'Group 2' => array(
      2 => 'Group 2 Item 1',
      3 => 'Group 2 Item 2'
    )
  )
);

That will produce a select list like this:


Modal dialog doesn't work I want to display ctools modal. I tried the following code.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['my_module/%ctools_js/test-page'] = array(
    'title' => 'Demo CTools Page',
    'page callback' => 'my_module_modal',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_modal($js) {
  $output = '
' . t('Test content?') . '
';
  dsm($js);
  if ($js) {
  ctools_include('ajax');
    ctools_include('modal');

  ctools_modal_add_js();
    return ctools_modal_render('Define as start matrix', $output);
  }

  return $output;
}

The link where I click is

Open modal

But it returns me only the content of the page with no modal.
When I printed the $js variable, it is displaying 0. While the javascript is enabled in the browser. I have checked it with multiple browsers .

What can be the issue?

I have found the solution.

You need to add these 3 lines of code to the page where the link Open modal is displaying.

ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();


Creating a token for the image field file path with node reference nid Since there is not support for fields in Drupal 7 tokens, how do I create the code to replace a token in an image field file path?

EDIT:
First, this is with the Node Reference URL widget so the NID of the referenced node is loaded into the form array as long as the link was clicked on the referenced node.

I realize that there isn't any context to load the information to pass to the token module because there isn't any information about the node by the time token_replace() is called. This is before the NID of the referenced node is added to the form.

Adding the file path by using hook_form_FORM_ID_form_alter() works, but it's not very safe. The user might not use the Node Reference URL widget to access the page in which case the node is saved with a reference while the image path didn't have access at any point for know about the NID of the referenced node. And, if the node is then edited it will change the path on creation as it will then know about the referenced node making a mess of the place.

Here is the simple code which isn't very safe. I wouldn't mind a better solution.

Update:

It turns out that the node reference URL widget can be set to return a page not found if the referenced node's URL is not in the URL, which would make this function a little safer as it forces the user to only be able to create the node if they clicked the create node link on the referenced page.

/**
*  Implements hook_form_FORM_ID_form_alter\
*/
function HOOK_form_photo_node_form_alter(&$form, &$form_state) {
  $lang = $form['language']['#value'];
  $form['field_business_photo'][$lang][0]['#upload_location'] = 'public://photo/' . $form['field_reference_business'][$lang][0]['nid']['#default_value'];
}

The answer is using the Fieldfield Paths module.

  The FileField Paths module extends the default functionality of Drupals core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.


Migrate from xml with two attributes as condition I have a problem with drupal migrate, i'm trying migrate content with this xpath:

item_xpath = '/import/content/contentInstance[@contentTypeId=\'ac1ssss___\' @window=\'blank\]';

when i execute drush ms return 0 results, however if i use only one condition in item_xpath:

item_xpath = '/import/content/contentInstance[@contentTypeId=\'ac1ssss___\']';

Return 15 results

'/import/content/contentInstance[**@contentTypeId=\'ac1ssss___\' @window=\'blank\]';

Return 10 results

The xml have content with two attributes, not migrate allows two conditions as attribute?

Thanks for all.

You don't mention what XML source plugin you're using - is it MigrateSourceXML? If so, note that (as documented), it does not read in the entire XML file thus general-purpose xpath is not available, it implements a limited subset of xpath syntax for selecting the items to import. You should use MigrateSourceMultiItems when you need full xpath syntax.


Friendly error page to replace WSOD This should be the easiest thing to do, but for some reason I just can't get it done.

I'm trying to get a friendly static error page to replace nasty 500 scenarios. For now I'm just trying to replicate a 500 situation on my local machine (Drupal 7 running on MAMP) by throwing in some crap characters on the top of my template.php in my theme, which does trigger a 500 situation, but for some reason the ErrorDocument directive in my .htaccess or Apache config file has no effect.

What I'm doing is quite simply this:

ErrorDocument 500 /500.html

And I have the simplest ever static html-page in the root of my site with the name of 500.html.

Still, when I intentionally break template.php, I get the dreaded White Screen Of Death instead of my nice friendly error page.

What am I doing wrong here? I've done this a billion times in non-Drupal setups but just can't get my head around this one.

500 error pages are strictly server error pages. Once the server hands off execution to PHP, Drupal/PHP are responsible for serving their own error page. You might try telling Drupal to redirect the user to a custom error page, along with an HTTP 500 status header, when it receives certain errors within a try...catch block.

However, note that some WSODs can occur at the system level and they could cause a fatal error that immediately halts execution and possibly prevent the catch to execute. One example of this is when your database is not properly tuned to handle queries of certain size (like when doing a Features revert all operation) - the database may choke up, giving you an insta-WSOD.

I'd say the best thing to do is check your apache, MySQL and PHP error logs, and try to isolate the root cause of WSOD on a case-by-case basis, as opposed to trying to cover them up with a pretty-error page. While the errors that cause the typical 500 server error pages sometimes are unavoidable, and having custom server error pages in production is feasible, having WSODs happening live is not.

It looks like you have the server error pages set up properly. You just need to make the distinction that typical server error pages != WSODs. Server error pages can be triggered because of high traffic and resource bottlenecks, but you shouldn't really be having WSODs happen in production, period. These typically happen because of poor coding, optimization or configuration. If you still see an WSOD, make sure you find (and solve) the root cause of the problem first, as opposed to trying to apply a band-aid to it.


Is there way for create custom "add userpoints transaction" form Good day to everyone!

I have view which show user list, current userpoints, and email. I want set some link, which will lead to add transaction form where name will already fill. Is there way to add userpoints transaction for specific user except standard form?

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Grant user points, to the user specified as a parameter for this Rules Component.

For an example of a Rules Action to grant user points, refer to the rule included in the answer to "How to grant User Points to viewing user when user has viewed content?".

Step 2

Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...


Uploading local photos to blog I notice here that I can upload a photo from my computer, like this one:

On my drupal site, I can do so as well, as an admininstrator. But for a regular authenticated user, I can't. Here's what regular users gets when they click on the upload media icon. Only access to gallery, not local files. Why?

Go to permissions settings page admin/people/permissions and search for the permission 'Import media files from the local filesystem'. Give this permission to all user roles that should be able to upload files from their local computer.


How To Calculate Sum() of a field in a view using use aggregation=Yes option I have  a field called payment_value for different customers i need to calculate the sum of payments for each customer , i can see ""use aggregation =Yes" at the view page but i dont know how to implement this option .
thanks a lot.

I am not sure if you have already found the answer. I found this question from Google, so I am answering this so that somebody else might benefit.

When you are using Aggregation = Yes, remember one rule of thumb : All the fields that you are selecting must either use GROUP BY that field or some aggregation function on that field.

In your case you have two fields, User Name and Payment value. Once you enable the Aggregation, you will find Aggregation settings beside your fields in Fields, Filter and Sort groups.

For User Name - click on Aggregation settings and select "Group Results together".
For Payment Value - click on Aggregation settings and select Aggregation type as SUM.

Check List

In-spite of the above if your view is not using, then the culprits are sort and filters. Be careful about them. Removing them and adding them back one by one may be a easier solution.
Remember that sorting is not necessary as GROUP BY does default sorting of groups. And more over if you add a sort it might add an additional GROUP BY, if your settings are not right.


Exporting menu along with code I am new to Drupal 8, been developing only with D7 until now and I have a question regarding menus. I need to create this basic main menu for the page, but I am not sure how to export it and send to the test site, later to production environment. What is the best way to export something like this without features? I've heard something about hook_install() functions in the profile that allow this, but I cannot really find any information about this. Can someone please provide me with some guidance? Thank you in advance.

As far as I know, the menu itself is exportable by the built-in config management but the links are not (because the menu is config, the links are content). So when you export the configs and import it on the target environment, you get an empty menu.

What you could do is manually create the menu links programmatically during deployment. One technique is to use a "deployment module", where you use a dummy module and take advantage of hook_update_N. As for creating the menu items in Drupal 8, this answer can probably help you.


How can I change the temporary file directory path without the UI? In Drupal 8, Is there any way to change the temporary file directory path if I don't have access to the UI page /admin/config/media/file-system, either with Drush or by modifying a config file?

Drush

drush config:set system.file path.temporary /tmp -y

settings.php

If done through settings.php it will no longer be changeable via either the interface or Drush.

Drupal 8.8+

See the change record.

$settings['file_temp_path'] = '/tmp';

Drupal 8.7 and below

$config['system.file']['path']['temporary'] = '/tmp';


Shopping cart is not updated after add to cart when you select an attributes In my drupal commerce I have a product type. it's name is "Cellphone"

in my product type I have a field named "color" that in field settings I have set this check box "Enable this field to function as an attribute field on Add to Cart forms."
so this field is an attribute.
color has two options. One is red and another is blue.

When I want to create a product display , I make two products for this product display one is blue and another is red.
So in product display, visitor is able to change the product via color attribute.

Now I have made and price attribute for my products. It's name is guarantee and it includes two options. "Type A" that increases price $100 and "Type B" that increases price $200

every thing works well. in product display page and during ordering, when user set color and also set an attribute, price of product change correctly. but after click on "Add to cart" button, the new item in shopping card block doesn't have correct price (it has base price without any attribute effects)
and when user press on F5 and refresh the browser page, shopping card block is corrected

do you know what is the reason and how can I solve this problem ?

Here is where I would do like the big stores, and add a separate line item (product) for the warrantee add-on where you you can have two variations of it, one for $100 add-on value, the other for $200 add-on and then in the product display page you can have a customer select which option if any to select, which will then be itemized in the cart by itself with its own description. If you want you can also have a product display page or just a page for the two to them. It would be a product type by itself, with variations as opposed to color terms describing variations of a cell phone.
And it might be easier on cart space.
And Warrantee variations are products that can be related by name.
You end up with less sku products: The cell phone product color variations, and the Warrantee two variations.


How can I programmatically change the active theme? How can I programmatically change the active Drupal 8 theme?

In Drupal 6, we used the following code.

global $custom_theme;
$custom_theme = 'garland';

In Drupal 7, we used hook_custom_theme().

In Drupal 8, what's the correct way to do this?

In Drupal 8, you use theme negotiators, which essentially are services using a specific tag. See the theme negotiators implemented by Drupal, to understand exactly how they work; the example given in the change record is not updated.
user.services.yml
  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

AdminNegotiator.php
<?php

namespace Drupal\user\Theme;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;

/**
 * Sets the active theme on admin pages.
 */
class AdminNegotiator implements ThemeNegotiatorInterface {
  use DeprecatedServicePropertyTrait;

  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = ['entityManager' => 'entity.manager'];

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $user;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The route admin context to determine whether a route is an admin one.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * Creates a new AdminNegotiator instance.
   *
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\AdminContext $admin_context
   *   The route admin context to determine whether the route is an admin one.
   */
  public function __construct(AccountInterface $user, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, AdminContext $admin_context) {
    $this->user = $user;
    $this->configFactory = $config_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->adminContext = $admin_context;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return ($this->entityTypeManager->hasHandler('user_role', 'storage') && $this->user->hasPermission('view the administration theme') && $this->adminContext->isAdminRoute($route_match->getRouteObject()));
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    return $this->configFactory->get('system.theme')->get('admin');
  }

}

The code is pretty easy to understand: The applies() method returns TRUE when the current route is the one for which your module wants to change the theme; the determineActiveTheme() method returns the theme machine name of the theme to apply.
See also ThemeNegotiator::determineActiveTheme() should not require a RouteMatch to be passed in for a possible change on the arguments received from the methods used by theme negotiators; if that patch is applied, you will need to change your theme negotiator code too.
That issue's status has been Needs work since May 10, 2018; it has been also moved to Drupal 9.2.x on December 28, 2018. Drupal 8.9.x could not get that change back-ported and it's probably safe to say that a Drupal 8.x module needs to use the RouteMatchInterface $route_match parameter for applies().


How to restrict what content types can be added to a Book? In activating the book module, I've noticed that all other content types on a Drupal 7 site have an option to add their nodes to a book. It would be ideal to restrict only the book nodes to go into a book. Does anyone know how to prevent other content types from being allowed to join the book party?

The answer seems to be within the permissions. For books there are a few main permissions (plus others in the Node section):

Administer book outlines
Create new books
Add content and child pages to books

Removing the 'Administer book outlines' will allow roles who have the other two permissions to create book pages but not see the option to add other content type nodes into a book. This is exactly what I was looking for.


Configure inline images upload path per content type There is a core feature that lets you configure where to save inline images uploaded using CKEditor:

Here you can specify the path where you want store inline images.

But this is global configuration, which works for all content types.

I want to have ability to control directory path per content type.

There is a module called File (Field) Paths which gives you ability to configure paths for only file fields under any content type but not for inline images.

Is there any module or a way to implement this?

Not directly. The only approach that I could think of right now is that you create a text format for each node type and then use a module like Allowed Formats or Better Formats to limit the allowed formats of each node type to that.

Maybe you can also alter the settings at runtime with some custom code based on the page that you're on right now, but I'm not sure.


How to configure a view accessible on user's profile only by that user I have a view listing the nodes a user created on /user/{user}/mycontent.

How should I configure the view so that other users won't have access it?

If you don't want them to see their own content instead of the user which profile they are currently viewing, you need to add a contextual filter

skip to 8:52 and watch Views Relationships and Contextual Filters

Note: this is for drupal 7, but I imagine the drupal 8 views look the same.


Add class to "link to content" view field I'm using Drupal 8 and building a view. I have a field, which happens to be a title field, and I have set it to link to content. I would like to know how I can simply add a btn class to the anchor tag. Right now the output looks like this:
... custom text ...

I know I can use the Rewrite Results view feature to accomplish this, however, I need more power than that because I am building a theme for a client. The theme needs to be more generic, so I need to be able to accomplish this in a template. Is there template suggestion/hook that would allow me to override this in a template such as .../templates/views-view-field--link.html.twig? Or is there a theme function that I could use to override the markup by adding the class I would like?
I've considered using the views-view-field.html.twig template and overriding the node_view type to accomplish this, but I'm not sure how to do that whilst keeping the custom text a user could be using because it's really hard to debug the field options.
Edit
I forgot to mention, this needs to rely on Drupal core. I can't expect the user to install any additional modules for it to work.

Along with Wims suggestion, I would suggest (as I usually do) to bypass fields in views, and render the view mode of the entity in question. Usually, this is sufficient in most cases if this is a presentation based view, and not a 'report' style view (where records are in table format and fields serve as cell data).

Then, supply the twig template for view modes, where the title is linked, and you can add the class(es) there. Now when you use that view mode to render in Views, it uses one template and is consistent, and Views that rely on rendering entities become easier to maintain and quicker to setup.

Here is an article that explains the difference and the benefit: https://www.amazeelabs.com/en/blog/views-field-rewriting-to-views-modes

That said, no, links themselves do not have a twig file (where you would see the anchor tag markup). I have seen the |merge option before that Wim linked to, though I have been unsuccessful in getting that to work in 8.2.5.

You could also implement theme_preprocess_field and supply the class to the attributes before it is rendered, though as you can imagine, if you have a lot of these, it'll be some work.


Proper backup procedure for remote site? I know variations of this question have already been asked here, but I could not find proper information on details for a backup procedure for a remote site. I am still new to Drupal.

Assuming a host handles multiple Drupal 7 sites under a /public_html directory, using the same MySQL installation:

/public_html/my_drupal_site_1/...
/public_html/my_drupal_site_2/...
/public_html/my_drupal_site_3/...
...

I see two situations to consider: i) Drush is not installed on the remote host, ii) Drush is installed on the remote host.

Regarding i), that is, Drush is not available:

What would be the proper step-by-step procedure to backup and restore my_drupal_site_2 on the remote host from a local pc, assuming the Backup & Migrate module is installed on this site?
Which part of the directory tree should be copied (eventually with FTP)?
Which part should be restored?
How to make sure only the part of the database for my_drupal_site_2 is backup and restored?
Does one need to create a database before restoring the back up?
Does one need to create an 'empty' Drupal site before restoring?

Regarding ii), that is, Drush is available, say via SSH on the remote site:

What would be the proper step-by-step procedure to backup and restore  my_drupal_site_2 on the remote host from a local pc, assuming the Backup & Migrate module is installed on this site?
Is there a way to synchronize a local directory tree from the remote directory tree? The idea is to put this content under subversion or git for example.

At last, is there a all-in-one solution? Like a script that could do everything at once? Thanks.

You set a path for manual and automatic backups in Backup & migrate module. You get the resulting tar.gz file using ftp to your local machine for backup. If you want to restore, from within the module you choose file to upload.
For the db backup just the generated file, for the files the /my_drupal_site_1/sites/ directory
See #2
You can create a new profile in Backup & Migrate module and select which tables to backup (restore only restores what was backed up so you are ok there). Partial backup requires a lot of caution as to not forget necessary tables.
If you are restoring to an existing site NO, if it is a migration you are after YES
See #5

I think you are better of using i rather than ii, as using drush is a lot more "technical" and mistake prone.

As for you last question, yes... use Backup & Migrate to create a DB backup file on the server and then get everything using FTP. Even better use CPanel or Plesk and backup Home and mySql alltogether.


Is it possible to run a module written for drupal 7 in drupal 6? In another question I was searching for a module that provides a simple shopping cart and checkout process (Is there a simple shopping cart and checkout process module?).

I have found this simple module called Basic Card.

I am running Drupal 6.x while this module is written only for Drupal 7.x.

Is it possible to run a Drupal 7.x module on a Drupal 6.x installation?

No, it's not generally possible without back-porting the code.

The API is very different between Drupal 6 and 7. A few things have remained the same, so it's theoretically possible that a module for one version might work as-is in the other version, but generally speaking, it's not possible.

For a proper idea of the task ahead of you, take a look at Converting 6.x modules to 7.x. Not a trivial task, unfortunately.

I just had a quick look and the specific module you've mentioned definitely won't work in Drupal 6, it would need to be re-written.


White screen of death: Fatal error: Allowed memory size of X bytes exhausted I have a issue with my Drupal installation, for example:

when I enable or disable the modules, It redirects me to a blank page,
when I create a new content type and save it, redirects me to a blank
page,
when I add a new view and save it, it redirects me to a blank page,
when I try to clear the cache, it redirects me back to a blank page,
or in similar cases.

Basically all the confirmation pages redirect me to a white screen. When I refresh it again, it shows me the page. I tried to increase the PHP memory value but it doesn't help.

Are there any other solutions for this?

The error which I'm having:

  Fatal error: Allowed memory size of 100663296 bytes exhausted (tried to allocate 8192 bytes) in sites/all/modules/views/plugins/views_plugin_localization_none.inc on line 1

I know this may be late, but it helped me. Most times a module causes WSOD, I couldn't just disable modules to test which it was, since I may have lost data in the process. What I did was to temporarily edit this function in module.inc, in the core includes directory

function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {

        print "Starting loading $module
";

        $function = $module . '_' . $hook;
        if (function_exists($function)) {
          $result = call_user_func_array($function, $args);
          if (isset($result) && is_array($result)) {
            $return = array_merge_recursive($return, $result);
          }
          elseif (isset($result)) {
            $return[] = $result;
          }
        }

        print "Finished loading $module
";

  }

  return $return;
}

And I added those 2 print statements in the code above, then refresh the page, the module which didn't reach the "Finish loading $module" statement is the one with the problem... it was devel in my case.

After finding the module, you can go into the system table and look for that module, set it's status = 0 and bootstrap = 0 or run the query:

UPDATE system SET status = 0, bootstrap = 0 WHERE name = 'module_name' LIMIT 1

Reference: Debugging Drupal White Screen of Death (WSOD)


Drupal custom OG subscribe url I am using latest version of Organic Groups module. And create a page with panel page to view this group (classroom) content type. After that I added group_group field to subscribe user in this node.

But when user is going to subscribe, this path look like:

siteURL/group/node/63/subscribe/og_user_node

But I want to customize this path which look like:

siteURL/classroom/subscribe/?classroomId=63

It's not necessary to make it (siteURL/classroom/subscribe/?classroomId=63)

But I want to remove "group/node" & "og_user_node" from url and replace with other word.

Thanks for your kind help.

I'll suggest the most easy thing to do: Create a menu item and in that menu item you'll create the membership by your self. Don't know why this happening to you but the solution i suggest might be quicker.


Views: Suggest nodes based on user behaviour and history I tried to search here and there to see if there's an easy solution for what I'm trying to do but to no avail!

I want to show a list of nodes using views based on user's behavior specifically based on previously viewed nodes and Likes on Rate module, so it will be something like "suggestions based on user".

What you're looking for is known as a Content Recommendation Engine (CRE). There are a few modules out there are provide elements of CRE functionality. See this g.d.o. post for a pretty comprehensive listing, but nothing is a popular, easy, & comprehensive CRE solution.

The most popular is Similar By Terms, but it's a pretty basic and doesn't take user viewing history into account. The most comprehensive are the various Recommender modules based on the Recommender API, one of which, Browsing History Recommender, is based off of viewing history, however this isn't an easy solution; it requires a few dependendencies.

Note that CRE's are complex; think of the man-hours and money NetFlix has spent for its proprietary CRE. You're probably not going to find an easy/comprehensive solution from a install-and-ready-to-go Drupal module. If none of the above can cover what you need, you're best going to a 3rd party that provides easy integration into any website (e.g. LinkWithin).


How to get views field data in defineOptions() method of custom filter? I am  creating a custom filter for views. In *.views.inc file I am using hook_views_data_alter() to create the filter in views. Then creating a class for filter that extends NumericFilter filter class. Now, in defineOptions() method I want to feed the min and max numbers. These min and max data comes from a field in the view. Therefore, I want to know how can I get field data in that defineOptions() method.

class ItemQuantity extends NumericFilter {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['value'] = [
      'contains' => [
        'min' => ['default' => ''],
        'max' => ['default' => ''],
        'value' => ['default' => ''],
      ],
    ];

    return $options;
  }

  public function operators() {
    $operators = parent::operators();
    $operators['overlaps'] = [
      'title' => $this->t('Overlaps by'),
      'method' => 'opOverlap',
      'short' => $this->t('<>'),
      'values' => 1,
    ];
    return $operators;
  }

  protected function opOverlap($field) {
    $this->query->addWhere($this->options['group'], $field, [$this->value['min'], $this->value['max']], 'IN');
  }

  /**
   * Override the query so that no filtering takes place if the user doesn't
   * select any options.
   */
  public function query() {
    if (!empty($this->value)) {
      parent::query();
    }
  }

  /**
   * Skip validation if no options have been chosen so we can use it as a
   * non-filter.
   */
  public function validate() {
    if (!empty($this->value)) {
      parent::validate();
    }
  }

}

I want to get the value of min_quantity field in the view.

You can access with:

$this->options['value']

Read more about this in Building Views Query Plugins for Drupal 8, Part 3


Interface translation - Body, Title built-in interface I use i18n and I10n_client to translate English to Dutch in my web page, however some interface variables are not changing.

I searched 'Body' and try to replace it with its Dutch word, it doesnt take effect no matter what I do http://imageshack.us/photo/my-images/831/searchbody1.png/

and http://imageshack.us/photo/my-images/576/searchbody2.png

How can I change this type of built in interfaces. I cant change "Title" as well.

If having it only in Dutch is enough for you, you could change it to Dutch directly in the Edit content type form; go to Admin -> Content -> Content types, select edit for the one you want to change. You can set a title and body label in the "Submission form settings" fieldset.

There is a bug report open for this, see http://drupal.org/node/1016006.

I also found some reports that this should work now with multiple languages, with i18n: http://drupal.org/node/149349#comment-1135605.


execute drush command from devel/php drupal Can any one please tell me how can I execute drush command from devel/php?

I can execute PHP codes from devel/php. But I don't know how can I execute drush command from devel/php. (As we know "devel/php" URL coming from devel module).

I have written some custom drush command for cron purpose. I can able to run those commands from command line.

> drush my-cmd or drush cc all or drush status , etc ... I can run it through command line.

Expecting some function as mentioned below to run from devel/php

some_function("drush cc all");

Someone tried to create a module to provide shell access from within a Drupal site, but it was never fully debugged. See the Drupal Terminal project.  Perhaps there have been advances in the jQuery terminal that might make it easier to get this working if someone revisited it.

If you want to exec Drush from within php, it is generally better to use drush_invoke_process() rather than exec("drush ...").

$values = drush_invoke_process("@site", "cc", array("all"), array("verbose"));

If you are just running a one-off command and you don't care about the command results, then exec("drush ...") is fine, though.


Set taxonomy field on node creation I have a node type 'blog_entry' that uses a taxonomy reference (tags). The tags are created if they don't already exist, i.e. the reference field uses the option 'Create referenced entities if they don't already exist'. My node bundle as well as the taxonmy term 'tags' have both a field 'field_section', which is also a taxonmy reference.

I would like to set the 'field_section' of the taxonomy 'tags' to the same value as the one 'field_section' on my 'blog_entry' node when I create a new node.

This means: when creating a ne blog_entry I'm selecting a value for the field_section and I'm entering a new value for the field_tags. The new taxonomy value is successfully created in 'tags' but I would also like to set it's field_section to the same value as choosen for the blog_entry.

thinking the fastest way to do this one is hook_node_insert() ...
see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.2.x

if i am following what your saying, you want to set the value of 'field_section' the newly created taxonomy term in tags? if so the following will get you started ..

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function YOURMODULE_node_insert(EntityInterface $entity) {
  $type = $entity->bundle();
  if (!empty($type) && $type == 'blog_entry') {
      $field_tags_terms = $entity->field_tags->referencedEntities();
      // Your selected term id.
      $field_section_id = $entity->field_section->target_id;
      if (!empty($field_tags_terms) && !empty($field_section_id)) {
          foreach ($field_tags_terms as $term) {
              $term->set('field_section', $field_section_id);
              // or
              // $term->field_section->appendItem(['target_id' => $field_section_id]);
              $term->save();
          }
      }
  }


Node reference - show parent node when viewing child I'm using References module. I have parent node where I can choose multiple child nodes for it. This parent has reference-field.
I have made views to list child nodes when viewing parent node.

Now I need to have views to show parent node when viewing child node.

This should be fairly easy to do(?), but I was not able to achieve it.
I tried with reverse reference relationship, but it does not show nothing on child page.

How to show parent node (in views) when viewing child node?

Create one content type view with views module,

Set relationship >> Content: Reference node (field_reference_node)

In contextual filter >> Content: Nid (relationship field_reference_node)

Pass NID of child node within argument will result all node referenced with parent content.


How do I unset a region in template.php AND have it alter the body classes In some cases I need to programmatically remove the sidebar_first region in template.php.  So, I'm doing something like:

function template_preprocess_page(&$variables) {
  if(my_condition){
    unset($variables['page']['sidebar_first']);
  }
}

this does, indeed, remove the sidebar, however, it does NOT alter the body classes.  So, I still have a class of

body.two-sidebars

...even though I unset one of them (so the proper class would be body.one-sidebar).

How can I programmatically remove a sidebar AND have it alter the body classes properly?

(please, for various reasons dont suggest creating a new template suggestion and altering the sidebar there.  that won't work in my case.  I am asking specifically how to remove a region programmatically)

If you look at the default template_preprocess_html, you will see

  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }

If you don't want this behavior, you should implement your own version which will run after.  Then, you just check your condition and muck with $variables['classes_array'] as needed.


Drupal 7 CKEditor and KCFinder, how to upload to private files directory I'm trying to configure KCFinder to upload to the private_files directory that I created outside of the web root. However, it seems like this may not be possible without hacking some library or module files as the KCFinder upload path requires the absolute URL of the website file upload path. I'd rather set this to my private file upload path "/var/www/private_files"
My best guess is that I can hardcode this in /var/www/my_site/sites/all/libraries/kcfinder/core/class/uploader.php but I don't know exactly what to change in this section, or if that will work at all:

// FULL URL
    if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)\/?$/',
            $this->config['uploadURL'], $patt)
    ) {
        list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
        $path = path::normalize($path);
        $this->config['uploadURL'] = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/$path";
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath("/$path");
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";

    // SITE ROOT
    } elseif ($this->config['uploadURL'] == "/") {
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::normalize($_SERVER['DOCUMENT_ROOT']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "/{$this->type}";

    // ABSOLUTE & RELATIVE
    } else {
        $this->config['uploadURL'] = (substr($this->config['uploadURL'], 0, 1) === "/")
            ? path::normalize($this->config['uploadURL'])
            : path::rel2abs_url($this->config['uploadURL']);
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath($this->config['uploadURL']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
    }

I found a solution that works at least in my case. I was on the right path... If you simply want to hardcode an upload path, you just need to configure two things in the uploader.php, the uploadDir where the files will be stored, and the Drupal URL where Drupal can find the private files, in my case:

// UPLOAD FOLDER INIT

    // hardcode private file upload path outside of web root, can't be configured through the UI that I could find
    $this->config['uploadDir'] = '/var/www/private_files';
    // hardcode the private file url that Drupal needs to be able to access private files internally
    $this->config['uploadURL'] = '/system/files';

I know uploadDir already because that's where I've already configured private files to be stored. To find uploadDir, I linked to a private file already located in /var/www/private_files, then double clicked to see the first part of the URL on the dialog that points to where the root of /var/www/private_files is located.

The next thing I had to do was disable htaccess checking in the KCEditor config file (/sites/all/libraries/kceditor/conf/config.php) by setting '_check4htaccess' => false


How can I (programmatically) display a custom block with user profile links in dropdown? I would like to display a custom block with some links for authenticated users like drupal.org does.

I would like to display username next to user's picture, and custom menu items. For example, "My contents" where url is something like this: "/user/{uid}/my-contents".

Do you have any idea how to create that?

Ps: I tried "menu_token" module but it didn't work for me correctly.

If you don't have any issue rendering a block of menu, you can just show up a menu there which I suppose you've got that covered. for the UID part there are couple of workarounds for this:

Using Views
Menu Token
Me (Drupal 7) only
Templating: Much easier approach

The Views way

Number 1, using views is a long story, I'll keep it short and I move on to number 2, my own approach. With views you can use contextual filters and build your own custom links using "Current logged in user" filter, you can randomly get a view from whatever and override it with the HTML structure of your need. in case you need a more in depth answer for this, let me know and I will update my answer

Menu Token

This module is exactly what we need, but we have to consider some bugs that it currently has, if you check the issue queue there are some major issues with it, but still, you can manage to get it working with a little bit of dirty hacking, using jQuery/JavaScript

The issue with this module is that you cannot use the token in middle of a string for instance: /user/{uid}/my-contents wouldn't work but simply /{uid} works just fine.

So in our case, we override the href attribute and hardcode the path we want to it as prefix and suffix, using the UID

This is not the best practice at all, but in case anyone wants a quick solution, this is what I suggest, in case you need help with the jQuery part, let me know and I will update the answer.

ME module - Drupal 7 only

for those who have this issue in Drupal 7, this module considers /me as the user ID if configured properly, so a link in question would become something like this: /user/me/my-contents

Templating

So let's say we edit our page.html.twig file so we can create our custom structure for our menu, then in our case, we can simply refer to the current user's UID like so:

Test menu item


Change blog comments display order I have a Drupal 7 site with blog and comments enabled for certain user groups and the users complain that in longer discussions like this one the order of comments is totally chaotic, they just can't follow it.

Is there please a way to change the order? I'd be happy with all blog comments sorted by the creation date.

I've looked around, but couldn't find any blog settings. I've tried to construct my own path admin/content/blog/settings too, but there was nothing about sorting.

Thank you!
Alex

You can set the "threading" option for each node type on the node type form (eg. on admin/structure/types/manage/article, where 'article' is the name of your content type). Deselecting that will put all comments in chronological order.

As far as I can see, the setting for the sort order (newest first/oldest first) was removed in this issue, but I'm not sure why.


hook_install() doesn't seem to work, even though I have disabled and uninstalled module I'm writing a module that will enable an editor to determine whether a script is available on a specific node, in order to improve page load times.

I need to create a database table to hold an indicator showing, for each node ID, whether the script is available. My code is this.

function script_show_schema() {
    $schema['script_show_enabled'] = array(
        'description' => 'Tracks whether Script Show is enabled for a given node',
        'fields' => array(
            'nid' => array(
                'description' => 'The {node}.nid that has Script Show enabled',
                'type' => 'int',
}               'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('nid'),
    );
    return $schema;
}

I've disabled, then uninstalled, then re-enabled my module through the admin UI, (as opposed to using Drush), but I still don't seem to be able to see my database tables.

I know this question has been asked a couple of times before, but usually the solution seems to be the uninstall thing.

Does anyone have any idea on what is going wrong? I wonder if it's a DB permissions thing. But then, I guess Drupal has root access to the DB in order to create its tables in the first place.

Updates:

I am using version 7.23 of the core.

Here's my .info file:

; $Id$
name = Script Show
description = "Allows the user to specify that the Maxymiser script will only execute on specific pages"
package = JD Dev Modules
core = 7.x
files[] = script_show.module

flag

My entire module is here: github.com/jamesdesq/script_show.

The code in your git repo is not the same as the code posted here.  Both has syntax errors.  See @ARUN's answer for the bug in the code posted here.

As for the code in the git repo, there are two lines of random junk in it (indicated with red striketroughs below), causing Drupal to crash before the table is created in the database.

Remove those two lines and try again.


Batch API and curl or file_get_contents() issue in Drupal 7? Has anyone ever experienced issues with curl or file_get_contents() when using the batch API?
I'm trying to import nodes from a remote data source via batch API; I used file_get_contents() during one phase of development, but then it stopped working.

I can assure that neither curl or file_get_contents() is working, and that they work outside of batch API. Could it be related to how batch API makes its calls via AJAX? The really odd part is that it was working while I was trying to figure out how to get images into a field.

I know it's a really obscure question but I was hoping that someone else had experienced this before.

I think it isn't related to batch api.

Drupal has other HTTP client implementation - drupal_http_request()


How do I enable User 1 rights in minimal installation? I have Drupal 8 minimal installation profile and it does not seem to have provided super user status to the first admin account created during the installation process.

How do I enable it?

User 1 doesn't need any roles to have super user status. User 1 is exempted from the permissions system entirely. So, they automatically have all permissions, regardless of roles they may or may not have.


Permission denied when configuring my module though admin page I am following drupal's module development tutorials. I am using drupal 7.41 and my operating system is ubuntu.

I am creating a module that list links in the footer section of the page. I am making an admin configuration for my module. I have done everything what the tutorial said and I went to my configuration page, I couldn't see my configuration button of my module in admin/config/content. Here is my hook_menu() implementation:

function footer_links_menu() {
$items = array();

$items['admin/config/content/footer_links'] = array(
    'title' => 'Footer Links',
    'description' => 'Configuration for Footer links posts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('footer_links_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
);

return $items;
}

I have manually tried to access to admin/config/content/footer_links, I got a permission denied error. However, I was already logged in as the admin.
I have changed the value of access arguments to array('access content'). And it worked. What was the problem? If I leave my code like this, can others also edit my module through the form? Thanks in advance.

Try to change

'access arguments' => array('access administration pages'),

into

'access arguments' => array('administer site configuration'),


node_delete() is not deleting nodes I'm trying to use a drush function to flush out all of the drealty module's nodes in my drupal 6 install.  However, something is causing a memory leak and the nodes are not being deleted after node_delete is called.  What can I do?

Here is the memory exhausted error:

drush rets-flush
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 71 bytes) in /home/directory/public_html/sites/all/modules/filefield/field_file.inc on line 300
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Allowed memory size of 134217728 bytes exhausted (tried to
allocate 71 bytes) in
/home/directory/public_html/sites/all/modules/filefield/field_file.inc,
line 300

Here is the drush rets-flush function:

function drush_drealty_rets_flush() {
  set_time_limit(0);

  $result = db_query("SELECT nid FROM {node} WHERE type = 'drealty_property' OR type = 'drealty_agent' OR type = 'drealty_office' OR type = 'drealty_open_house'", $conid);

  $count = 0;
  while ($nid = db_fetch_object($result)) {
    node_delete($nid->nid);
    drush_log(dt('Deleting node id: @nid. ', array('@nid' => $nid->nid)));
    $count++;
  }
  drush_log(dt('Deleted @count nodes', array('@count' => $count)), 'success');
}

There are about 5000 records total.

Found the answer myself.  I had to run drush as admin:

drush -u admin rets-flush

I thought drush ran as admin automatically, but I guess not.


Drush is always scanning the whole drupal directory? Every time i run a drush command the command returns after 40s. (or more if time consuming operation like cache clean or so)

After strace the command i realized that drush is scanning my whole drupal directory. I have mounted via nfs an storage with thousands of Files which are accessed by an own module and i think there is no need for drush to scan these files on every run.
Is there an option to exclude a path ?

my files are in drupal_root/sites/default/files/my_module/nodes/nid/

Greetings Robert

There might be something wrong with your module... You say there are more than a thousand files scanned but are they placed in your module's directory ?

Drush is not supposed to scan your sites/default/files folder for instance or any other data folder you might have set. As a  best practice you should not place data in your module's path (obvious... isn't it ?). If you have done so, you should think about moving them somewhere else.

When executed, Drush scans all activated modules path (along with a few others such as sites/all/drush) for .drush.inc files. This is the expected behavior and that might cause your slow script execution.


How to add dynamic class in li element? Need to add dynamic class in li element of below code like dymanic democlass1,democlass2...... so-on in loop.

 {% if prefix_text %}

{{ prefix_text }}

 {% endif %}

{% for button in buttons %}

      {{ button.svg | raw }}
      {{ button.text }}

{% endfor %}

You can use

{{ loop.index }}

this will count up each time it goes through the loop


newly created fields values are not loaded with node_load I am loading nodes with node_load in one of my tpl.php, so i can get custom built teasers of nodes of specific content type in that tpl. Everything works fine, but from some unknown point of time i am not able to pull field values with node_load. Fields are included in node object, but there are no values in array!

For other custom fields i am able to get values, but for every newly created field- no value! (value is present in edit form and in database)

I am node_load-ing from tpl file of another content type. When i am trying to load those new fields from the tpl.php of its own content type, they are appearing.

But i see no logic because i have other custom fields that are being read with no problem.

Help please, i am pulling my hairs!

Oops.

All my values are there. I was fooled by output, reading values from wrong nodes. I have complex loops here pulling out nodes so i was fooled.

How trivial :(


CKEditor tabber shows tabs to the right on the screen when logged in as admin I have reported this question with the CKEditor tabber issues, but I thought I ask this question here too, in case I am missing something obviuos... I have installed the CKEditor tabber module and after creating some tabs and tab content, the tabs is pushed out to the right in the screen. Like this:

I noticed that when I log out the tabs appear above the content as expected. I have narrowed it down to the permission "Use admin toolbar". When the admin toolbar is shown, the CKEditor tabs is showed as on the image. When the admin toolbar is not shown, the CKEditor tabs shows as they should above the tab content.

I have spent hours trying to find how the toolbar affects the CSS in this way, but I can't figure out what to do...

Anyone?

UPDATE: I noticed that the "left" attribute is 100% too large in this section that is in charge of the first tab's positioning and width:

<dt id="tab-0-0" class="current style="width:16,6667%; left:100%;">

In the js file semantic-tabs.js this code is in charge of the above:

$(this).css({
  'width': (100 / numTabs) + '%',
  'left': (100 / numTabs * tabIndex) + '%'
});

So, if I add "-100" after tabIndex above the tabs are positioned correctly when logged in with the admin toolbar visible. If logged out the tabs are pushed to the left in this case. So the JS decides to add 100% to the "left" value when the toolbar is visible. Also I can see that for half a second the tabs are positioned correctly before being pushed out, every time I refresh the page. I am going crazy here...

In case anyone else has the same problem I will answer my own question. I found the answer to my problem in this issue for the same module: https://www.drupal.org/node/2774763
The problem was not exactly the same to begin with, but the solution was the same. The variable tabIndex needed to be placed within the function, not outside as a global. Problem solved.


Metatag Database updates need to be ran When im trying to add new node it gives me Error : The website encountered an unexpected error. Please try again later.

When I checked in Reports. I got this.

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'revision_id' in 'where clause': DELETE FROM {metatag} WHERE
  (entity_type = :db_condition_placeholder_0) AND (entity_id =
  :db_condition_placeholder_1) AND (revision_id =
  :db_condition_placeholder_2) AND (language =
  :db_condition_placeholder_3) ; Array ( [:db_condition_placeholder_0]
  => node [:db_condition_placeholder_1] => 133 [:db_condition_placeholder_2] => 133 [:db_condition_placeholder_3] =>
  und ) in metatag_metatags_save() (line 559 of
  /home/public_html/sites/all/modules/metatag/metatag.module).

Im using
Drupal 7.31
Metatag 7.x-1.0-rc2

Just create a local setup of drupal with meta tags module installed.

Now check for its table structure, if any of the table or column is missing add it manually. Because it can be issue occured you enabled the module.

Other soluion can be disable metatag module then uninstall it and then re-enable it. It might fix issue for you.
It is just the issue of missing table and column field.

Hope it will help.


How do I grab the current product SKU in code, as early as possible? In Drupal Commerce, using programming, what is the way to grab the product SKU of the product entity that is about to fire off and display on the page in a product display node, as early as possible?  I'm looking for something that is before panes and views are executed and drawn.

I know the SKU lives in $form_state['default_product']->sku within a hook_form_alter, but that is too late.

In panels, I know there is a time in hook_panels_pane_content_alter where I can scrape the SKU out of $content->content['#markup'].  That doesn't seem to update though as I change the selectors that affect which product is currently displaying.  So that's no good.

I need it as early as possible, because I want to pass that value into a view during hook_views_pre_view, which is executed very early.

Have you tried using menu_get_object?  It provides access to objects loaded by the current router item.

Once you've got the node, the product reference field is just going to list the products and Drupal Commerce may exclude products from the add to cart form based on rules and other modules.  But you can get the SKU of the first referenced product on the product display like this:

$node = menu_get_object(); // May want to check that it's a node.
$node = entity_metadata_wrapper('node', $node);
$products = $node->field_product->get(0)->sku->value(); // field_product is my product reference, may want to check that it exists.


How do I suggest broken link fixes to a Drupal module project page description? I noticed that a Drupal module's project page description has a broken link.

How do I suggest/contribute the change? Is this done through GIT?

Basically, you want to report documentation bug, because project page is maintained by module maintainers, and it's entry point to all other documentation.

You need to log in
Go to the module page
In the right sidebar, you will have section "Issues for [module name]"
Enter issue queue by clicking any link in this section, for example open bugs.
On the page "Issues for [module name]", click "Create a new issue"
Set the Component field to "Documentation" (unless maintainers defined better fitting component option for your purpose)
Fill all the rest as needed


Testing Batch API usage with Simpletest I've written a module that reads a csv of user records and imports them into Drupal 6 using the Batch API. The Batch API operations callback basically just does a user_save(). It works fine when I test it manually. I'm now writing a SimpleTest to verify it.

What I've found is that when I run my test (which extends DrupalWebTestCase), it actually creates new users in my primary Drupal's tables, rather than into the "simpletest" prefixed tables. I suspect this has something to do with the combination of SimpleTest and the Batch API.

Has anyone experienced this before?

SimpleTest 6.x-2.11
Drupal 6.22

Edit: Adding a very simple test case that duplicates the problem. After running the SimpleTest, my primary Drupal site will have 3 new users (u1, u2, u3) created in it. The test will fail, because no users will be created in the 'simpletest*' prefixed tables.

Module code:

function user_import_batch($user_data) {
  $batch = array(
    'title' => t('Importing users'),
    'operations' => array(
      array('userimport_process', array($user_data))
    ),
    'progress_message' => '',
    'finished' => 'userimport_finished',
  );
  batch_set($batch);
}

function userimport_process($user_data, &$context) {
  // Initialize
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($user_data);
    $context['results'] = array();
  }

  // Process max 20 users at a time
  $processed = 0;
  while ($context['sandbox']['progress'] < $context['sandbox']['max'] && $processed < 20) {
    $index = $context['sandbox']['progress'];

    // create user
    $account = user_save('', $user_data[$index]);

    $context['sandbox']['progress']++;
    $processed++;
  }
  $context['sandbox']['import_object'] = serialize($Import);

  // Finished yet?
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

Simpletest code:

class ImportTestCase extends DrupalWebTestCase {
  protected $privileged_user;

  public static function getInfo() {
    return array(
      'name' => 'User Import Test',
      'description' => 'Test',
      'group' => 'User Import Test',
    );
  }

  public function setUp() {
    parent::setUp();

    // Create and log in our privileged user.
    $permissions = array(
      'administer users',
    );
    $this->privileged_user = $this->drupalCreateUser($permissions); // user id 3
    $this->drupalLogin($this->privileged_user);
  }

   public function testAddUsers() {
     // import 3 users
     $user_data = array(
       array(
         'name' => 'u1',
         'mail' => 'u1@example.com',
         'pass' => 'password'
       ),
       array(
         'name' => 'u2',
         'mail' => 'u2@example.com',
         'pass' => 'password'
       ),
       array(
         'name' => 'u3',
         'mail' => 'u3@example.com',
         'pass' => 'password'
       ),
     );

     user_import_batch($user_data);

     // verify that the users have been created
     // this will fail, as the users will be created in the host site that is running the SimpleTest
     $imported_count = db_result(db_query('SELECT count(uid) FROM {users} WHERE name LIKE "u1" OR name LIKE "u2" OR name LIKE "u3"'));
     $this->assertEqual(count($user_data), $imported_count, 'Imported users appear in users table. Found ' . $imported_count);
   }
}

Running batch API in tests should work just fine, although there is an issue with the testbot.

Make sure you are always using curly braces for your tables, that's the usual issue when something like this happens. So for example SELECT * FROM {node}.

Edit:

Two things wrong with your code, as written in the comments.

You are not calling batch_process() in your code, so the batch is never executed within the tests.
My initial answer was not 100% correct. You can not trigger batch runs directly within your test code. A batch requires direct interaction with the browser and it is not possible to run tested batches (simpletest is already running as a batch run). What you need to do is create a test module, implement hook_menu() with a page callback and then call batch_set()/batch_process() there.


How to trigger a rule if a node has a certain Taxonomy term? I'm trying to create a rule using Rules that will apply a watermark to an image within a node (using the ImageCache Actions module) if that given node has a specific Taxonomy term. For example, nodes with the term "Video" will get a play button icon over their image.

Is there a way to add taxonomy terms as a condition in Rules? It seems like it would be a simple task but I can't seem to figure it out. Does anyone know how I could do this?

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tags" } },
      { "list_contains" : { "list" : [ "node:field-tags" ], "item" : "21" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_tags] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_tags", which is the machine name of the term reference field I want to check for.
List contains item "node:field-tags" and with Taxonomy term identifier value "21" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_tags] just got created or updated." (with [node:field_tags] the actual term with term id = 21).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions.

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Replace the Rules Event (if needed).
Within the Rules Conditions, perform these changes:

replace the "node" entity with your entity.
replace the machine name of term reference "field_tags", and adapt the "term id" to fit your case (for the term "Video").

Replace the Rules Action by whatever fits your case.


How can I print the value of the node body using PHP with the text format applied? I am printing the node body using PHP on an admin view via a template; however, when I do this, the text comes out as one giant block (spacing is ignored).  However, when I go to edit the node, the content is spaced properly.

My code looks like this:

print "Body: " . $body[0]['value'];

What do I need to change to make sure the spacing/formatting is printed out properly?

I believe you're looking for the check_markup() function:

Runs all the enabled filters on a piece of text.
Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.

E.g.
$markup = check_markup($body[0]['value'], $body[0]['format']);