Instead of using jQuery AJAX, you can achieve this by Drupal Form API AJAX.

You can hide the Actual submit button in the hook_form_alter using hide() and add a custom button with AJAX callback.

Or if you still want to practice this using jQuery AJAX, Drupal's way of handling AJAX calls is little different. You may have to first understand the hook_menu in Drupal. Once you have a clear understanding of this system, you have to create pages using this hook. In drupal, it is not advisable to create custom php files for handling AJAX callbacks. Instead you can create a page using hook_menu and handle the server callback there. For the JS part, the Drupal way is to use Drupal Behaviors

This is a small example of how it would look like.

Your custom module to handle AJAX login (sign_up.module)

<?php
function sign_up_menu {
    $items = array();
    $items['custom/user-login'] = array(
        'page callback' => 'custom_user_login_callback',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE
    );
    return $items;
}
function custom_user_login_callback(){
    /**
     *  You can validate the User credentials here and provide error message for invalid credentials or send him to welcome page using drupal_goto() for valid credentials
    **/
}

-

The custom JS file (sign_up.js)

Drupal.behaviors.customSignUp = {
    attach: function(context, settings) {
        $("#test", context).once(function(){
            $(this).click(function(){
                $.ajax({
                      url: Drupal.settings.basePath + 'custom/user-login',
                      type: 'POST',
                      data: {
                        username: /** Pass the User Name **/
                        password: /** Pass the Password **/
                      },
                      success: function(response) {
                        $('#ajax-response-wrapper').html(response);
                        Drupal.attachBehaviors();
                      }
                });
            });
        });
    }
};


slideshow images for one specific view, with alot of fields

you can use Field Slideshow. If it's not a good solution, another one would be to create 2 views (one slideshow with only the images, one normal with all the other fields) and, with CSS, position one over the other.

Have fun !


Send daily automated mails to specific roles programmatically

Yes! hook_cron is a good approach. Of course, you also will have to set up the server cron, which will trigger the Drupal one. Or at least that's the cleanest solution.

Here you can read how to configure cron.

If you don't use an OS cron to trigger, the following use case may appear.
You set the Drupal cron to run each day at 00:00.

But nobody is browsing the site at 00:00. The next user will come at 6:54 in the morning. By the request the cron will know: oh.. it's 6:54, I should have run the cron at 00:00, so I will run it now.

If the subscribed modules have heavy processes on going, the request for the user could be slow. There is your module, which sending emails (not a big deal) but also the Drupal garbage collector (temporary files, abounded fields etc..) may run by this time.
If this is the first extra cron hook of your site: don't mind it. It won't change much.


How to tell variable_get to get the value from the database and not the $conf array?

I don't think Drupal core has anything like that, no. For speed and efficiency, the variables array is in memory pretty much as soon as settings.php has been processed.

You've always got db_query():

$var = db_query('SELECT value FROM {variable} WHERE name = :name', array(':name' => 'var_name'))->fetchField();
$var = unserialize($var);

It would be trivial to build up an efficient variable_get_from_db function based on that.


Preprocessor to use a different template for popup window

You probably want:

print render($page['content']);

You can find the variables available to you in the template by printing get_defined_vars() using print_r(), core's debug() function, or one of the extremely handy devel module debugging functions such as kpr() or dpm().

I'd install devel and do this:

kpr(get_defined_vars());

Your modal method might not play nicely with page cache so I'd definitely test to make sure it fits your usecase.


You need to create a custom module for this.  You'll have to learn how to use PayPal's SOAP requests and handle it that way.

This question, as it is now, is FAR too broad in scope to answer in this forum beyond that though.


How to re-create vanilla field configuration strings programmatically for any field?

I guess you will need a combination of field_update_field() and field_create_field().

During field_create_field(), the settings are loaded from the default field definition as each field has defined in its own hook_field_info().

$field['settings'] += field_info_field_settings($field['type']);

What you are looking for is to apply this logic to field_update_field().

Basically you will need to load all fields:

$fields = field_info_fields();

Optionally limit the fields to your selection:

foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {} // Filter by type
  if ($field_name == 'some name') {} // Filter by name
}

And update the fields:

$field['settings'] = field_info_field_settings($field['type']);
field_update_field($field);

So I guess it should look something like this:

$fields = field_info_fields();
foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {
    $field['settings'] = field_info_field_settings($field['type']);
    field_update_field($field);
  }
}


How to create a relationship between a table in a database and content type in views d7?

You can certainly implement this functionality by creating a views plugin:

In your <module_name>.module file implement hook_views_api().
In your <module_name>.views.inc, implement hook_views_data(). Something roughly like this:

/** This hook should be placed in MODULENAME.views.inc and it will be
 * auto-loaded. MODULENAME.views.inc must be in the directory specified by the
 * 'path' key returned by MODULENAME_views_api(), or the same directory as the
 * .module file, if 'path' is unspecified.
 */
function MODULENAME_views_views_data() {
  $data = array();

  // Select/Create a category.
  $data['table_A']['table']['group'] = t('Your category');

  // Define the join with your table.
  $data['table_A']['table']['join'] = array(
      'node' => array(
      'left_field' => 'abc_nid',
      'field' => 'nid',
    ),
  );

  $data['table_A']['abc_code'] = array(
    'title' => t('ABC Code title'),
    'help' => t('Some help text.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
  return $data;
}

You can choose the appropriate handlers:

Views field handlers
Views sort handlers
Views filter handlers

If required you can add you own handlers by extending the handlers. But, adding a handler is required.
This will provide you a field, a filter and a sort criteria in your view of nodes which will display/filter/sort the fields on the basis of the value of abc_code for that particular field.


How to turn on block or panel from old site to the new one

Views out of the box support export / import functionality . You can export any view from any instance to any instance using below steps.. Make sure both the instances are in same Major Drupal version..

Login as administrator
Go to the view you want to export "admin/structure/views"
Edit View
Click on export link in the drop down

Copy content
Go to new site and navigate to "admin/structure/views/import"
Paste copied content and click on Import


Accessing all taxonomy terms from one specific vocabulary through url

Is there a functionality made for that particular page? Is that a term namde, a node or a view? Any kind of entity? Because if it is not, nothing will show up, obviously. Create a view page showing all taxonomy terms within that vocabulary. Taxonomy pages are for taxonomy terms only, not for taxonomy vocabulary based on some url scheme.


Update query not working for db_update and db_query("update

Try something like this, It should work.

$num_affected = db_query("UPDATE {field_data_field_department}
SET delta=:highest_delta
WHERE entity_id=:entity_id AND delta=:delta
", array(":highest_delta" => $highest_delta,":entity_id" => $entityID,":delta" => $delta))->fetchAll();


Translation view path broken after upgrade to 8.5.1

Because Content: Path has been removed in 8.5 version. Instead you should use Link to Content.


How can I target a webform results page to create a panel around?

Since webform, for showing results implements a different path than the standard node/%, you need a way to tell Panels to take over this path.

The module Page manager existing pages allows you to do this.

Install and enable the module. Go to admin/structure/pages/existing-pages/add, find the path /node/%webform_menu/done and add it to the list.

Now go to admin/structure/pages and you should see a new "task" for results, where you can customize the result page.

As pointed out by winchendonsprings, the results are available under Add Content >> Existing pages >> Existing page >> node overview.

In order to do this on a webform by webform basis, one will need to add a manual node context, where you select the webform you want by nid, and then add a selection rule that compares the current context against the manually loaded one.

Normally manually loaded contexts should be avoided as "hardcoding" node id's is rarely a good idea, but this seems like a good exception from the rule, although it will still not be properly exportable.


apparently , there is a field of that name ... and some node / entity which is trying to get saved automatically. Could you have Profile2 installed ?
Did you try the report on admin/reports/fields ?
If you dont find it there, try the database - finde the table that uses the column ie this way :

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'field_published_value'
AND TABLE_SCHEMA = 'yourdb'

i tried on a "default install" and didnt see it :)


If your contents are promoted to front page, they will be shown on front page.

If you want to see your content in a seperate page or block you should create a View from your contents, with the Views module


How to translate a custom Constraint message?

The constraint system is one of the few places where string literals aren't directly wrapped in t(). One reason for this is probably because the variables which form the "context" and string replacements for the messages aren't directly available when defining the constraint. @see \Drupal\Core\Validation\DrupalTranslator.

So the answer is: core does this for you. You can see exactly where this happens in: \Drupal\Core\TypedData\Validation\ExecutionContext::addViolation.


How to change bean's block view mode programmatically?

You can use hook_entity_view_mode_alter()

function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
    if ($timevalue1 == $value1) {
      $view_mode = 'view_mode1';
    } elseif {
      .......
    }
}


How to override a module in sites/all/modules directory?

Answering my own question here:

  Your installation will choose from the most specific one available
  (first /sites/sitename/modules (sitename typically might be - default), then /sites/all/modules, then
  /modules).

from Directory precedence and multi-site considerations.


Sorry I wasn't trying to be vague. My view was based on an entity, rather than content, like a node. So I wasn't seeing the "Has taxonomy term id" option in the list of contextual filters. I was only seeing specific taxonomy fields as options. I found that core does not offer that by default for other entities.

I did find a module that provided the functionality I was seeking:
https://www.drupal.org/project/taxonomy_entity_index

I will also say that this module seems to expect entities to have bundles. If not there is an error. I'm going to submit a patch soon.

Hopefully that will help others. I will take my 2 downvotes and go home now.

(I'll also include this issue link for having the functionality in core: https://www.drupal.org/project/drupal/issues/1040786)


The form_build_id is used as key to cache a particular build of the form. For multi-step forms, this allows the user to go back to an earlier build, make changes, and re-submit.

See also : drupal_build_form,  drupal_rebuild_form


I would say the easiest way is to make the first image also be the "featured" one, as then you already have most of the functionality built in.

It is then trivial to use a view that filters on "Image field: delta = 1", to give you only that one image, and then output it where appropriate.

A php savvy themer could also pull out the first image right in the template as well.


How to print id of user whose profile I visit rather than id of  logged in user?

The function menu_get_object() allows you to get a user/node/.. object based of the current request URL.

To get the account object, you can do this:

if ($account = menu_get_object('user')) {
  print $account->uid;
}


Please explain caching in complex render arrays

http://omnifik.com/blog/render-arrays-and-cache-drupal-7 is an excellent resource, I use it as a guide when caching render arrays. The nice thing about render arrays is they are recursive. So for the hook_menu page callback you can have that function return mutiple items. As an example I have the page callback function looks like this

function my_page_callback() {
  // Form dumps values in the URL, act on them.
  $input_values_from_form = drupal_get_query_parameters();

  // Get form with URL values set in the form as defaults.
  $input_form = drupal_get_form('my_form', $input_value_from_form);

  // Build table render array.
  $table = array(
    '#theme' => 'table',
    '#pre_render' => array('my_table_pre_render'),
    '#header' => $header,
    '#rows' => $rows,
    '#links' => $links,
    '#url_queries' => $url_queries,
    '#filters' => $filters,
    '#entity_types' => $entity_types,
    '#missing_info' => $missing_info,
    '#attributes' => array('class' => array('table', 'table-striped')),
    '#attached' => array('css' => array(drupal_get_path('module', 'my_module') . '/css/table.css' => array('type' => 'file'))),
    '#cache' => array(
      'keys' => $input_values_from_form,
      // Cache this for 1 hour.
      'expire' => REQUEST_TIME + 3600,
    ),
  );

  // Put them together.
  $page_array = array($input_form, $table);

  return $page_array;
}

So this will render the input form first and the table second. Using this you can in theory split up your complex page into many smaller parts caching each array separately.

In the above example theme_table does most of the work but some other parts get used inside my_table_pre_render so the '#theme' => 'table', here is a complex example but it shows how to do this.

Pick the keys for each render array wisely as in make it relevant only to that part of the page; see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_render_cid_create/7.x


Reading between the lines of the other mentioned question and its comments and answer, I've been able to pull out these useful bits of information.

You can do this with
hook_form_FORM_ID_alter
You can find the correct FORM_ID by looking at the HTML source of the form you're working with.  It's given inside the  tag.   Apparently you need to replace the hyphens with underscores.
The code might include something like this:

function hook_form_sublanding_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['promotion_settings'] = array(
    // something goes here....
  );
}

The code is very incomplete and quite possibly incorrect.  Perhaps someone will complete/correct it.


Recreating vocabulary and term pages by using views

try to create a views Taxonomy terms, add fields in this order: Taxonomy term: Term ID (Term ID) (enable Exclude from display, Thousands marker None), Taxonomy term: Name (uncheck "Link this field to its taxonomy term page" option, open "SHOW REWRITE RESULTS" fieldset, enable Output this field as a link, in Link path enter gallery/[tid]), this is solution for your PS.


The path 'public://admin/myfile.txt' is not a real path (because of the 'public://'-part, which is a drupal-custom), it's a stream-wrapper-path (see link at end of answer).

  file_exists() can only process real-paths and registered stream-wrapper-paths

This means for you: Either your Drupal-installation didn't register it's custom stream-wrapper or your server-isp deactivated the stream-wrappers on your server/account.

You should check your php-config for Filesystem and Streams Configuration Options:
http://www.php.net/manual/en/filesystem.configuration.php

More info on php's stream-wrappers:
http://www.php.net/manual/en/wrappers.php

BTW: Registering of custom stream-wrappers is supported by PHP 4.3.2+


How do views Contextual Filters behave with Pathauto?

You would get the node id(nid) as argument. Internally the system gets its data from the unaliased url, not the browser url created with path_auto.


views exposed filter on non existent field

The most obvious solution to me would be to get the month data into the date field, since you are treating the date to be 1/1 when no month is given, this would fit just fine; there is no reason to create a new field for this.

You should be able to do this in a form submission handler for the node edit form.


Why not just use a modified node add form? You can change it to have whatever fields and validation you want.


Permission to edit a node by multiple users

The best option is to install a node access module that allow the admin to:

Create access control lists (ACLs) to individual nodes; and
Add and remove individual users from an ACL.

The module named Flexi Access lets you do exactly that.

The Flexi Access module will provide a simple and flexible interface to the ACL (Access Control List) module. It will let you set up and mange ACLs naming individual users that are allowed access to a particular node.
The module let you manage access to individual nodes. The administrator may grant individual users the right to: View (read), update (edit/write), and delete the node.

It depends on the ACL module.  (It actually provides an administrative interface to ACL.)
Disclosure: I am one of the maintainers of Flexi Access.


How can I programmatically change the parse mode?

On Drupal 7, I've achieved this by using hook_views_pre_build() since this hook is executed before hook_views_pre_execute() and hook_search_api_views_query_alter(). Using code similar to the following will do the job.
$options = $view->display_handler->get_option('query');
$options['options']['parse_mode'] = 'TYPE_OF_PARSE_MODE';
$view->display_handler->set_option('query', $options);

Note that TYPE_OF_PARSE_MODE can be:

Direct query - direct
Single term - single
Multiple terms - terms


Encrypted Files module sounds like exactly what you're looking for. From the project page:

  Say you want users of your site to be able to upload and download documents, but you also want these documents to be protected in case someone breaks into your server. This module allows Drupal to encrypt files that users upload and decrypt files for download, keeping the unencrypted versions of files from ever being stored on disk. It does this by creating a custom file stream wrapper that Drupal can read from and write to and a new download method that sits alongside the regular public and private methods. So you can make Encrypted Files the default download method, or only use it as the download method for specific file-type fields.


I was wrong, 2.teintÃ©_60_380X448_2.png works, now I only have to write a script that converts all filenames to utf8, and use it as latin-1, great :/


You are looking for the DBTNG Migrator module.

  This module is a UI and Drush interface to replicate a database from one database to another independant of what kind of database server they are. So long as ther are support by Drupal, you can migrate to them, including non-SQL stuff!


You need to deselect "Verify HTML" in the configuration page for the input format using Wysiwyg. Those settings are available in admin/config/content/wysiwyg.

Once I disabled that option, I tried with the following HTML, and it worked.

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mp3">
  Your browser does not support the audio tag.
</audio>

With that option enabled, this is what I get right after entering the HTML with the HTML button.


How to get only parent term ids of a given term, without loading the terms

Have a look at taxonomy_get_parents() and taxonomy_get_parents_all().

You could copy most of the functions but skip

$parents[$tid] = taxonomy_term_load_multiple($tids);

to not load the terms.

/**
 * Load a terms parent.
 */
function MODULE_taxonomy_get_parents($tid) {
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.tid', $tid);
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    // $tids = $query->execute()->fetchCol();
    // $parents[$tid] = taxonomy_term_load_multiple($tids);
    $tids = $query->execute()->fetchAll();
    $parents[$tid] =  $tids;
  }

  return isset($parents[$tid]) ? $parents[$tid] : array();
}

/**
 * Load all parents for a term.
 */
function MODULE_taxonomy_get_parents_all($tid) {
  $cache = &drupal_static(__FUNCTION__, array());

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

  $parents = array();
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
    $n = 0;
    // while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
    while ($parent = MODULE_taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

  $cache[$tid] = $parents;

  return $parents;
}

If you don't need any access control or sorting you can just query the taxonomy_term_hierarchy table directly.

$query = db_select('taxonomy_term_hierarchy', 'h');
$query->addField('h', 'parent', tid);
$query->condition('tid', $tid);
$query->condition('parent', 0, '!=');
$tids = $query->execute()->fetchAll();
$parents[$tid] =  $tids;


How do I attach JS and CSS on Slick Views

Picking up from @leymannx (and copy/pasting from the linked answer) here's a more spelled-out solution:

You could use the template_preprocess_views_view() hook to do this:

function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'my_slick_view') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}


You want to add a filter and use "Date: Date (node)" not "Node: Date" for a CCK date field. Then, you can choose "Select" and granularity of "Year". Once you expose the filter, you will get a drop down list to choose a year to filter by. The paths will need to be arguments, as you've found out. But, they will work separately. If you want the drop-down to only work with those specific paths, I think you have to create your own select box.


How can I design a relationship between two types of users?

You can use the User Relationships module for that.

  Administrators are able create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.

I've used this module for one of my project. It works great!


How do I handle multiple arguments with `hook_drush_command()`?

In the 'official' make-me-a-sandwich command:

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

  // The 'make-me-a-sandwich' command
  $items['make-me-a-sandwich'] = array(
    'arguments' => array(
      'filling' => 'The type of the sandwich (turkey, cheese, etc.). Defaults to ascii.',
    ),
  );
}

Arguments is clearly an array. Add new keys to it.


Is there a way to create a Webform automatically via script using Drush or another method?

You can exactly do what you touched on with config: put a placeholder into the yaml for the URL and remove the uuid completely. As you import into a new site, that will generate a new one for you.


Change CSS rule for small screen with jQuery

Resolved.

if ($(this).hasClass('is-active')) {

doesn't allow to show menu links when no class is attached:

else {
          $('ul.menu').css('display', 'none');
        }

So, I modified checking for small screen:

 $(window).resize(function(){
        if ($(window).width() > 720 ){
          $('ul.menu').css('display', 'none');
        } else {
          $(this).toggleClass('is-active');
        }
      });


is your function called ?
put a drupal_set_message('hello'); in it to see.

remove these to lines, they're not needed

$vars['script'] = drupal_get_js();
$vars['styles'] = drupal_get_css();

then - you need to add some custom JS, where you tell which of your div should be modified:

drupal_add_js('jQuery(document).ready(function () { $("#logoParade").smoothDivScroll({
    autoScrollingMode: "always",
    autoScrollingDirection: "endlessLoopRight",
    autoScrollingStep: 1,
    autoScrollingInterval: 25
});

// Logo parade event handlers
$("#logoParade").bind("mouseover", function() {
    $(this).smoothDivScroll("stopAutoScrolling");
}).bind("mouseout", function() {
    $(this).smoothDivScroll("startAutoScrolling");
}); });', 'inline')

is this div already setup ?

else - add it in page.tpl.php or whereever you like to ..


Change commerce kickstart admin toolbar logo

Ho it was easy, just add a css class in your subtheme css with the class

body.toolbar #toolbar-home a span

from there you can change the background image


ok if you're looking at drupal 6 look into custom_url_rewrite_outbound(). For D7, you can use hook_url_outbound_alter().

Some example code I have sitting around in a module that takes media resources of a Drupal site and points the generated urls to another server to serve media content, we used Nginx. Keep in mind that if you're just sending back to same server on another port .... you're just feeding yourself more traffic -- which isn't as helpful as a true CDN.

 /*
 *
 * A mechanism in Drupal to rewrite outbound urls to point to another domain.
 * This can be used to serve static content from a dedicated server, aka a CDN.
 *
 * Taken 100% from the following url. I am not smart enough to pull off this
 * magic :).
 *
 * http://drupal4hu.com/node/260
 *
 * In the below code $conf['dew_cdn_domain'] is a custom value in
 * settings.php that points to like "http://yourotherserver.com" to serve
 * media files.
 */

/**
 * Implementation of hook_file_url_alter()
 *
 * This inspects and transforms file urls to our remote CDN host.
 */
function dew_cdn_file_url_alter(&$uri) {
  global $conf;
  static $drupal_static_fast;
  // A drupal_static_reset() would clear this and then we need to rerun variable_get.
  if (!isset($drupal_static_fast['dew_cdn_domain'])) {
    $drupal_static_fast['dew_cdn_domain'] = &drupal_static(__FUNCTION__);
    $drupal_static_fast['dew_cdn_domain'] = $conf['dew_cdn_domain'];
  }
  $cdn_domain = &$drupal_static_fast['dew_cdn_domain'];
  if ($cdn_domain && strpos($uri, ':') === FALSE) {
    $uri = $cdn_domain . $uri;
  }
}

/**
 * Implementation of hook_stream_wrappers_alter()
 */
function dew_cdn_stream_wrappers_alter(&$wrappers) {
  $wrappers['public']['class'] = 'DrupalCDNPublicStreamWrapper';
}

/**
 * Any files that would go the public stream public:// get rewritten to another
 * base domain.
 */
class DrupalCDNPublicStreamWrapper extends DrupalPublicStreamWrapper {
  function getExternalUrl() {
    global $conf;
    $path = str_replace('\\', '/', $this->getTarget());
    return $conf['dew_cdn_domain'] . self::getDirectoryPath() . '/' . drupal_encode_path($path);
  }
}


How do I create a page using Views and Drupal Commerce, where every listed term is a search term?

Assign taxonomy terms (e.g. Flomax) to products, then display those terms in your view. Clicking on a term displays the term's page, with all its associated products.


First of all the reply form and the comment form are the same forms (form_id: comment_node_NODE_TYPE_form), you shouldn't think they are different forms.

Second, you would need some custom coding in your own module, that would look like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function yourmodule_form_comment_form_alter(&$form, &$form_state, $form_id) {

OR, even more specific to comments on article nodes (you can replace article with page, blog, YOUR_CUSTOM_CONTENT_TYPE)

function yourmodule_form_comment_node_article_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['comment'])) {
    $comment = $form_state['comment'];
    // if this is a reply, hide the two fields
    if($comment->pid > 0) {
      $form['subject']['#access'] = FALSE;
      $form['author']['#access'] = FALSE;
    }
  }
}

Good luck!


It sounds to me like you are looking for something like Superfish or Nice Menus.

My personal preference is Superfish, as it has become pretty damn useful in recent updates. It's also responsive if that's a requirement, and support touchscreens quite nicely.

EDIT

Something I missed (possibly another personal preference) is that I find the CSS for Nice Menus an absolute NIGHTMARE in comparison with Superfish.


How to create sticky Social Media Tabs to the right of the website?

Try Social media module, it will display as block and then assign it to the proper region and AFAIK no module exist as such, you need to customize through CSS.

  The social media module helps integrate your website with social media
  sites such as Twitter, Facebook and Google+. It provides an
  centralized way of managing social media profile information and
  plug-in widgets such as follow and share buttons.

if you are looking to share the posts then Share Bar is the right choice for you.

  The Drupal Sharebar module lets you easily add a "floating" social
  media submission bar on your website (like that found on Mashable)
  that includes share buttons for the most popular social media websites
  online such as Facebook, Twitter, and Google +1 Buttons.


Tags are used to find services while building the container by so called compiler passes. They are not available during runtime of the container.

You can find the default compiler passes in CoreServiceProvider::register().

Usually, the tag related compiler passes all do the same thing. Find all services and add them to a service, so that when that service is instantiated, it has a list of service objects that it can do something with.

Thats why this has been abstracted with the service_collector tag, which tells it to pass all services with the tag to the provided method. That's done in TaggedHandlersPass::process()


You're going to want to understand the relationship between Organic Groups, Spaces, Context, Features and possibility the Persistent URL and Strongarm modules. Aside from Organic Groups, they were all created by the same developer who started Open Atrium.

Here is one very basic run-through about how Open Atrium works.

Here is a description of how each of those modules factor into the OA structure.

Be warned: I don't think I've seen a more complex site built with Drupal. Most of those modules are not only complex, but also genius.


How to set date format in drupal 8 for date time field?

In Drupal 8, the date format and time format are separated. The values for this has to be set separately.

I found this by creating new cck field in a content type and printing it from form alter.

$date_format = 'Y-m-d'; $time_format = 'H:i';

$form['start_date'] = [
      '#type' => 'datetime',
      '#title' => t('Start Date'),
      '#date_date_format' => $date_format,
      '#date_time_format' => $time_format,
      '#description' => date($date_format, time()),
      '#default_value' => Drupal\Core\Datetime\DrupalDateTime::createFromTimestamp(time())
    ];


How do I get the vote result in Vote API?

As you have installed the Rate module, then you can use the function rate_get_results(), which can be called as rate_get_results('node', $nid, $widget_id); $nid is the node ID of the node for which you want to get the result, and $widget_id is the identifier of the widget used to cast the vote.
The result is an array that contains many values (some of them are present only for a particular widget); in particular $output['rating'] is the rating, and $output['count'] is the number of the votes.
If the widget saves the sum of the votes, then $output['rating'] (where $output contains the result returned from rate_get_results('node', $nid, $widget_id)) contains the sum of the votes, which is what you are looking for.


Security issues while using external javascript and php files to access mysql database in drupal nodes

Doesn't look like any of the questions you have are directly related to Drupal. I highly suggest reading about PHP security concerns. This is a good resource to get started.

That said:

  Is this method secure?

Without looking at specific code, that is hard to say. Since you're running a database query based on user input, it's important you properly sanitize the input before running the query. I suggest using PDO instead of mysqli_* functions, since PDO is more widely used now and provides easy ways to use "prepared statements" to protect your database.

  Can some anonymous user access my .php script and get to know my mysql
  admin password? ( I use admin password during mysqli_connect() )

Not unless the .php script prints the password to the screen. Sounds like it accepts POST data and will return JSON output with data from the database. Make sure your POST data in sanitized before running a query.

  Can my whole database be exposed easily even though I always query a
  single table of the database?

See above

  Can the .php file be edited to update or delete parts of my database
  or the table in which I query every time?

Not unless a malicious user has access to your web server


Multistep user registration using profile2

You can try Field group

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Available group types

Fieldsets
Horizontal tabs
Vertical tabs
Accordions  Divs
Multipage steps: Note: This is only client side.

And i found a nice tut here


How to remove the containing "response" tag from GET output

Rest plugins always use the standard seralization methods, you can't really influence that for just your plugin. You could implement your own, like ?_format=my_fancy_xml.

Or, if you have very specific needs an an existing client that you need to work with, you can always just implement a normal controller and build the XML yourself and return it with a normal Response object.


How to highlight only unpublished nodes in views result

in your views add fields:

Node: Published, options "Label" empty, tick "Exclude from display",
"Output  format" choose "True/False"
Node: Title, option "Rewrite the output of this field" write [title]
Make css class ".false {color:red;}" for "unpublished" in your theme .css file

make 2 and 3 to your vbo fields, add "Node: Published", and rearrange to be first top field


Print message only if checkbox field is alter using form alter

You can use form_state instead of form in your submit handler and use default_value of check box in your form alter

$form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
    '#default_value' => 0,
   );

and then your submit handler will go like this

function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form_state['values']['checkbox'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form_state['values']['checkbox'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }

Use debug tools for proper index of form_state for checkbox.


How to i programatically change the page thats loaded from hook_init?

you can do somthing like this:

function MY_MODULE_init() {
    global $user;

    // or you can also use ip_address() function
    if($user->hostname == 'MY_BLOCKED_IP') {
      drupal_goto('node/NID_OF_IP_BLOCKED_NODE');
    }
  }

2-aproach (this is a recommended way. Because hook_init() will be removed from drupal v8):

// in template.php
function MY_THEME_preprocess_page(&$variables) {
  if($variables['user']->hostname == 'BLOCKED_IP') {
    drupal_goto('node/NID_OF_IP_BLOCKED_NODE');
  }
}


How to display different image on hover and content in pop-up?

The Beautytips module provides ballon-help style tooltips for any page element and you can also use it in views.

Currently i am using this module with views to display the text(for field) in bottom of my page , when mouse hover of image. For more information check this video

  It provides an API for adding custom beautytips as well as some
  built-in features. Admins can enable rollover balloon-help style
  tooltips for text fields within forms. It also supplies hover tips for
  Drupal help links and advanced help links.


Bootstrap 3 - parent nav element disabled

it took me ages but if you go to menu-link.func.php and take out line 33       $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';

works!!! took me like 3 weeks of reading :)


Loading a form from a form include file in a module

Module_load_include includes the file with extension and filename. Sinds your file is called example2.form.inc and you include the file example2.inc, it doesn't work.

You should be using

Module_load_include('inc', 'example2.form');


Users unable to view orders even with permissions set

Since you said the permissions are set right you can do a quick test for this using views;

Create a new view with "show" Orders and use the Filters(users) to check if you can find the orders of different users.


You can use form_set_value() in your validation handler. Let's say you are retrieving a user ID from a remote API, by sending the user's name. In your form definition, you can have:

$form['user'] = array (
  '#type' => 'textfield',
  '#title' => t('User to fetch'),
);

In your validation handler, you can retrieve the value. If a value exists you save it using form_set_value, and if it doesn't, you set an error:

$remote_user_id = retrieve_uid_from_api($form_state['values']['user']);
if($remote_user_id) {
  form_set_value($form['user'], $remote_user_id);
}
else {
  form_set_error('user', t('%user does not exist in the remote API', array('%user' => $form_state['values']['user']));
}

So in your submit function, `$form_state['values']['user'] will now contain the User ID from the remote API:

$remote_user_id = $form_state['values']['user'];


Can I set up Paypal recurring payments on Commerce Kickstart?

The only existing module-based solution is Commerce SP plus Commerce SP PayPal.

The latter is in dev at the moment, but I've found it to work pretty well, albeit with a few minor business-specific alterations.


Using wget to get the latest module version

The latest stable is published on an XML file, so your script would need to query and parse it to get the proper URL. http://updates.drupal.org/release-history/project-list/all this returns ALL the projects release history, obviously very large. You can get a specific project with this URL http://updates.drupal.org/release-history/views/7.x where "views" is the project name and "7.x" is the version.

Or you could just use DRUSH. It's super easy to install and will make your life 100x easier and better. Drush is a command line PHP script that allows you to simply type things like drush dl views or drush up views. It can do a lot more too, it's truly amazing. http://drupal.org/project/drush


Displaying a table from local menu (Drupal 7)

From a page callback you need to return something that can be run through the render() function. This will either need to be a string, or a properly formatted render array.

You can use:

$block = theme('table', $table);
return $block;

or

$block['content'] = array(
  '#markup' => theme('table', $table)
);
return $block;

or even

$block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
);

The last method is probably the most preferable in terms of extensibility, as it potentially allows other modules to alter the table before it's rendered. Using either of the other methods will render the table into an HTML string, and other elements in the system will no longer be able to alter it before it's displayed.


How do I redirect the unsubscribe link in a newsletter to a particular node?

Use the Rules module and use the Rules (System) Event "Drupal is initializing" (= init). And add an extra condition related to the URL of your unsubscribe link. Add to that a Rules Action to perform a redirect to your node/2.

Here is a rule that should be close to what you'd need (assuming the path of your unsubscribe link is Some/Unsubscribe/Path):

{ "rules_redirect_unsubscribe_link" : {
    "LABEL" : "Redirect unsubscribe link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Some\/Unsubscribe\/Path",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirecting URL [site:current-page:url] ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "node\/2" } }
    ]
  }
}

The above rule does not (yet) take into account to only apply the Rules Action for your "test user" (as in your question) only. But for anybody a bit familiar with the Rules module, that is a straight forward Rules Condition to add ...

And the above rule also uses a Regular Expression in its Rules Condition that could be simplified to a simplified version of it (not using such expression). However, if you have various unsubscribe links that all have a similar pattern, you only have to massage that expression in the above Rules Condition to have all such links fit in the same expression.

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if the Rules UI submodule is enabled). Then further edit/refine to make it fit in your own environment (e.g the "Redirecting URL ..." message to be shown).


This is an error saying you have a link to an non-existing resource.

You should use Webmaster Tools to dig deeper, if I remember correctly, it should provide the URL for the page with the bad link.


Change field requirements on validation?

The validation function in the Form API is meant to evaluate the user input and report the errors back to the user if any.

You could change your logic in this way to facilitate your implementation:
 - The field _field_title_tag_list_article_ is not required by default
 - In the validation function, you would check whether the value of a second field (i.e. _field_validate_titles_) is set to a given value (i.e. _field_validate_titles_ == 'needs validation').

It would look something like this:

if ($form_state['values']['field_validate_titles'] == 'needs validation' &&
  empty($form_state['values']['field_title_tag_list_article'])) {
  form_set_error('field_title_tag_list_article', t('The title tags are required.'));
}

You could download the Drupal Examples modules and install the _form_example_ module, then check the example number 6.

Advice for new users

In general, I suggest you browse the examples so that you are familiar with this handy reference.

Quite often, you will find that someone else had the same problem before. Sometimes, there is a community contributed module that solves your problem.

In your particular case, the conditional fields module could help you accomplish your goal without having to write a single line of code:

Conditional fields module page.
Conditional fields module documentation.


Check if the user has flagged content with any flag

The flag module has a utility function flag_get_flags() that retrieves multiple flags, with an option to filter on the entity type of the flag:
// Same logic, looped over multiple node flags:
$flags = flag_get_flags('node')
foreach ($flags as $flag_name => $flag) {
  if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
    print "This node is flagged";
  }
}


button for boolean field during node display

Maybe you should check out the Flag module. Out of the box this module will give you the boolean field, the ajax button on the node view, and rules integration.

The flag module integrates nicely with views. Here is some helpful documentation. http://drupal.org/documentation/modules/flag

You will no longer need the boolean field on your node though so, depending on existing content may require a migration.

It does have a very large user base too and it may save you some development.


Querying for user's whose birthday is today plus other OR conditions

If you want to filter in your efq, you'll have to compare strings:

   $today = new DateTime();
   $today = $today->format('Y-m-d\T00:00:00');

Then add in your query the condition

'field_date_of_birth_value', $today, '='

I can't tell more unless you show us your code.


Possibility to apply a patch to a target directory with Drush make?

After clarifying that the goal of the original question was to be able to use patches generated by pull requests on GitHub directly, I'm suggesting an alternative answer.  My original answer is correct if the goal is to package this on Drupal.org.  Because a drupal-org.make requires patches to be found on Drupal.org, the path can be updated in the patch to to target directories within the CiviCRM project.  drupal-org.make also requires all external projects to be whitelisted.  Only the sk (starterkit) build of CiviCRM is whitelisted (https://www.drupal.org/node/1588192) because of the size and licensing limits.

When using drush make locally, you can use both patches and code from any source.

  IIRC it was a bit more complicated than just combining the repos?

It really isn't more complicated than just combining the repos.  There is some additional logic in https://github.com/civicrm/civicrm-core/blob/master/tools/scripts/releaser/releaser and https://github.com/civicrm/civicrm-core/blob/master/distmaker/distmaker.sh, but you can really focus on what happens in...

https://github.com/civicrm/civicrm-core/blob/master/distmaker/dists/drupal_php5.sh

dm_install_core "$SRC" "$TRG"
dm_install_packages "$SRC/packages" "$TRG/packages"
dm_install_drupal "$SRC/drupal" "$TRG/drupal"

That combines https://github.com/civicrm/civicrm-core with https://github.com/civicrm/civicrm-drupal and https://github.com/civicrm/civicrm-packages.

Other than the versioning, that's really all that happens when a new release of CiviCRM is packaged.  There isn't any code for a D7 release that doesn't come from those 3 repos.  By adding each of these projects directly, the relative path of the code will match what the patch expects allowing the patch to be applied in the .make.

So to get something like https://github.com/civicrm/civicrm-drupal/pull/144.patch to work before it is merged into a release, your .make would look something like...

libraries[civicrm][download][type] = get
libraries[civicrm][download][url] = "https://github.com/civicrm/civicrm-core/archive/4.4.10.zip"
libraries[civicrm][destination] = "modules/"
libraries[civicrm][directory_name] = civicrm

libraries[civicrm-drupal][download][type] = get
libraries[civicrm-drupal][download][url] = "https://github.com/civicrm/civicrm-drupal/archive/7.x-4.5.4.zip"
libraries[civicrm-drupal][destination] = "modules/civicrm/"
libraries[civicrm-drupal][directory_name] = drupal
libraries[civicrm-drupal][patch][144] = https://github.com/civicrm/civicrm-drupal/pull/144.patch

libraries[civicrm-drupal][download][type] = get
libraries[civicrm-drupal][download][url] = "https://github.com/civicrm/civicrm-packages/archive/4.5.3.zip"
libraries[civicrm-drupal][destination] = "modules/civicrm/"
libraries[civicrm-drupal][directory_name] = packages


Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8()

To solve this issue I had to change this line  '#title' => filter_xss($dimension)['name'], to this On the line '#title' => filter_xss($dimension['name']),


How do I add "Update Status of User" action to a view?

If you have entity forms and rules, create an entity form with an entity reference to users, add another field for your preferred action, and use rules to perform the action.


Is it generally safe to add same Drupal javascript multiple times?

Usually, you add javascript with Drupal's behaviors as explain in the doc. If you have AJAX callbaks, javascript behaviors will be reloaded and this can cause some trouble.

For exemple, on my website I added moving clouds in the header with a javascript behavior, the speed beeing added by increments, each time I loaded an AJAX form it was sped up unintentionally. I could either add a jQuery Once behavior or use the common $(document).ready function.

So in conclusion, it depends on the way you call the code inside your javascript file. Your javascript code called inside a $(document).ready function should be loadded once, even with AJAX callbacks. On the contrary, a Drupal javascript behavior will be executed each time your DOM is updated, exept with jQuery Once enabled:

Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('input.mybehavior', context).once('mybehavior', function () {
      // Apply the MyBehaviour effect to the elements only once.
    });
  }
};

Now if you are concerned with others javascript coding standards, see the official Javascript coding standards.


Finding out the machine name of a field when using Views

Go to the settings page of a view, and click on "Theme information"; then you look at the IDs of each field.  For example, if "Theme information" shown this information, then "last_comment_name" would be your machine name.

  Field Node: Last comment author (ID: last_comment_name):


add users to og group via vbo doesn't work: record is deleted immediately

You might need to grant a OG role to the new member after adding them.

e.g. og_role_grant('node', $node_page->nid, $account->uid, 2);

The magic number on the end determines the type of role granted. 1 = non-member, 2 = member, 3 = administrator member


Show menu even if node it's not in that menu

In the settings for the menu item itself, there is a checkbox below "enabled" that says "expanded". Check this box for all items whose children you want to be visible all the time.


How do I redirect users to an external URL?

Define a controller and redirect to external URL.

Use TrustedRedirectResponse class in case you know that you want to redirect to an external URL. Example below:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');
  }
}


embed photo album hosted on flickr.com using flickr module not showing photo album

It's likely you have photos in that set that aren't available in the size you've set the photos to display in.

Flickr module documentation > Sizes

  TAKE CARE, the c (800px) size is missing on Flickr images uploaded before March 1, 2012. Check if it exists on the Flickr photo page > Actions > View all sizes.

More info and debug inspiration in the 7.x documentation: Flickr Editor Guide 7.x-1.7


List module releases that are "Recommended by the project’s maintainer."

As described in Update status XML, Drupal.org returns information about project releases, including the recommended major version, as XML output. For example, the first XML elements returned from https://updates.drupal.org/release-history/imagemagick/8.x are the following one.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<api_version>8.x</api_version>
<recommended_major>3</recommended_major>
<supported_majors>3</supported_majors>
<default_major>3</default_major>
<project_status>published</project_status>

<recommended_major>3</recommended_major> is referring to any version matching 8.x-3.*.
Unfortunately, that information isn't returned from https://updates.drupal.org/release-history/imagemagick/current or any URL matching https://updates.drupal.org/release-history/*/current.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<supported_branches>8.x-3.</supported_branches>
<project_status>published</project_status>
<link>https://www.drupal.org/project/imagemagick</link>


Fetch column sum from database and print the output using static/dynamic queries

The first error is caused from the fact that Drupal 7 doesn't define db_result() anymore; it was used from Drupal 6.

The second error is caused from $query->execute() returning an object of that class, which you cannot convert into a string (which is what you do when you try to print it). You should use code similar to the following code.

$query = db_select('table_name');
$query->addExpression('SUM(column_name)', 'total');
$result = $query->execute()->fetchField();


How to inspect a css file generated by Less?

There are extensions available for Firefox (sadly not for any other browsers that I can find).

There's the FireLess Plugin which is:

  a Firebug extension that makes Firebug display the Less filenames and line numbers of LessPHP-generated CSS styles rather than those of the generated CSS

Also, if you're able to switch to using SASS (which is quite similar), there's FireSass, which:

  allows Firebug to display the original Sass filename and line number of Sass-generated CSS styles.

There's nothing for Chrome at the moment (see Less/Sass debugging in Chrome Dev Tools/Firebug)


Install.php available after xcopy deployment

What the installer checks for, is whether or not the settings file has database information for the site.

While this sounds simple in theory, and shouldn't lead to install.php being executed, there are many components involved.

There's DNS, which may or may not respond to various sub-domains.
There's the webserver configuration, which may or may not serve sub-domains, and may or may not re-write them before they hit Drupal.
Drupal, since 7, supports a sites.php file which can map domains to sites/ directories.
Finally, there's the sites directory itself, where Drupal can find a settings.php file, check for a valid $db_url, and decide whether or not to allow installation.

Due to the many components, and the technical complexity of setting them all up right, it's very easy to end up in a situation where install.php decides to allow installation. This should generally not be a problem, as anonymous users should not be able to create new databases, but it looks quite wrong regardless.

While removing install.php is a solution, it's technically hacking core, and makes future deployments needlessly complicated.

I normally do two things to counteract this.

The first thing is to run the site from a directory named after the domain, such as sites/example.com/ and make sites/default a link to the main site. This way, any unexpected domains being requested by Drupal will be served by the main domain.

Second, I always just block access to install.php completely on any production systems with this vhost file:

# ssh -L 8080:127.0.0.1:80 example.com
<Location /install.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

<Location /update.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

This ensures apache blocks access to both install and update. The comment at the top is a reminder for how I can open an ssh tunnel to the server so my traffic looks like it's coming from 127.0.0.1, thus allowing developers access to run update.php.

Something similar in IIS below. Note that I have not tested this. Someone with ISS experience, please update or comment so I can improve this part.

<location path="install.php">
    <system.webServer>
        <security>
            <authorization>
                <remove users="*" roles="" verbs="" />
                <add accessType="Allow" roles="Administrators" />
            </authorization>
        </security>
    </system.webServer>
</location>


Form elements created with AJAX aren't sending values through form_state

Move all form building activities from the callback to the form build function.

The form elements you add in the callback go directly through javascript to the DOM in your browser. You see them as normal form elements, but the form API doesn't know that they are in your browser and will ignore them.

Edit for the questions in comments:

In the form build function you know that you are rebuilding because $form_state is filled with data. On the first run it is empty.

You have the number of columns in the value of the select element.

You should wait with handling of the configuration data until submit.

In general an ajax form should have the same code in form build as a normal form, because if jquery is not available, ajax will fallback to a normal rebuild.


How to create automatically a view of all nodes sharing the same field value?

Suggested method

I suggest looking into using the Search API (with Views) for this purpose.

From the Search API module page:

  This module integrates the Search API with the Views module, allowing searches on any index to be created and viewed via Views. All of an entity's properties, as well as those of related entities (e.g. a node's author's name), are available as fields, filters and arguments for all indexed fields are available and sorts (as well as click sorts) can be created on any indexed single-valued field. Also some additional features, like linking the results to the entity, are available.

Drupal.org uses this method to create Issue pages with links like: https://www.drupal.org/project/issues/search_api?text=&status=13&priorities=All&categories=All&version=All&component=All. You should be able to craft your links to the view integrated with the Search API using tokens.

Detailed Instructions

I was able to set this up in my testing with the following steps, which are detailed below.

Install the Search API and related modules
Set up a search server
Set up a search index
Set up a view of the search index
Create the links to the view with tokens

Install the Search API and related modules

Install and enable the Search API module. Also enable the Search views extension module that comes with the Search API.

Set up a search server

For my testing, I used the Search API Database Search module. This is a separate module in Drupal 7 but it is in the main Search API project for Drupal 8. From the module page:

  This module provides a backend for the Search API that uses a normal database to index data. It is therefore a cheap and simple alternative to backends like Solr, but can also be a great option for larger sites if you know what you're doing.

This search server set up may work for you, or you may need to configure a different service class for your search server. I think specific instructions on other options like Solr are out of the scope of this answer, but I recommend taking a look at the Service classes and features documentation page which lists various options and their features.

To use the Search API Database Search, install and enable the module. Then visit Configuration > Search and Metadata > Search API (admin/config/search/search_api) and click +Add server. Name your server, leave the Enabled checkbox checked, and choose the Database service as the Service class. Click Create server.

Set up an index

Visit Configuration > Search and Metadata > Search API (admin/config/search/search_api) and click +Add index. Name your index, choose the Item type, and restrict by Bundle (content type) if desired. I restricted to Nodes of type Article in my testing. You can leave the Bundles checkboxes blank if you want to include all content types. Choose the server you set up in the previous step as the Server. Click Create index.

Now, you will select the fields you want to add to the index. In my testing I added an Integer field to the Article content type, so I added both the integer field and the tags field to the index. Check the fields you want to add and click Save changes.

The next part of the configuration is the Filters settings. You can choose to add "Alterations" or "Processors" to the data in the index. Your choices here will depend on what kind of data you're indexing, each option has a description that will help you understand what it does. In my testing I chose to Exclude unpublished nodes under Alterations and I chose Ignore case under Processors. Click Save configuration.

At this point, you should click the View tab to see the Index status page and add items to your index. The Index status page is located at Configuration > Search and metadata > Search API > Edit (Your Index) (admin/config/search/search_api/index/INDEX_MACHINE_NAME). For testing purposes I suggest indexing in a small batch at first and clicking Index now.

Set up a view of the search index

Now, visit Structure > Views (admin/structure/views) and click Add a new view. Name your view and in the Show dropdown field choose Your Index. Click continue and edit.

In the view under Filter Criteria, add a filter for your each of your indexed fields (I know that will be a lot of fields in your specific case). I added one for the Integer field and one for the Tags taxonomy field. Make sure you click the "Expose this filter to visitors" checkbox for each filter. (You can also look into the Facet API for the facets option, however I think you would end up with a block for every field you wanted to put a facet on as opposed to one disabled block with a ton of filters you won't use. I think the Facet API method would also be worse for performance but I may be incorrect.)

Now you can visit the view page and adjust the exposed filters to get the URL structures you need to use with your tokens. Or, the pattern is: https://example.com/[VIEW_NAME]?[FIELD_MACHINE_NAME]=[FIELD_VALUE]

Change the Exposed form to a block

For your use case, it sounds like you just want the results from your links and not really a search page with filters or facets. So, once you've got your tokens and URLs working, in your view settings expand the Advanced section and change the Exposed form in block to Yes. This will put all the filters you've added to a block that must be manually enabled. The filtering in the URL will still work, users just won't see the exposed form with all the possible filters.

Set up your fields to be links with tokens in your content type

It sounds like you've already got the tokens in links part working on your nodes or your view of nodes. In my testing, I found you can exclude all link arguments except the one you're filtering with, and the view will display everything that matches that field regardless of the other filters.

So, instead of having to make a link this: https://example.com/test-view?field_integer_field=&other_field=&another_field=&field_tags=[TOKEN_VALUE]

Your link can just include the one relevant filter: https://example.com/test-view?field_tags=[FIELD_VALUE_TOKEN]


I've been digging through this code, and Feeds does not use Background Process.

It uses Job Scheduler

From FeedsSource.inc:

  /**
   * Background job helper. Starts a background job using Job Scheduler.
   *
   * Execute the first batch chunk of a background job on the current page load,
   * moves the rest of the job processing to a cron powered background job.
   *
   * Executing the first batch chunk is important, otherwise, when a user
   * submits a source for import or clearing, we will leave her without any
   * visual indicators of an ongoing job.
   *
   * @see FeedsSource::startImport().
   * @see FeedsSource::startClear().
   *
   * @param $method
   *   Method to execute on importer; one of 'import' or 'clear'.
   *
   * @throws Exception $e
   */
  protected function startBackgroundJob($method) {
    if (FEEDS_BATCH_COMPLETE != $this->$method()) {
      $job = array(
        'type' => $this->id,
        'id' => $this->feed_nid,
        'period' => 0,
        'periodic' => FALSE,
      );
      JobScheduler::get("feeds_source_{$method}")->set($job);
    }
  }

Job Scheduler in turn uses cron to complete jobs, so you're not really saving yourself anything if you are already calling this from cron.

The core Drupal Batch API uses AJAX to break up jobs into batches. You can't start a Batch API batch from cron. If you don't have JS and try to start a Batch with the core API, you'll still need to watch the progress bar move across the screen. If you abandon your browser during a batch, it will stop working.

Contrary to what the previously accepted answer above states, the core Batch API does not use cron

Background process is now a suite of modules, and it does now include a Batch API module. These are 2 separate modules, which are not related to the Job Schedule module. We can't refer to Background Job/Process as 1 thing. These are 2 unrelated modules.

The key differences are as follows:

Drupal Batch API uses your browser to make new requests to the server at regular intervals. This does not work from a cron job

Job Scheduler uses cron to call on a set of scheduled jobs during cron execution. There is a limit on how long the process can run during cron, so this is not ideal for long-running processes. It also is not good if you need your import to occur in a timely manner, when you have your cron job only running at night. Scheduling a new Job during cron is a bit backwards, since it might not be until the next cron run that the job is actually dispatched (depending on if your hook_cron() is called before or after job_scheduler_cron())

Background process / Background Batch uses server-side http requests to chain steps of a process together. This is ideal for long-running processes that need to be started immediately. You can also start a long-running process from hook_cron() with this module, and it will run until finished.

I know you probably don't need this information now, but I did when I found this page from Google.

The information provided in the previously accepted answer is incorrect, and led me down the wrong path.


Where do I find default value for contextual view filters?

You choose a field from that drop down, and the settings you are talking about come up for that field.

These settings are tied to each field, so you can set different fields to come from different sources with different responses if they're not there.


You need just to implement the hook_form_alter in a test module this way:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      dpm($form);
      break;
  }
}

where $form_id is form identifier (in the example code I captured the new taxonomy term entry form) which you can find through firebug.


Change the text on the message which is displayed after the user registration

Goto Admin -> Configuration -> Account Setting -> Change the messages.
OR
You can implement through Rules module.

Send mail after creating new user a/c

Usage :

Goto Admin -> Configuration -> Rule

Click on 'Add new  rule'

Enter Name & Select React on event : After Saving a new user a/c & SAVE

Click on Add Condition & select Send Mail.

Click on Data Selector button & Enter Data Selector : account:mail

Enter Subject & Message & Save


How to check if code is running inside simpletest?

In Drupal 7, drupal_http_request() use the following code to add an extra header, when tests are running.

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  $test_info = &$GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  }

In your module, similar code should work.

  $test_info = $GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    // Drupal is running tests.
  }

In Drupal 6, the following code is present in drupal_http_request().

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
    $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  }

The following code should work for a Drupal 6 module.

  global $db_prefix;

  if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix)) {
    // Drupal is running tests.
  }


Each item between the slash after the domain name of the website is called an argument. Take, for example, example.com/one/two/three/four/five -- in this case one is the first argument, two is the second argument, ect.. Drupal has a function that separates these arguments named arg() which takes an argument as a number. arg(1) when called while loading this example URL will always return 'one' while arg(5) will always return 'five'. This way context can be passed into all the modules in a consistent way. I just want to make sure you see arguments for what they are.

Here is why. You are creating a two separate pages for items that should be on the same page. Instead of creating pages you might consider blocks in views and place the many blocks on the same page. This way you can, for example, use taxonomy terms to tag content as IBM, Intel or Apple. Create a balance sheet and tag it IBM. Create another tag it Apple. Create an income statement and tag it IBM. Create another and tag it Apple.

Then create a basic page with a brief description of the IBM corporation and a logo using the path alias module to change the name of the URL to example.com/ibm. Then add the two views as blocks to the page. Each view will be called when the user goes to example.com/ibm and arg(1) will be ibm. Then you can use the arguments (in View 3 contextual filters) to use this argument to define the Taxonomy term to filter the information in the database with. In this case IBM. Now you might have 12 reports for IBM for each category going back 4 years. Views will pull them all and you can use a field of title that links to the node to have a link going to each one. Then you can also use the date filter to make sure that the most recent one is on top. Once the View block is created, Views will just load the other view using once again arg(1) to define the taxonomy term to find all the other reports information in the database.

Now there are more advanced ways to trigger which Views get called with modules like Context or Panels which are super high powered tools that focus on just this simple purpose.  You might be interested in the videos on Panels at Node One or the Mustard Seed Media video on the Context module.

(edit) To create a similar tabbed look like companies on the WSJ you can use either Quick Tabs for an ajax tabbed effect or creating a Views page and assigning it a Menu Tab for the menu item so that several tabs are found on the same page.


Page cache works on local dev but not on production

My guess is during your testing you're visiting the page for the first time which would result in a X-Drupal-Cache: MISS (As you'd expect)

And as you've got the max-age set to 1 day your browser has now cached that response so no matter how many page visits you do for the next day you'll always see the MISS for that page (Because your browsers not going back to your server to get a fresh response) So other future users/different browsers could potentially be getting a HIT response after you've now forced drupal to create its initial cache

I'm only guessing here as I haven't tried myself but would seem to make sense. You could test it out by opening the same page in a different browser after you've got the MISS on your first browser to see if that 2nd browser is now seeing HIT


Creating QuickTabs programmatically not working

Well, after some thinking and searching, I managed to solve my own question. All I needed was this:

$tabs = array(
   $tabs[] = array(
      'title'   => t('Tab one'),
      'type'    => 'node',
      'nid'     => '24',
      'weight'  => 0,
    ),
    $tabs[] = array(
      'title'   => t('Tab two'),
      'type'    => 'node',
      'nid'     => '23',
      'weight'  => 1,
    ),
);

// Configure the QuickTabs options
$quicktabs_options = array(
   'style'   => 'Bullets',
   'ajax'    => FALSE,
);

$quicktabs_name = 'dynamic_quicktabs_menu';
$quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
return $quicktabs;


What are bundles? Can we create custom bundles?

Bundles are an implementation of an entity type to which fields can be
  attached. You can consider bundles as subtypes of an entity. With
  content nodes, for example, you can generate subtypes like articles,
  blogs, or products. Not all entity types have bundles, however. For
  example, users do not have separate bundles or subtypes. With bundles,
  you can have as many subtypes as you want. Then, using the Field
  system, you can add additional fields to those bundles such as file
  download field for Articles and location fields for Users.

Read more here and a good article that i found. Hope it helps :-)


As always there is more than one way of doing things in Drupal.
I'll guess that one of the popular ways of solving this problem currently is with the Inline Entity Form module.
Once you have it installed you can go to the "Manage form display" of your Content type and choose the Inline entity form Simple or Complex for your Taxonomy ER field (Complex allows you to also add existing entities, not only create new ones on the fly). Adjust the settings to your needs.


How to programmatically populate a country field

I played around with this now for a little while. Seems all you need is the iso2 key to be set.

global $user;

$node = new stdClass();
$node->title = 'Lorem Ipsum';
$node->type = 'article';
node_object_prepare($node);

$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1;

// In the end this was it.
$node->field_country[LANGUAGE_NONE][] = [
  'iso2' => 'FR',
];

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

Apart from that you can use the Devel module to either dump variables like that

dpm($variables);

for example in a MYMODULE_preprocess_node() hook. After you filled out a node with a country field from the UI you can use that to check which values are set. Or you can checkout node values directly by appending /devel to a node path (http://example.com/node/42/devel). Although I must admit that what I got there as output was quite misleading. All that really was needed was the iso2 key.


Altering body text of a node before the page is rendered

Try this in mytheme_preprocess_node:

function mytheme_preprocess_node(&$vars) {
  // Collect / create / adjust new body content
  $new_body = 'xyz';
  // Assign to output
  $vars['content']['body'][0]['#markup'] = $new_body
}

After looking through the vars array a bit, I'm a little surprised at the amount of redundant data there.  There are a few different places where the body text is recorded, usually as an array.

Note that the node body will likely have a 'safe value' and a 'value'.  You'll probably want to use safe almost all the time, but it might be good to check on the filter type selected in $vars['body'][0]['format'] to select which of the body values you'll want to output and display.


How to make one field's appearance on form depend on another field

You are looking for Conditional Fields module.

Description on module page says -

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition.


create two different registration form with same fields without using profile2

Well you can make small form with 2 submit buttons (Register as A, Register as B) and post that data on register form, in this way you can hide it from url

OR

The other way which is more complicated, using ajax, when link is clicked and based on the clicked link you create the $form_state and set the flag then you call the register from using drupal_get_form and you pass the argument

OR

Just create boolean field in user, and put the option (Register as A, Register as B) and make it required to be listed in register from


n00b question, form callback and form_alter

hook_form_alter() has $form_id as an argument:

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

Which is:

  String representing the name of the form itself. Typically this is the name of the function that generated the form.

(emphasis mine)

To understand the "typically" in there, have a read through the docs for hook_forms() (chances are it won't apply to your situation, or if it does, you probably already know about it).

So, generally speaking, you can use:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYMODULE_some_form') {
    ...
  }
}

Or, the more specific hook_form_FORM_ID_alter(), which will only be invoked for that specific form:

function MYMODULE_form_MYMODULE_some_form_alter(&$form, &$form_state, $form_id) {
  ...
}


What are some benchmarks with Mysql vs MariaDB while on Drupal 7?

When you have applied full due diligence, the difference between MariaDB and MySQL should be virtually negligible. Why would I say this?

MariaDB has done some benchmarking with some settings that give all MySQL processes the same level playing field : See Sysbench OLTP: MySQL-5.6 vs. MariaDB-10.0.  In fact, here were the setting used in the benckmark.

[mysqld]
sql-mode="NO_ENGINE_SUBSTITUTION"
back_log=500
user=root
port=3306
max_connections=4096
max_connect_errors=5000
max_prepared_stmt_count=50000
table_cache=2048
transaction_isolation=REPEATABLE-READ
loose-skip-external-locking
innodb_status_file=0
innodb_data_file_path=ibdata1:200M:autoextend
innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=20M
innodb_log_file_size=650M
innodb_log_buffer_size=100M
innodb_support_xa=0
innodb_doublewrite=0
innodb_flush_log_at_trx_commit=0
query-cache-size=0
query-cache-type=0
symbolic-links=0
skip-grant-tables

Please note

the settings do not accommodate use of more read and write I/O threads.
double write buffer disabled, good for speed, bad for data consistency in case of a crash

The key to really deciding which version of MySQL to choose is to effectively tune all the versions  under test and then benchmarking with actual Drupal data. I would look into getting all MyISAM converted to InnoDB as much as possible (If you are using FULLTEXT indexes, you must go with MySQL 5.6).

Here are some of my past posts from the DBA StackExchange on what settings to look for when tuning InnoDB and why:

Jun 19, 2011 : How do I properly perform a MySQL bake-off?
Nov 24, 2011 : Why mysql 5.5 slower than 5.1 (linux,using mysqlslap)
Oct 05, 2011 : Query runs a long time in some newer MySQL versions


Different behaviour saving programatically vs UI

For anyone that might find this in the future, this is related to this issue:

http://drupal.org/node/1534356

Still trying to figure out a workaround for my scenario, but this is the cause.


Module to easily insert link to other content into textarea?

CKEditor with CKEditor Link does the trick.


drush language importing untranslated strings

The statuses flag is saying to export untranslated strings, so you are importing an empty file.
Or are there any steps you missed to describe?


Can a taxonomy term be loaded into an EntityMetadataWrapper?

Yes. Like so:

$term_w = entity_metadata_wrapper('taxonomy_term', taxonomy_term_load(TERM_ID));

The first parameter is the entity type ID. If you visit MODULE_NAME_entity_info(), you can see the key of the definition will match the ID you need to load it.


Change on/off values for existing boolean checkbox

Solution was to reexport into features field_base and field_instance proper labels, then to make sure field_config and field_instance_config blobs are properly updated. I used update hooks to resave the fields with proper info, I loaded them with field_info_field, set the required properties and the used field_update_field. Also field config from list_key must be changed to list_default.


Menu Link not translating correctly on initial creation through node form

I created a hook to set customized=1 which allowed the menu item to be translatable without editing it directly.

function epc_menu_insert_menu_link_insert($link){
    $link2 = menu_link_load($link['mlid']);
    $link2['customized'] = 1;
    menu_link_save($link2);
}


You can try template_preprocess_block(&$variables). There is a global $base_url variable. Create variable for block template:

function your_module_preprocess_block(&$variables){
  global $base_url;
  $variables['base_url'] = $base_url;

}

Now you can use {{base_url}} in twig template of your block.


Are you saying that the thumbnail images for file uploads aren't displaying (a broken image icon the browser)?

If so, depending on how you installed Drupal ... drupal (well your webserver) needs to own the /sites/default/files/styles directory, or else drupal cannot create thumbnails for preview on-the-fly.

This is a known Issue: theme_image_style_preview() and image_requirements() should check whether style directories are writable.


There won't be a definite answer to this question as this can be achieved in a lot of possible ways. Depending on your knowledge in drupal you could start with the built-in drupal taxonomy system that enables you to classify your content as needed (e.g. with a tree-like-hierarchy or even related terms). To build the menu you can try the taxonomy menu module or use Views to create this manually.

For a start i recommend reading through this overview: https://www.drupal.org/documentation/modules/taxonomy


Conceptual help needed for creating forms related to parent node

I would solve this a bit differently:

Programmatically create and validate the form "attendance" - sounds good.
I would create a separate database table and store the filled form data there. It should have node (and user) id fields to determine to which node (user) it is related to. The node id field or node and user id field combination should be unique so you can always get the right attendance data for the specific node/user. Optionally it could have a unique, auto-incremental attendance id as the primary key if more than one field would be needed otherwise (easier to create unique paths for every attendance). Then I'd also add either separate fields for every form field or one field for all the data (serialized) depending of the needs.
Add a link instead to a programmatically created path (example: attendance/1/pdf where 1 would be the unique id for the attendance). When the user goes to the page create the pdf from the attendance data that they can download/view.
Add a link to the attendance edit form page (example path: attendance/1/edit).

One more thing to note is to get the (view/edit) permissions right if there is a need for restrictions.

In case my solution idea doesn't fit too well with all the specific requirements I would just say that you should store data in the database not files.


This is not possible with just the formatter configuration, someone would need to create a "Link to file with entity label" formatter, which would also not be that complicated.

But you can do it quite easily directly in a media template, the name would be something like media--document--embed.html.twig and the content then looks like this:

  {{ name }}

I also included a target and noopener rel here, but that's of course up to you.


Routes != URLs, you can't translate a route, you only can translate URL aliases.
One route has only one path, which - through optional wildcards - could match more than one URL. Because no single part in your desired URLs is stable, you can't do this with one route. (And AFAIK the first /part/ of a route path must be constant too in Drupal, it cannot start with a wildcard.)
An URL alias is an optional, separate entity that matches an arbitrary URL to an existing route.
You either have to dynamically create/update URL aliases, or add new route only for the spanish translation. But it is allowed to reuse the same controller for multiple routes, so overhead would only be a single entry in a routing.yml file.


This is pretty much a Views theming task.  Hopefully you are familiar with either Firebug or Web Inspector for Chrome. Your "Image Postion Right" and "Image Postion Left" will have their own respective div classes so you can leverage / theme those CSS classes to get the image in the correct postion.

If you need something more powerful beyond this, you may also need to create a Custom Views Template. (In your View, you should see a link for "Theme:Information" -- it might be under "Advanced" if you are using Views 3 for Drupal 7.) Clicking on this will give you template suggestions. You may also need to use the Devel module's "Theme developer" to quickly find the field variable names.-- see this

You also did not say which version of Drupal you are using so there may be some specific things relative to your Drupal version that you will need to be aware of.

So basically as you can see there are multiple ways to do what you need but this should be a good overview and resource. Theming a View is an artform and can take a while to get the hang of but once you do, it's pretty cool.


This issue is related to drupal/boostrap theme. It doesn't occur with default drupal theme.
Replace methods in Attributes.cleanClass pass the identifier as a 3rd parameter isn't needed because string replacements in JS are chained.
https://www.drupal.org/project/bootstrap/issues/2969106


Checking for existence for a field on an an entity_metadata_wrapper

Simply call the PHP function isset():

$headshot = array();
if (isset($item_wrapper->field_contributor->field_contrib_headshot)) {
  $headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();
}

EntityStructureWrapper implements the __isset() function according the principe of Overloading.


How to extend duration of the the one time login link?

For Drupal 7: In your settings.php try adding this:

$conf['user_password_reset_timeout'] = '259200';


Update hook - is it possible to generate success or failure message on operation success?

In Drupal 7, hook_update_N() doesn't need to return anything to make Drupal understand the update was successful; it needs to throw an exception in case of failure, which is what the methods of DatabaseSchema, such as DatabaseSchema::addField(), already do. (Those methods are the ones behind functions like db_add_field().)

See any of the update hooks used by Drupal core as example. (I removed the code comments just to make the code shorter.)

function user_update_7010() {
  db_change_field('users', 'signature_format', 'signature_format', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the signature.',
  ));

  db_update('users')
    ->fields(array('signature_format' => NULL))
    ->condition('signature', '')
    ->condition('signature_format', 0)
    ->execute();

  $existing_formats = db_query("SELECT format FROM {filter_format}")->fetchCol();
  $default_format = variable_get('filter_default_format', 1);
  db_update('users')
    ->fields(array('signature_format' => $default_format))
    ->isNotNull('signature_format')
    ->condition('signature_format', $existing_formats, 'NOT IN')
    ->execute();
}

function node_update_7012() {
  if (variable_get('update_d6', FALSE)) {
    db_update('field_config')
      ->fields(array('translatable' => 0))
      ->condition('field_name', 'body')
      ->execute();

    foreach (array('field_data_body', 'field_revision_body') as $table) {
      db_update($table)
        ->fields(array('language' => LANGUAGE_NONE))
        ->execute();
    }

    node_type_cache_reset();
  }
}

The only reason for hook_update_N() to return a string is changing the message seen in the update page.

// user_update_7002
if ($sandbox['user_from'] == $sandbox['user_count']) {
  if ($sandbox['user_not_migrated'] > 0) {
    variable_set('empty_timezone_message', 1);
    drupal_set_message(format_string('Some user time zones have been emptied and need to be set to the correct values. Use the new time zone options to choose whether to remind users at login to set the correct time zone.', array('@config-url' => url('admin/config/regional/settings'))), 'warning');
  }
  return t('Migrated user time zones');
}

Reference

update_do_one()


I assume you are already using the Internationalization (i18n) module. i18n provides the Language Switcher block, which contains links to switch among all enabled languages. When the user chooses one of the links in it, he is redirected to the corresponding page rendered in the newly-selected language.

Note that the block is only shown if at least two languages are enabled and language negotiation is set to something other than None.


How to create an end date field in a hook_form_alter

there is no way to do it with the standard field widgets, you have to craft your own, the examples module may help you


Creating event lists using nodequeue, static pages and dynamic dates

Yup, adding my solution for the collective knowledge!

Created each location as an individual page (appropriately classified by taxonomy/etc. for site navigation)
Assigned the desired custom fields, most ended being display hidden
Created new content type, "itinerary-location-reference", using module "Reference" (for D7)
Within this content type, assigned custom fields for dates/visitor name/etc.
One of the custom fields needs to be a node reference
Referenced the location

This creates two nodes that are linked...one is the static location content, the other a node containing date/personal information. I then added this overall reference node to my nodequeues. Done.

I can see a few issues down the road regarding number of entries into the database, but apparently Drupal's good for a few million, so fingers crossed!


How to define positive AND negative depth on taxonomy filter in views' module?

I've done stuff like this (eg, World and nesting of regions in the world with heirarchical taxonomies).

Take a look at Taxonomy Edge. It provides view integrations to provide search filters for "Taxonomy edge: Parent term ID" and I believe "Taxonomy edge: Parent term has child term". I mean it adds some useful parent and child Views search filters (I dont believe it adds a single positive or negative search as you've described).


Migrating XML data with many-to-one relationships

I ended up not using the "plugin:migration" option because apparently it assumes one-to-one relationships. So instead, I added code to the 'author' plugin's prepareRow to rejected incoming duplicate authors. Then I added code to my 'book' plugin's prepareRow to retrieve the author entity ids from the database and add it to the book entity. I was hoping for a built-in solution in the migrate system but this will do.


Is it possible to create a view of Nodequeues

Excerpt from the Community Documentation of Nodequeue (about "Automatic Creation of Views"):

When configuring Nodequeue, you can opt to "Automatically create one view per queue" (you may wish to leave this off if you plan to create the views yourself).
The views created automatically cannot be deleted from the Views interface because they are implemented "in code". However, if you disable the auto-creation, then clear caches, these views will be removed.
It is highly recommended that you use the Views module to display your subqueues. However, if you choose not to, you can alternatively use a small PHP snippet.
To use nodequeue from Views (D7), add a 'relationship' to the queue, and typically set to 'require this relationship'. Optionally add 'nodequeue: Position' to match the preset queue order.


How to save in a different subfolders the attachments of my users?

In Drupal 7, the core File module and the Token module (https://drupal.org/project/token) will let you do this.

In the settings for your file field, specify a file directory using a user token. I recommend prefacing the token'd directory with users/ (or something) so that you can easily find all of these files separate from other files on the site.

For example to use the user ID as the directory, set the 'file directory' to

users/[user:uid]

You can see all the user-related tokens available to you on your site at admin/help/token.


Using Rules and Content access to restrict node access after date

A proposition:

Enable "Rules Sheduler" at /admin/modules.
Go to /admin/config/workflow/rules/components and create a component

Add new component:

Component plugin => Action set
"Continue"

Component plugin:

Specify the component name (e.g. Revoke node access component)

choose in the table:

Data type => Content
Label => Node:Component or Node or what you want
Machine name => node_component or node or what you want
Usage => Parameter
"Continue"

Add actions:

Select actions to add => Revoke access by role
Data selector: is set as node-component by default; this is the selector name you have specified in the table in the step above
In "Role-based access control settings" check roles you want to revoke access for view/edit/delete content
"Save"

Go to admin/config/workflow/rules and add new rule (Add new rule):

Add new rule:

specify the rule name (e.g. Revoke node access rule)
React on event => After saving new content
Restrict by type => optionally, choose a node type you want to apply this rule to
"Save"

Events:

(optionally) you may also add here "After updating existing content" event if the rule has to triggered on existing nodes

Conditions:

(optionally) add your additional conditions here

Actions:

Add action
Select the action to add => Schedule component evaluation
Component: Select yor component you have already created (Revoke node access component)
Continue
Scheduled evaluation date:
click the "Switch to data selection and specify" button and specify:

Data selector: node:created (or other date-based condition)
Add offset: optionally specfify an offset for the chosen data selector (e.g. 1 seconds)

Identifier: Specify an identifer ("A string used for identifying this task") which is visible (Rules) "Scheduler" (/admin/config/workflow/rules/schedule) and in "Recent log messages" (/admin/reports/dblog). You may use tokens/replacement patterns.
Node:Component:
Data selector => node
Save

What's this?

This solution triggers a rule after a new and/or existing node has been saved. The rule "schedules" the component with an action set - in our case, the action is to revoke node access to the checked user roles. After content has been added as new and or edited, the component revokes node access on nodes for specified roles as scheduled on cron run, e.g. adding new article now +1 sec makes it unaccessible (view/edit/delete) on next cron on > (node:created +1 sec).

Hint:

It is also possible to add Schedule component evaluation as an action into a component. For example: you want this rule to be triggered using node:changed date, so every time you edit a node, the date for the action "Revoke node access" will be moved forward (e.g: node is changed now => the rule triggers in 1 day (offset in component settings); the node will be changed tomorrow, so the rule will be trigerred on tomorrow date +1 day and so on).

You can import and test the component:

{ "rules_revoke_node_access_component" : {
    "LABEL" : "Revoke node access component",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "content_access_rules" ],
    "USES VARIABLES" : { "node_component" : { "label" : "Node:Component", "type" : "node" } },
    "ACTION SET" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node-component" ],
          "permissions" : { "value" : [
              "view:2",
              "view:1",
              "view:3",
              "view_own:2",
              "view_own:1",
              "view_own:3",
              "update:2",
              "update:1",
              "update:3",
              "update_own:2",
              "update_own:1",
              "update_own:3",
              "delete:2",
              "delete:1",
              "delete:3",
              "delete_own:2",
              "delete_own:1",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }

    }

You can import and test the rule:

{ "rules_revoke_node_access_rule" : {
    "LABEL" : "Revoke node access rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "DO" : [
      { "schedule" : {
          "component" : "rules_revoke_node_access_component",
          "date" : { "select" : "node:created", "date_offset" : { "value" : 1 } },
          "identifier" : "Revoke node access",
          "param_node_component" : [ "node" ]
        }
      }
    ]
  }
}