Get book bid to display at search results page

The book id bid is nothing more then the node id nid of the parent. Therefor if you have the bid, you still need to extract the title from the parent node.

$search_hit = $variables['result']['node']->nid; // The node id of the search result item
$node = node_load($search_hit); // Load the whole node whose search result we got
$parent_id = $node->book['bid']; // Extract the parent from the found node

$node2 = node_load($parent_id); // Load the parent node.
echo $node2->title; // This is the parent title.


I've had similar issues with this, but unfortunately there can be a number of causes. Here are some things to check:

Do you have any modules that utilise flash installed? There are some issues with certain versions of Flash player that show up on 64-bit versions of Windows with IE8. If uninstalling modules that use Flash fixes the issue, then at least you know more about the problem.
Do you have CSS optimisation/aggregation turned on? If yes, try turning it off, then see if IE8 still crashes. There is a bug of some sort in the Drupal CSS optimiser, that means that if a CSS page the site is requesting returns a 404 error, then turning aggregation on will crash IE8. If you can, load up the site in another browser and use developer tools (like Firebug, etc.) to see if any of the CSS files are not being loaded. It is probably a good idea to check this regardless of whether you have turned on CSS optimisation.
Do you have JavaScript optimisation/aggregation turned on? If yes, try the same steps above, but for your JS files. Sometimes complicated JavaScript files cause IE8 to crash too.

Since you say it's a new site, I'm guessing the problem might be related to #2. Best of luck.


Add prefix / suffix to field by using template_preprocess_field

to prefix a paragraph field, this needs to be put into mytheme.theme .

function mytheme_preprocess_paragraph(&$vars) {
  if (isset($vars['elements']['#paragraph']) && ($vars['elements']['#paragraph']->getType() == 'hp_dean')){
    //kint($vars);
    $vars['content']['field_hp_dean_title']['#prefix'] = '
';
    $vars['content']['field_hp_dean_more']['#suffix'] = '
';
  }
}

you can adjust this to your specific hook, like hook_preprocess_node and similar .


how do I change the number of nodes that the admin layout shows?

You could create a nodes view of all your nodes. Set the pager to whatever number of nodes you want to view, and put various exposed filters on the View to help you find the content you need.

You could also access your database directly. Depending on your hosting provider, you probably have access to some sort of database interface. PhpMyAdmin is very common. If you go to the nodes table, you can view as many nodes as you'd like and figure out the NID you need to pull up the node. Clunky, but it'll work.

There's an old doc page for Drupal 6 regarding this same issue, but based on some of the comments, I don't think it'll work for D7. Worth a shot, though.


How to render a Commerce pane programmatically?

Panes are forms. Run them through drupal_get_form but you'll need to pass in some extra options:

require_once drupal_get_path('module', $payment_pane['module']) . '/' . $payment_pane['file'];
$order = commerce_order_load($order_id);
$payment_form = drupal_get_form($payment_pane['callbacks']['checkout_form'], $payment_pane, $order);
$output = drupal_render($payment_form);


Why doesn't the pagination work for a comment type, but it works for the other one?

If you have more than one listing on a page, the pager ID for each needs to be different. This applies to views, but also comment lists.

The way to change this is under your content type's display settings (admin/structure/types/manage/MYTYPE/display). For the comment fields, click on the gear icon and you should see this configuration option:

So long as each comment type uses a different ID, the pagers should work independently of each other.


Drupal Commerce Change Order Weight at Checkout

You can use HOOK_commerce_fedex_rate_request_alter(&$request, $order) to alter the request before it goes out:
function MYMODULE_commerce_fedex_rate_request_alter(&$request, $order) {
    // Test this value and set it to whatever you'd like.
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Value'] = 1;
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Units'] = 'LBS';
}

Just test the value and update it if you want.


Also checkout http://drupal.org/sandbox/Fabianx/1184598 as this is adding a subquery to a view; which is exactly what your trying to do.


in hook_preprocess_node, how to tell if node is being edited?

hook_preprocess_node() doesn't get fired for node edit pages so you don't need to do any checks, you can just add your JS as normal.


Migrate addressfield: Call to a member function import() on a non-object in migrate/includes/migration.inc on line 696

I gave up with the Addressfield Migration Class and decided to do a db_insert -- and it worked!

Not only works, but because I register the insert in the prepare() function of class SchoolMigration (where I was already using db queries) it also rolls back!

<?php
/**
 * @file migrate_users.migrate.inc
 * Our own hook implementation.
 */

/**
 * Migration classes for migrating users and user fields
 *
 * see Migrate handbook: https://drupal.org/migrate
 * and http://www.verbosity.ca/working-drupals-migrate-module
*/

/* useful functions for debugging using drush migrate commands:
drush_print_r($row);
drush_print_r($this->destinationValues);
*/

/**
 * Implements hook_migrate_api()
 *
 * Returns 'api' => 2 for the 7.x-2.x branch of Migrate.
 * Registers the migration classes for the 7.x-2.6 branch of Migrate (including
 * 7.x-2.6+xx-dev).
 */

function migrate_users_migrate_api() {
  $api = array(
    'api' => 2,

    // Migrations can be organized into groups. The key used here will be the
    // machine name of the group, which can be used in Drush:
    //  drush migrate-import --group=MigrateMembers
    // The title is a required argument which is displayed for the group in the
    // UI. You may also have additional arguments for any other data which is
    // common to all migrations in the group.
    'groups' => array(
      'MigrateMembersGroup' => array(
        'title' => t('Import Member Users'),
      ),
    ),

    // Here we register the individual migrations. The keys (MigrateMembers_Step1,
    // etc.) are the machine names of the migrations, and the class_name
    // argument is required. The group_name is optional (defaulting to 'default')
    // but specifying it is a best practice.
    'migrations' => array(
      'MigrateMembers' => array(
        'class_name' => 'MigrateMembers',
        'group_name' => 'MigrateMembersGroup',
      ),
      'GraduationYear' => array(
        'class_name' => 'GraduationYearMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'School' => array(
        'class_name' => 'SchoolMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'SchoolID' => array(
        'class_name' => 'SchoolIDMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
    ),
  );
  return $api;
}

/**
* Abstract class as a base for all our migration classes
*/

abstract class MigrateMembers_Basic_Migration extends Migration {
  public function __construct($arguments) {
    // Always call the parent constructor first for basic setup
    parent::__construct($arguments);
    // Avoid known line ending issue: drupal.org/node/1705850
    ini_set('auto_detect_line_endings', TRUE);
  }
}

/**
* User-only migration
* (and creates $row (Row) with user id to key other tables in subsequent migration classes)
*
* The data file is assumed to be in
* sites/all/modules/migrate_users/data_sources/
* the columns in the csv must be in the same order left-to-right as the $columns array below
* every row in csv must have a unique id in the first column (can be ascending numbers, for example)
*/
class MigrateMembers extends MigrateMembers_Basic_Migration {

public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = t('Import an CSV-file (only "User Account"-fields)');
  $columns = array(
  // Format: ('Fieldname', t('Description'))
      0 => array('Row', t('Row number (must be unique)')),
      1 => array('Type', t('S = Student M = Member')),
      2 => array('Prefix', t('Mr. Mrs. etc')),
      3 => array('FirstName', t('First Name')),
      4 => array('MiddleName', t('MiddleName')),
      5 => array('LastName', t('Last Name')),
      6 => array('StaffNotes', t('Staff Notes')),
      7 => array('SchoolNameAffiliation', t('SchoolName Affiliation')),
      8 => array('ProfessionalAffiliation', t('Professional Affiliation ')),
      9 => array('AddressLine1', t('Address Line 1')),
      10 => array('AddressLine2', t('Address Line 2')),
      11 => array('City', t('City')),
      12 => array('State', t('State')),
      13 => array('ZipCode', t('Zip Code')),
      14 => array('Country', t('Country')),
      15 => array('TelephoneNumber', t('Telephone Number')),
      16 => array('EMAIL', t('Email')),
      17 => array('Birthday', t('Birthday')),
      18 => array('SchoolID', t('SchoolID')),
      19 => array('Descriptor', t('Descriptor')),
      20 => array('GraduationYear', t('Graduation Year')),
      21 => array('SchoolAffiliation', t('SchoolAffiliation')),
  );

  // TIP: delete ", array('header_rows' => 1)" in the next line, if the CSV-file has NO header-line
  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationUser();
  $this->map = new MigrateSQLMap($this->machineName,
  array('Row' => array( // this field is used to connect user to other tables
          'type' => 'varchar',
          'length' => 6,
          'not null' => TRUE,
          'description' => t('User\'s Member-ID') // description never used
        )
       ),
  MigrateDestinationUser::getKeySchema()
  );

  // Mapped fields

  $this->addFieldMapping('name', 'EMAIL')
    ->defaultValue('')
    ->description(t('Name (User Account)'));
  $this->addFieldMapping('mail', 'EMAIL')
    ->defaultValue('')
    ->description(t('Email address'));
  $this->addFieldMapping('init')
    ->defaultValue('')
    ->description(t('Email address used for initial user-account creation'));
  $this->addFieldMapping('pass', 'PASSWORD')
    ->defaultValue('asdf')
    ->description(t("User's password (plain text)"));
  $this->addFieldMapping('is_new')
    ->defaultValue(TRUE)
    ->description(t('Build the new user (0|1)'));
  $this->addFieldMapping('roles')
    ->defaultValue(6)
    ->description(6 . t(' = "member"'));
  $this->addFieldMapping('theme')
    ->defaultValue('')
    ->description(t("User's default theme"));
  $this->addFieldMapping('signature')
    ->defaultValue('')
    ->description(t("User's signature"));
  $this->addFieldMapping('signature_format')
    ->defaultValue('filtered_html')
    ->description(t('Which filter applies to this signature'));
  $this->addFieldMapping('created')
    ->defaultValue(time())
    ->description(t('unique timestamp of user creation date'));
  $this->addFieldMapping('access')
    ->defaultValue(0)
    ->description(t('unique timestamp for previous time user accessed the site'));
  $this->addFieldMapping('login')
    ->defaultValue(0)
    ->description(t('unique timestamp for user\'s last login'));
  $this->addFieldMapping('status')
    ->defaultValue(1)
    ->description(t('Whether the user is active(1) or blocked(0)'));
  $this->addFieldMapping('timezone')
    ->defaultValue(t('Europe/London')) // 'America/Los_Angeles', 'Europe/Berlin', 'UTC', ... from drupal.org/node/714214
    ->description(t("User's time zone"));
  $this->addFieldMapping('language')
    ->defaultValue(t('en')) // e.g.: 'en', 'fr', 'de', ...
    ->description(t("User's default language"));
  $this->addFieldMapping('picture')
    ->defaultValue(0)
    ->description(t('Avatar of the user'));

  // Other handlers
  if (module_exists('path')) {
    $this->addFieldMapping('path')
       ->defaultValue(NULL)
       ->description(t('Path alias'));
  }
  if (module_exists('pathauto')) {
    $this->addFieldMapping('pathauto')
    ->defaultValue(1)
    ->description(t('Perform aliasing (set to 0 to prevent alias generation during migration)'));
  }
  // Unmapped destination fields
  $this->addUnmigratedDestinations(array('role_names', 'data'));
  }
}

class GraduationYearMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = 'Add data to field_data_field_graduation_year';
  $this->dependencies = array('MigrateMembers');
  $table_name = 'field_data_field_graduation_year';

  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationTable($table_name);
  $this->map = new MigrateSQLMap($this->machineName,
    array('Row' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
       )
     ),
    MigrateDestinationTable::getKeySchema($table_name)
    );

  // Mapped fields
  // add uid from completed MigrateMembers migration
  $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
  $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

  // Insert Graduation Year value
  $this->addFieldMapping('field_graduation_year_value', 'SchoolAffiliation')->sourceMigration('MigrateMembers')
    ->defaultValue(date("Y"));

  // set some defaults from the schema
  $this->addFieldMapping('delta')
    ->defaultValue("0");
  $this->addFieldMapping('entity_type')
    ->defaultValue("user");
  $this->addFieldMapping('bundle')
    ->defaultValue("user");
  $this->addFieldMapping('language')
    ->defaultValue("und");

  $this->removeFieldMapping('path');
  $this->removeFieldMapping('pathauto');
  }
}

class SchoolMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_member_school';

    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_member_school';
    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
         )
       ),
      MigrateDestinationTable::getKeySchema($table_name)
      );

    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('field_member_school_tid', 'SchoolAffiliation')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');

  }

  public function prepareRow($row){
    // convert 3 letter codes to ISO 3166-1 standard 2 letter codes http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Current_codes
    // TODO:
    // 1 - check for full list of country codes in old data
    // 2 - many records with US addresses do not have a foreing country code, not the USA country code
    // 3 - What are INO SAF SWD?
    switch ($row->Country)
      {
        case 'AUS': // Austria
        $row->Country = "AT";
        break;
        case 'BEL': // Belgium
        $row->Country = "BE";
        break;
        [more mappings]
        default :
        $row->Country = "US";
        break;
      }

  }

  function prepare($entity, stdClass $row){

    // delete rows added by MigrateMembers
    $num_deleted1 = db_delete('field_data_field_member_school')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();
    $num_deleted2 = db_delete('field_data_field_user_address')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

      switch ($row->SchoolAffiliation)
      {
        case 'AR': // Arts
        $row->SchoolAffiliation = "91";
        break;
        [more mappings]
        default :
        $row->SchoolAffiliation = "NULL";
        break;
      }

    $this->destinationValues->field_member_school_tid = $row->SchoolAffiliation;

    $fields = array('entity_type' => 'user', 'bundle' => 'user', 'deleted' => 0, 'entity_id' => $this->destinationValues->entity_id, 'revision_id' => $this->destinationValues->entity_id, 'language' => 'und', 'delta' => 0, 'field_user_address_country' => $row->Country, 'field_user_address_administrative_area' => $row->State, 'field_user_address_sub_administrative_area' => '', 'field_user_address_locality' => $row->City, 'field_user_address_dependent_locality' => '', 'field_user_address_postal_code' => $row->ZipCode, 'field_user_address_thoroughfare' => $row->AddressLine1, 'field_user_address_premise' => $row->AddressLine2, 'field_user_address_sub_premise' => '', 'field_user_address_organisation_name' => '', 'field_user_address_name_line' => '', 'field_user_address_first_name' => $row->FirstName, 'field_user_address_last_name' => $row->LastName, 'field_user_address_data' => '');
    db_insert('field_data_field_user_address')->fields($fields)->execute();
  }
}

class SchoolIDMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_SchoolID';
    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_SchoolID';

    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
           )
         ),
        MigrateDestinationTable::getKeySchema($table_name)
      );

    // add uid from completed MigrateMembers migration
    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

    //this assignment does not find the SchoolID; it is set in prepare()
    //$this->addFieldMapping('field_SchoolID_value', 'SchoolID')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");
    $this->addFieldMapping('field_SchoolID_format')
      ->defaultValue("plain_text");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');
  }

  function prepare($entity, stdClass $row){
    // delete rows in table added by MigrateMembers
    $num_deleted = db_delete('field_data_field_SchoolID')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

    //
    if ($row->SchoolID) $this->destinationValues->field_SchoolID_value = $row->SchoolID;
    else $this->destinationValues->field_SchoolID_value = "NULL";
  }
}


How to change the title of submit button when someone register in mailchimp?

As mentioned, you'll want to use hook_form_alter(). You can check if the user has subscribed with mailchimp_is_subscribed() and change the submit button text accordingly.

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mailchimp_lists_user_subscribe_form_test') {
    global $user;
    // First parameter is the list id, which can be found here:
    // https://polkaspots.zendesk.com/hc/en-us/articles/201070513-Where-can-I-find-my-MailChimp-API-key-and-List-ID
    $form['submit']['#value'] = mailchimp_is_subscribed('123abc', $user->mail) ? t('Unregister') : t('Register');
  }
}


This is answered in this other question:

How to perform join with multiple columns using db_select?

  Calls to SelectQuery::join() (like-wise SelectQuery::leftJoin(),
  SelectQuery::innerJoin(), and SelectQuery::addJoin()) chain-able
  because those methods don't return a SelectQuery object, but the
  actual alias used for the join.


How to create a Views relationship using the Address Field module?

The country should be filtered by the current node's title

The better approach is to create Taxonomy Terms, so you can tag your nodes.

In admin/structure/taxonomy Add a vocabulary called Countries.

Then add a term reference field to your content type and select countries as your vocabulary, and use auto complete widget.

So all you have to is type the country name here and it will tag your node with that name.

In views, for contextual filter add Has taxonomy term ID

PS: You could use the Rules module to auto tag your nodes based on the Country field value.


Why didn't the Drush command bam-restore work?

First, I would have run drush up drupal, updates only Drupal core, no third party themes or modules. To do a restore, try drush archive-restore


Show "create new node" form with "my" and "user I followed" content in a single block

I have a content type. Let us say "articles". When a user wants to
  create an article, he will go to /node/add/article and it will show a
  form like it shows on stack exchange when go to /questions/ask.

Give whichever user you want to create the node, permission to do so /admin/people/permissions

What I want?

  I want to create a block which will show the "create new node" form
  as above

  my articles

You mean the articles of admin or of the user creating the form? If admin, create a view with articles and filter by user admin, or filter by currently logged in user.

  articles of the user I am following with follow(user) flag.

as above. I presume you are giving the user the ability to flag other users to follow somehow? So you could filter by a list of users that are being followed.

  "My" and "user followed" articles should be shown below the form. The
  form and articles should always be visible in the block.

  When user saves a new article, it should show in the list below
  without page refresh.

You would use ajax to achieve this. Check out 'exposed filters' in views and look for the option to 'use ajax'.

  The user should not be allowed to select text format. The admin should
  choose which text format to enable on this particular content type.

This is built in. There are permissions for, example, "Use the Filtered HTML text format" and in the settings for the content type, which text formats are available.

  Note: When user visits node/add/articles directly, he must not see the
  articles. He should only see the form to create a new node.

  I am sure I have explained it quite well. Let me know in case you have
  any questions.

There are multiple questions here, and ideally you would post some code and show what you have already done.


Login via REST fails (403 forbidden) if cookie set by Drupal is kept

Can authenticated users not use the login url anymore?

No they can't, it wouldn't make sense for them to be able to (you can't login if you're already logged in).

In practical terms, this is the routing entry for the login endpoint:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

As you can see from the requirements, the user cannot already be logged in to access the resource.


using hook_user() to capture user actions

hope you are trying for drupal 7, there are hook for login and logout, hook_user_login and hook_user_logout respectively. the user id available for logout hook so you can populate the data you want about user.


There's a module for that: the Context module is what you need.
You can do it with page-[type] via preprocess functions.


drupal_add_js best practice to include inline code or script file

They are both and the same. The fileparameter you have specified in your second example is the same as the first example as it's the default type.

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.

Source: drupal_add_js

If your question is about whether it's best practice to use inline or file then it depends on your requirements. If you need to load a JavaScript library or a large amount of JavaScript then I would use file type. If you are just loading say some tracking code, or a few lines of JavaScript then I would probably use inline as it's one less HTTP request.


You can set a lower limit than the default 5000 for the number of cache items that are stored in the page cache bin:

settings.php:

$settings['database_cache_max_rows']['bins']['page'] = 500;

See this change record: Database cache bins are now fixed size — no more unlimited growth


How to send an email from user email templates programmatically?

I have found the solution. Below is the method I followed.

I added the new email template to the user account settings form using the following code.

$form['custom_email_template'] = array(
    '#type' => 'fieldset',
    '#title' => t('Contributor Email on Miles recieved'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE,
    '#group' => 'email',
  );
  $form['custom_email_template']['user_mail_custom_email_template_subject'] = Array(
    '#type' => 'textfield',
    '#title' => 'Subject',
    '#default_value' => variable_get('user_mail_custom_email_template_subject'),
    '#maxlength' => 180,
  );
  $form['custom_email_template']['user_mail_custom_email_template_body'] = Array(
    '#type' => 'textarea',
    '#title' => 'Body',
    '#default_value' => variable_get('user_mail_custom_email_template_body'),
    '#rows' => 15,
  );

And then on the 2nd submit handler of the user account settings form I used the following code to save the email content in a drupal variable.

variable_set('user_mail_custom_email_template_subject', $form_state['values']['custom_email_template']['user_mail_custom_email_template_subject']);
variable_set('user_mail_custom_email_template_body', $form_state['values']['custom_email_template']['user_mail_custom_email_template_body']);

and then use the following code to get the content of the email template.

$body = variable_get('user_mail_custom_email_template_body');
$subject = variable_get('user_mail_custom_email_template_subject');

and used the str_replace() function to replace the tokens with the dynamic values.

Hope it will help someone.


Link it's node link to the node:body in views

In all seriousness, you could do this by first including the node:nid in your view and then rewriting node:body as a link to node/[nid] in the configuration.  What might happen with all the content of that body inside of that though is undetermined.  I would hope views would check_plain it or remove tags etc so that just text is linked but I've never done it to see.


How to create a block view that displays content one year ago from from the post date of the current node

Can Views Data Rnage be a useful module? There is another choice is Views Date Range Filter D6. You will have investigate both solution if they work for you.


Can I test code contained in module files?

Unit-testing procedural code
In principle, you can unit test procedural code just as easily as code that is in a class, but you can't really mock it. Therefore, whether your tested code is in a class doesn't matter so much as whether its dependencies are.
Even though procedural code cannot use dependency injection and has to access services via \Drupal::service(), you can put your mocks into a custom container and call \Drupal::setContainer():
$container = new ContainerBuilder();
// ... insert mocked services
\Drupal::setContainer($container);

That means if you call only class code like \Drupal::logger() or \Drupal\user\Entity\User::load() or even \Drupal::database(), you should be able to mock everything, load your .module file, then call all of the hooks and check that they return the correct values.
But if your code references procedural core constants or functions (eg REQUEST_TIME, db_query(), drupal_set_message(), watchdog_exception(), file_*(), user_load()) then those .inc/.module files must be included as well, along with any files used by that code. You'll quickly run into problems that way, as that code will assume it's running in a full Drupal instance. To test such code, a kernel test or functional (ie browser) test will likely be required.
Unit-testing Hooks
With hooks, there is an extra caveat for unit-testing: You are declaring a function that you expect to be called from elsewhere, and which often doesn't do much other than altering and returning arrays.
You can test that as a unit, but because the contract of that code is so vaguely defined, it generally won't tell you much. Most of the errors in such code will only be revealed by testing the results in a functional test.


I see.

Try this, create a view of fields of content type (ie: Articles)

In your view, under Advanced, RELATIONSHIPS, add taxonomy terms on node.

Now under FIELDS add a field, and now you should have access to the tax term fields now.


How do I allow editors to select a template with CkEditor?

I suggest you have a closer look at the widget API / the widget plugin for CKEditor. The widget API enables you to have something like 'templates' meaning predefined groups of elements inside the editor window.

"Widgets are special rich content units in that they are groups of elements which are treated as a single entity inside the editor."

http://docs.ckeditor.com/#!/guide/dev_widgets
At the end of that page there are links to further info about the Widget SDK and a step-by-step tutorial for creating your own widget ('mini-template').
I use the widgets plugin myself together with the SCALD module family and I must say I am still quite excited how very well these two play together.
If you 'just' want to add content templates however, you should probably download and install the Content Templates plugin for CKEditor.
From the download dialog window:

Extract the downloaded plugin .zip into the plugins folder of your CKEditor installation. Example:
http://example.com/ckeditor/plugins/templates
Enable the plugin by using the extraPlugins configuration setting. Example:
config.extraPlugins = 'templates';
Download and configure all its dependencies, too.
Add-on Dependencies: Dialog

The configuration setting can be found/added in config.js inside the ckeditor directory.


How can I get the entity ID after saving it?

Use $CustomerEntity->id(); after saving your entity.
$CustomerEntity = CustomerEntity::create([
  'customer_id' => $customer['id'],
  'customer_name' => $customer['name'],
  'address' => $customer['address'],
]);

$CustomerEntity->save();
$id = $CustomerEntity->id();


How to display a form in controller method

Thanks to Kevin's comment, I realised that I can just return the form AND still use the custom access check reference to a controller method:

mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _form: '\Drupal\add_performance\Form\myForm'
    _title: 'Add performance'
  requirements:
    _custom_access: '\Drupal\add_performance\Controller\mymoduleController::checkAccess'
  options:


If you are talking about the actual content then check out the replicate and the replicate ui modules. They allow you to duplicate any entity. Much more powerful than the node clone module which only supports nodes.

If you are talking about cloning the content type or product type then look at the bundle copy module.


try not passing that parameter at all
Here is an excerpt from the PayPal's Express Checkout Integration guide  about Shipping address:

Suppressing the Buyer's Shipping Address
You can suppress the display of the buyer's shipping address on the
PayPal pages. You might want to do this in these cases:

You are selling a product or service that does not require shipping.
You prefer to handle addresses completely on your own and do not want
to let buyers choose from their PayPal address book.

To suppress the display of the buyer's shipping address, set the NOSHIPPING parameter to 1
in the call to SetExpressCheckout. No shipping address displays
on Express Checkout pages.

Hope this helps.


Why can't I add another allowed file extension to a Drupal 7 image field?

The Image widget internally allows (and silently enforces post Drupal 6) the use of only the png, gif, jpg and/or jpeg extensions. So, while you can remove an extension from a field, eg, I have removed gif from most of my implementations to avoid anything animated, you can't add any to this list.  I would imagine this is because it in itself displays the image after being uploaded and didn't want to break any displays in older IE browsers in the actual form (plus, who knows how image styles would work on them as well :)


How to get the commerce subscription status for current user on particular product page?

I'm actually in thought of adding comment to your question, but my reputation count made me convert my comment to answer. (Yes, I'm a beginner!)

For your question:
You have multiple products in your page and there exists a distinct 'commerce sp time' per product. So, the process flow would be,

When an end user subscribes to a particular product:

Disable the subscribe button of that product (may be a video tutorial) and change its value to 'subscribed'.
Set a schedule for the user with respect to 'commerce sp time' of that product, to trigger a custom PHP code (probably, enabling the susbcription button of that product).

All my concern is, Is this useful?
I had already achieved this feat technically, so would you..


Allow user to pick a number with each taxonomy term

Typical Field Collection case.

Have fun !


pagination broken on custom theme's search system page

So i found out that a view on the search page had pagination and it caused a conflict with the search results pagination! I removed pagination in the View's configuration screen.

Removed the pagination of the pager settings.


How can I make changes to "people" page?

Easiest way to do this:
enable Administration Views, this would provide you with a view for "/people" page.

  Replaces administrative overview/listing pages with actual views for
  superior usability. Filter users by name, ban/blocked status, or user
  roles.

Use a filter setting boolean field to "true" or expose this filter to allow admins to filter people by "true" or "false"


Send email to webform submissions when new content is created

how about direct get data from database? If you add hidden field and the default value will be [current-page:query:sid]. Use php code to get the data. Example: $raw = db_query("SELECT AGE.data AS age FROM webform_submissions S
    LEFT JOIN webform_submitted_data A ON A.sid=S.sid AND A.cid=1
    LEFT JOIN webform_submitted_data AGE ON AGE.sid=A.sid AND AGE.cid=2
    where [current-page:query:sid] = A.sid)->fetchAll();

I dun know I have not tried to code yet. Hope its can help you.


In Views how to configure a contextual filter to exclude the node being viewed?

The problem I believe is the relationship. I assume the entity reference on each event points to the parent event, including that on the parent (recursive).

Get rid of the relationship. Set up two contextual filters, one on Content:Nid and the other on Content:field_parent.

On the configuration for the contextual filter on NID, set the default value to Content ID from URL, open up the 'More' settings, and select 'Exclude'.

For the contextual filter on field_parent, set the default value to PHP Code and use something like the following:

$node = menu_get_object();
return $node->field_parent['und'][0]['target_id'];

This will get the ID of the parent from the current node, and will require all nodes displayed to have the same parent. The exclusion of the current node from the list will work, and you will have a list of all other children related to the same parent.


You can create different views and filter the content types.


Did you check if your localhost is capable of sending e-mails? (probably not, mine for example can't send an email)


Multiple language node import with Feeds

There was a fantastic Solution not so long ago that addressed something similar.

I believe that the best thing to to would to be to split each node into two nodes (one in Language A, one in Language B) and import each one in a separate feeds import, and then use the SQL query in the above solution to link the translation. This way, each node can contain otherwise identical information about the same item, in its own language, and simply be displayed based upon which translation the user/viewer would prefer.

Let us know how you go with the SQL script and if you have any issues that you need help with!


Access denied at password reset page when logging in

Comment out the /* $cookie_domain = $_SERVER['HTTP_HOST']; */ from settings.php from the path \sites\defaults will work for you.

or else use the below code in settings.php:

<?php
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
$cookie_domain = '.your_domain.com';
$conf['https'] = TRUE;
?>

On sites with anonymous users, it is handy not to set this so that you login as admin on one tab and anonymous on another by not using "www" on one of them.

source


How to upload file from a custom module?

If you upload a file, it stores the file temporarily in file_managed table in database.And you have to set the file permanent status 1 to save it permanently else it will be deleted from the table by cron after some time.
This sample code to load a image and save it to database might help you to understand.

/* Fetch the array of the image file stored temporarily in database */
$image = $form_state->getValue ('image');

/* Load the object of the image file by it's fid */
$file = File::load ($image[0]);

/* Set the status flag permanent of the image file object */
$file->setPermanent();

/* Save the file in database ( "managed_file" table) */
$file->save();

when you select any file from 'managed_file' field type, drupal make a entry in 'file_managed' table, you just have to set the permanent flag as above to decide whether you have to save it permanently or not.


How do I clear cache using an SQL query?

Yes, you can simply clear (TRUNCATE) all cache* tables.

This worked well for me:

TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

If you use drush, run drush sql-cli and paste the above in there.

These commands might not clear all cache tables of your specific site but it can help fix some errors. Afterwards you can try drush cc all to clear the rest.


Running "composer update" leads to errors with coder

What worked is the following commands

rm composer.lock
rm vendor -rf
composer clear-cache
composer require --dev drupal/coder
composer update

with last command perhaps not needed as the previous composer command does an implicit update


How to output Get Locations coordinates as a separate field?

Check out the geofield module. Even the Get Locations module supports it.


How do I get Drupal to recognize my 404 page override?

Have you check this link http://example.com/admin/config/system/site-information.
Visit the above link in your site and set the 404 error page for your site.


How to send email invite user fill in webform automatically?

There are a handful of different modules that can let you do bulk emailing (e.g. VBO, Mass Contact, Email Campaigns, etc.), but using Drupal as a batch email client I think only make sense in the context of:

Having regularly visiting user base, with pre-existing accounts.
Needing to contact a relatively small number of people (e.g. hundreds, or very low-thousands).

Your 4th requirement suggests that you'll be supplying any number arbitrary emails for the sake of feedback/lead gathering.

In lieu of a module or Rules (which only make sense in the context of some workflow built into the site), I'd suggest some 3rd-party email service (e.g. Constant Contact, MailChimp, etc.) to accomplish items #1-4.
Any decent 3rd party email service should give you a templating system with substitutable tokens that will let you customize your webform link if you need it to have pre-filled data (e.g. email, name, attended seminar, etc.) and a means to bulk submit email/contact info.

As far as item #5, there's a number of different way to accomplish this. One way is the Forward module which provides a share via email link/form for any node type.


How to add placeholder to all Drupal 7 text forms in node page?

I take it by wanting a Placeholder that the text is going to be removed by javaScript when the use enters text ?

If so, there are a couple of modules for that, for example :
https://www.drupal.org/project/field_placeholder

This will give you an extra setting in the field setting form so you wont have to use your description, allowing it to be used for the description.


How do I alter a database schema defined from another module?

hook_schema_alter() was not used for adding fields to the schema, it was used for reporting alterations to the schema by your module. This was so that functions such as drupal_get_schema() knew the alterations you had made. These functions have all been removed from Drupal 8 however, so there is no need to report your changes in hook_schema_alter().

You can add fields to another schema using:

\Drupal::service('database')->schema()->addField()

Documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Schema.php/function/Schema%3A%3AaddField/8.2.x


How to check if (unmanaged) file exists?

You could just use the old bog standard PHP function file_exists() if I understand you right:

$uri = 'public://images/an-image.jpg';
if (file_exists($uri)) {
  // Do something
}

This also works for normal (absolute) paths as well, e.g.:

$path = '/var/www/drupal/sites/default/files/images/an-image.jpg';
if (file_exists($path)) {
  // Do something
}


It was a permission issue on the content type.


How to choose between classic SQL query and Drupal 8 technic?

Finally, this worked:

$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }


Using Drupal Commerce, how do you render the "add to cart" button?

The product reference itself renders as the button. In your product display content type, make sure the product reference has the "Add to Cart form" format, then render it thus:

<?php print render($content['field_product']); ?>


How to prevent the results from being truncated?

You can simply add a new view mode for search results:

Go to admin/structure/types/manage/page/display (where "page" is your content type)
Expand the Show Custom display settings fieldset
Check Search index

Click Save
Go to admin/structure/types/manage/page/display/search_index (again, where "page" is your content type)

My advice would be to use download the Display Suite module (and enable the Display Suite module and Display Suite UI module) for extra fields and more options. No custom theming or coding required!


I have not come across such a scenario. However, here's a fairly simple method to achieve it:

Install the Entity Reference module
Add an Entity Reference field to the content type of this node by navigating to Structure > Content Type > [the content type of these nodes] > Manage Fields
Choose the Target type as 'Node' & choose the same content type as the 'bundle'
Label this field as 'Revision of' (say)
Now, you can either choose to manually enter the 'nid' of the original node here or run a query in the database to fill this entity reference field with the nid of the original node.
For example, lets say the content type is 'test' & the entity reference field is 'field_revision_of'

6.a. Write an insert query like this:
   insert into 'field_data_field_revision_of' set entity_type = 'node',bundle='test',deleted=0,entity_id = [nid of revision node],revision_id = [nid of revision node],language='und',delta=0,field_revision_of_target_id=[nid of original node];

6.b. Since you should also update the database revision table of a field:
 insert into 'field_revision_field_revision_of' set entity_type = 'node',bundle='test',deleted=0,entity_id = [nid of revision node],revision_id = [nid of revision node],language='und',delta=0,field_revision_of_target_id=[nid of original node];

Let me know if this helps.

Regards,

Supriya Rajgopal


Drupal 7 comments spam with Captcha installed

"to prevent the attacks" - not much can be done here. If an attempt to access node/add page ends with access denied page, its ok. You cant prevent users from entering urls in their browsers.

As for spam in comments, try some different modules for Captcha (Google reCaptcha with noCaptcha for example).
For different aproach, Honeypot can help limiting "robots" behavior.


With respect to your original post, I ran into this exact issue here in drupalsixlandia and resolved it with a dull ax inside of views.  By exact meaning I wanted to have a select list of bands created by a user presented to them when they wanted to add an album, but when an admin went in to add/edit things, s/he should see all of the bands on the system.

So, I created a view and used this view to populate the band Node Reference field in the album type in CCK.

I called it my_band and it filters on published bands and returns the Node Title of the band as the field. It has one argument, or in D7 a contextual filter, User Uid and in action to take if argument not present I provide a default argument via PHP code:

global $user;

if (in_array('super user', array_values($user->roles))) {
  return -1;
} else {
  return $user->uid;
}

Then in the Validation of that argument, I again use PHP:

if ($argument == -1) {
  return FALSE;
} else {
  return TRUE;
}

with display all values if validation fails.

So, now what happens (here at least) is if a casual user wants to create an album, s/he is presented with a list of only the bands s/he has created.  But, if any user with the super user role wants to create or edit an album, the validation is forced to fail, and the argument is ignored and all bands in the system are returned.

Perhaps with some D7ing of the code above this might work for you.


user_register_form not give pre filled form

You are trying to hack user registration instead of extending the feature in a right way.

If your requirement is additional validations on user registration form try using hook_form_alter.

More about hooks here.


View Template Override that is full page

If you want views template not to be wrapped in html.tpl.php, page.tpl.php and any other template whatsoever, I would susggest to do the following:

function YOUR_MODULE_menu(){
    $items = array();
    $items['path/you/want/your/view/to/be/available/at'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => 'View without wrapping templates',
        'page callback' => 'your_function_name',
        'access callback' => TRUE,
    );
    return $items;
}

function your_function_name() {
    print views_embed_view('your_view_name', 'your_display_name');
    exit;
}


Notifications from Workbench included content type

You can do this with the Rules module: http://drupal.org/project/rules

It should be pretty straightforward, once you figure out how to use Rules. (You can find some video tutorials here: http://drupalize.me/videos/basics-rules-link)

Basically, you are going to create a rule that is triggered when a node's workbench moderation state changes. When the rule runs, it will send an email. In that email, you should be able to include tokens (http://drupal.org/project/token) that will be specific to the node that was just changed.

Hope that helps.


Inline css is not working in ck editor full html

This is just an example where you can add inline class to P tag. Similarly you can do this with other tags. Refer CKEditor documentation

In the "Advanced Content Filter" section of CKEditor profile add this:

P [*]

In the "Advanced options" section of CKEditor profile add this:

config.allowedContent = true;

This did the trick for me.


file or image migrate from drupal 6 to drupal 7 using Migrate D2D module?

In your migrate register function define the files table migration.

/**
 * Migrate files table
 */
// The description and the migration machine name are also required arguments,
// which will be unique for each migration you register.
$file_arguments = $common_arguments + array(
  'description' => t('Migration of files from Drupal 6'),
  'machine_name' => 'Files',
  'source_dir' => '/var/www/drupal6/files/xxxx/',
);

// We just use the migrate_d2d D6 migration class as-is.
Migration::registerMigration('DrupalFile6Migration', $file_arguments['machine_name'],
$file_arguments);

Then in your node migration class set the files migration as the source.

// Map the image field to the new image field, base this on the Files migration
// to map the files to the imported files table.
$this->addFieldMapping('field_image', 'field_image')
  ->sourceMigration('Files');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

Hope that helps


How can I append date and time to node titles?

This will do for you

function modulename_node_presave($node) {
      if($node->type == 'node_type_machine_name') {
        $new_date = date("DMY_hms", time());
        $node->title = $node->title."_".$new_date;
      }
}


How to trim the beginning of a field (reverse trim)?

The right way would be to write your own view field plugin.

The quick way is as follows:
I assume your text field is the main body field.
Install views_php. In your view hide the text field. Add a Global PHP field. Make sure it is after the text field. In its output code put the following:

<?php print substr($data->field_body[0]['rendered']['#markup'], 100);?>

In Rewrite Results strip out HTML tags. As you are truncating text you will run into problems with unmatched tags, so you have to do this. Also, this sanitises the text. If you do not do this you have to run check_markup in the php.

Also, this is not the preferred way to output a field. The correct way is to use field_view_field.

And if your field is anything other than the body, then install devel module, and include this PHP snippet in the output code of the PHP field.

<?php print dsm($data);?>

This will help with getting the right field.


You might be looking for the #attributes property that you can add to forms and form elements. See example below

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
   $form['fbuser'] = array(
      '#type' => 'item',
      '#markup' => 'You have a facebook account?',
      '#weight' => -10,
      '#attributes' => array('class' => array('my-class-1')),
    );
   $form['login_link'] = array(
      '#type' => 'item',
      '#markup' => '
',
      '#weight' => -6,
      '#attributes' => array('class' => array('my-class-2')),
    );
   }


Generate image style from existing one instead of original image

Instead try to do this job you can  have the same result with create another image style and apply sequential this means first apply 1000x700 then 100x100.
I think you don't consider that  in one image style we can multi image effect.

I suggest you for better understanding image style  read this article


How to get a user's profile picture URL?

The code is OK, but you have to check if the field is not empty:

if ($user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())) {
  if (!$user->user_picture->isEmpty()) {
    $picture = $user->user_picture->view('large')
  }
  else {
    $picture = // get default picture
  }
}

In Drupal 8 don't use render service. The new template system does this automatically.


Use entity relationship to exclude records on view

You should be able to add a contextual filter, negated, that uses the relationship that you want.


Form error messages appearing in the middle of the form

This is actually due to the way the checkout module has been written (and is in line with recommended best practices for checkout form submission). The idea is to place the actual error message as close to the form element that generated it to reduce confusion in correcting errors on the form. There is no simple way to undo this behavior in the checkout module.

However, the fact that these are appearing halfway down the page is a good thing - what you really need to do is figure out what it is about your CSS that's causing the messages to float weirdly relative to your form elements.


Programmatically attach image to a content type from local system folder

You can just use file_copy or file_move.

Here is an example: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7


That seems dangerous to me - a node's bundle is fundamental to its identity, and has repercussions well beyond the node's data itself. You're on Drupal 7, presumably? Simple way to test would be a script like:

$node = node_load(5);
$node->type = 'other_type';
node_save($node);

If it breaks there, it'll break with migration too. And if it works there, it should work with migration.


How to add a file lock to all existing files in directory

To add a file_lock usage record for all existing files without one:

INSERT INTO file_usage (fid, module, `type`, id, `count`)
SELECT fid, 'file_lock' module, 'module' `type`, 0 id, 1 `count`
FROM file_managed
WHERE status AND NOT EXISTS (
  SELECT id FROM file_usage
  WHERE file_managed.fid = file_usage.fid
        AND `type`='module'
        AND id=0
        AND `module` = 'file_lock'
        AND `count`>0
);

To add a file_lock record for all files in a directory that are NOT registered in the file_managed table

Here I loop through all likely image files in and write them as public:// file_managed records if none exists.

preg_ls is not PHP/Drupal core - nicked it from PHP comment - v useful!
I exclude the styles/ directory which stores the variants made by different
image styles. I also exclude the images/backup/ directory - this is
particular to my needs, but I left the code in as you'll likely have
something to exclude too.
This assumes you have no private:// files and that everything under sites/default/files is to be a public:// file. do not run this as it is if you use private files at all!
It also assumes that on file_save, file_lock will add its own lock (based on your config for file_lock).

And now the code:

$dir = DRUPAL_ROOT . "/sites/default/files/";
foreach (preg_ls($dir, true, '/\.(jpe?g|gif|png|bmp)$/i') as $_) {

  $_ = substr($_, strlen($dir));
  if (preg_match('@^(styles/|images/backup/)@', $_)) {
    continue;
  }

  $uri = "public://$_";
  if (!db_query("SELECT fid FROM {file_managed} WHERE uri = :uri",[':uri' => $uri])->rowCount()) {
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}


How to get the string value from the function CountryManager::getStandardList()?

To fetch the string value from the translatable markup object use type casting:

$li[$key] = (string) $value;


Your module ships with a default config; it gets installed. Now your config has the default value; if someone overrides it, it doesn't have one anymore. $config->get('foo') doesn't have a default value.


If you want to maintain data integrity, there's not much you can do to speed the process up except upgrade your server's hardware.

user_delete calls user_delete_multiple, and it has plenty to do for each record;
 not just deleting the user record, it deletes fields/data, invokes hooks, clears caches, etc. All of that needs to happen or you're likely to find problems further down the line.

If you're finding that the slowdown is causing the script to timeout, you can process the list with the Batch API and solve that at least.

Incidentally, if you don't care about data integrity, you can just cherry pick the lines from user_delete_multiple that you do need, and execute those directly instead.


The $form array contains a #node key which has the nid attribute. Use that to filter like so:

if($form['#node']->nid == 1072) { ... }

However, since you ask for page-node-1072 it sounds like you want to put something in that particular page template, in which case you should use a process or preprocess function to add or alter variables for the template.


How can I a revert an overridden template to its default in a sub theme?

I don't know if there is a perfect solution to do that without any inconvenient. Here are two proposals :

Altering the Theme Registry :
To prevent the base theme from overriding a specific template, an idea would be to alter the theme registry. The theme registry array is keyed by theme hook name, and contains informations returned from hook_theme().
As Clive suggested above, you can achieve this by implementing hook_theme_registry_alter(). Here an example of how to revert theme overrides to preserve the original "node" template :
function example_theme_registry_alter(&$registry) {
  // Default template file path we want to use (relative to the Drupal root directory).
  $default = 'modules/node';

  // In Drupal 6, we can retrieve default template path in 'theme paths' array. The 1st key should
  // contain it, however 3rd party code might already have altered the registry...
  // $default = $registry['node']['theme paths'][0]; -> should be 'modules/node'

  // Reassign the template file path and theme path accordingly.
  $registry['node']['path'] = $default;
  $registry['node']['theme path'] = $default;

  // Reassign the name of the template file if needed (could have been overriden too).
  $registry['node']['template'] = 'node';

  // You may also need to unset some preprocess functions to protect template variables as well.
  unset ($registry['node']['preprocess functions'][11], ... , ... );
}

This hook is executed as the theme cache is rebuilt, you will need to clear it to see the changes.
This solution still "allows for overrides" on the module/theme level. However, since this code will always hook after modules and themes, you will probably need to bypass it every time you expect a change (e.g. brought by a new overriding template), just to be sure that what you see is what you expect, and to know which theme do what in the rendered page. So, if allowing module/subtheme overrides while preventing base theme overrides is required, you may want to try the 2nd solution.

Bypassing specific theme overrides :
This is not the clean way but according to your needs and how specific it is, you may prefer to directly "tweak" your base theme :

Templates : prevent override by renaming the theme template file : in the node example, one would rename node.tpl.php to bypass.node.tpl.php (or whatever).
Preprocessing : comment out preprocess functions in the base theme's template.php, e.g: themename_preprocess_node()
CSS, JS, ... : depending on how well your theme is structured, it can be easy or simply horribly boring to comment out the "overriding" part in these files.

The inconvenient here is that you'll have to redo these 3 steps every time you update or change the base theme, but until such a case happens, this will make it easier for modules and subthemes to manage overrides without messing with the theme registry.


commerce kickstart - how to edit a view ? the link is missing

It is available if you enable the "Contextual Links" module.


If folders don't exist in URI path, file_save_data() fails

I Noticed Similar issue while saving files using

 file_save_data();

In Drupal 8.

First I gave only first level directory to save the file as

$file = file_save_data($object->vertex_data, 'public://vertex_data.txt', FILE_EXISTS_REPLACE);

This worked fine.

But when I tried saving the file inside a subfolder as

$file = file_save_data($object->vertex_data, 'public://objects/vertex_data.txt', FILE_EXISTS_REPLACE);

it gave me the following Error :

File temporary://fileh1Gpl2 could not be moved/copied because the destination directory public://objects/ is not configured correctly.

The Solution for this is simple. Just use file_prepare_directory();

$directory = 'public://objects/'
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file = file_save_data($object->vertex_data,  $directory . 'vertex_data.txt', FILE_EXISTS_REPLACE);

This, first creates the folder if it does not exists and then proceeds to save the respective file.


Getting started with the Form API and Ajax framework

There is a module for submitting forms with Ajax.

  Provides AJAX comments to Drupal sites. Features:

  Makes AJAX submits
  Allows replies to comments on the actual thread page
  AJAX comments deleting
  Works with CAPTCHA
  Cool jQuery sliding


AFAIK you should use 2 spaces to indent your YAML. It seems you either use 4 spaces or a tab.

That is the case for the libraries files as well as the libraries key in info file.


In my experience, Profiler Builder has problem with modules, that are not full projects on drupal.org. I tried to use a module, that is hosted in GIT repository and the output was similar to yours. But it worked fine with drush generate-makefile, where generated output was like:

projects[svg][type] = "module"
projects[svg][download][type] = "git"
projects[svg][download][url] = "http://git.drupal.org/sandbox/josegaert/1511596.git"
projects[svg][download][branch] = "7.x-1.x-dev"
projects[svg][download][revision] = "04db94c4dc2bf5c8c9a2a0da5452c4a79d26d863"

I created an issue for Profiler Builder describing this at https://www.drupal.org/node/2479185. You may also want to look at https://www.drupal.org/project/make_local


Uncaught TypeError: $(...).dialog is not a function: How do I include dialog?

Drupal does not assign "$" to jQuery. That is because there may be libraries, which want to do something different with "$".

So you have to do this yourself:

(function ($) {
$( "#sponsor_dialog" ).dialog({
      autoOpen: false,
      height: 'auto',
      width:  520, resizable: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });

    $( "#sponsor_opener" ).click(function() {
      $( "#sponsor_dialog" ).dialog( "open" );
    });
})(jQuery);


If the only validation you are looking for is to make sure the fields are required, then you don't need to call to a validation function. The solution in that case will be to set the "required" attribute to TRUE for the fields description and keywords in the "form_alter" function. This solution will give you the style you are looking for in the required fields.

Something like this (this is a proof of concept):

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    // Make META DESCRIPTION required
    $form['metatags']['description'] = array('#require' => TRUE,);

    // Make META KEYWORDS required
    $form['metatags']['keywords'] = array('#require' => TRUE,);
  }
}

To get the right field names do the following:

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {

   print_r($form);

  }
}


How can I build an FAQ Page with sections?

As an alternative to the FAQ Field module, you may want to use the Views Accordion module instead (for which an official release for D8 is already available), and its related Community documentation.

By "grouping fields", the group header can be used as accordion header. In your case, just use your "Sections" (like General, Printing, Binding) as those grouping fields. Obviously, you'd have to have a regular field (like a select list field) to actually indicate for each question in your FAQ what the actual Section for it should be.

With this approach, you have the full power of Views available to make your FAQ look like you'd want it to look.


Fatal Error - Fatal error: Unsupported operand types in public_html/includes/common.inc on line 2999

You need to access the installation's database.

Find the 'block_custom' table. This contains all custom blocks.
Browse the records and locate the one which creates the problem.
Clear the field 'body' which should contain your custom PHP code.


How do I add client-side form validation to a Drupal form?

I'm biased since i created http://drupal.org/project/clientside_validation, but it is using http://bassistance.de/jquery-plugins/jquery-plugin-validation/ to do all validations, the benefit of the module is that you don't have to write any code


The common and very accepted way is to use a module and do everything from the UI:

I used Flexslider and it's a great module - If I remember correctly, you can use it's field display-option directly, without using Views. An "Instant" slider alternative could be the module "Content glider", but I'm not sure if it's responsive (the word responsive doesn't come up in the modules' page) so Better try the Flexslider field set first.

For better performance in slider image-replacement (and in general) you could try turning on Caching and Aggregation, and use modules like AvgAgg, Boost, and some others, it's a whole subject.


As leymannx and Kevin mention it is probably a misconfigured tmp/files directory

Uncheck aggregate css is something that you would not want on your live site as the performance will suffer.

Check in Reports > status report (/admin/reports/status) and try to fix or report on the errors that you see.

Also go into configuration > media > file system (/admin/config/media/file-system) and correct any file system problems reported when saving the settings.

The most probable cause of what you are seeing is wrong permissions.

There is a lot of guides on the net about setting those permissions.
You can start from the official guide on the subject or on one support thread that started as a drupal 7 thread but has Drupal 8 answers.


How to update non-property value with entity_metadata_wrapper?

The payload column is a property of the commerce payment transaction type already (property is a Drupal core term for any base fields on an entity), but for whatever reason the authors of the module have chosen not to expose it to the Entity API module through commerce_payment_entity_property_info().

Fortunately you can just use hook_entity_property_info_alter() in a custom module to provide the metadata on its behalf. See hook_entity_property_info() for details of the options available.


Can we automate scheduled published/Unpublished nodes in drupal 8?

The Scheduler module has it's own cron: http://example.com/en/admin/config/content/scheduler/cron, so you can configure any granularity you need


Allowing Automatic Logins from a Range of IP Addresses

IP Login

This module allows users to login automatically via their IP (v4)
address ranges or wildcards instead of having to enter a username and
password - plus many other features.


Disable registration functionality for sub-domain in Drupal 7

According to this answer on SO (to a 'similar' question posted 'a bit before' this question ...), this is a possible answer to this question (= quote from that question):

= = = Start = = =

As far as I know you can have different variables per domain (Because the Registration option is a variable) using the latest Domain Access module (currently 7.x-3.11 from 2014-Mar-02). It can be done with a submodule named Domain Settings. Enable it if haven't done yet.

If for any reason does not work for you I would suggest to use the Domain Variable module to handle variables for each domain.

= = = Stop = = =


One node for every referenced node in views

You can also use View Field View module and create a view named Content View in which you may have:

Fields

Content: Title

Sort criteria

Content: Post date: Sort ascending or Sort descending

Filter criteria

Content: Type (or anything else to filter only certain posts)

Pager

Use pager: Display a specified number of items | 1 items

Contextual filters

Content: Author uid

Now create another page view or a block view (whatever you want) named User View

Relationships

Content: Author

Fields

User: title
Global: View (in this field select the view: Content View)

User View passes arguments in every raw to the Content View and thus it filters content by user id.


Are absolute paths allowed in info files?

_system_rebuild_module_data is responsible for that. There is a whole section in code just to make sure:

// Prefix stylesheets and scripts with module path.
$path = dirname($module->uri);
if (isset($module->info ['stylesheets'])) {
  $module->info ['stylesheets'] = _system_info_add_path($module->info ['stylesheets'], $path);
}
if (isset($module->info ['scripts'])) {
  $module->info ['scripts'] = _system_info_add_path($module->info ['scripts'], $path);
}

My guess is that module should never assume that something exists if module itself does not install it. It's a way to introduce errors. Also, allowing modules to reach outside their directory might be a security breach.

If you need a script you can't include in your module, use Libraries API. Of course there are other ways, but most of them is problematic, and fixing all problems would pretty much result in cloning this ready module anyway.


Drupal Search API facet block not listing all indexed fields

Turns out that I had a limit on the number of items to display.

To fix it, I had to change the limit under Facet > Display.


Drupal Google Translate Module - Must be represented in the url

The only module I know of with a Drupal 7 version is GTranslate.

  GTranslate uses Google power to translate your web page. With 58 available languages your site will be available to more than 98% of internet users.

  Hides "Suggest better translation" pop-up
  Hides Google top frame after translation
  Mouse over effect
  Analytics feature
  Flags combined in one file to load faster
  Option to open translated page in new window
  Available styles Dropdown/Flags/flags with dropdown
  Valid XHTML
  Google Translate Element on your site (Google Default translation method)
  Ability to use SEF URLs and edit translations with Pro version

The module is used from 2250 sites, and 1216 of those are using Drupal 7.

As for the comment written by monymirza, The Google TOS once contained the following paragraph:

  5.3 You agree not to access (or attempt to access) any of the Services by any means other than through the interface that is provided by Google, unless you have been specifically allowed to do so in a separate agreement with Google. You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers) and shall ensure that you comply with the instructions set out in any robots.txt file present on the Services.

The actual version of the Google TOS says:

  Don't misuse our Services. For example, don't interfere with our Services or try to access them using a method other than the interface and the instructions that we provide. You may use our Services only as permitted by law, including applicable export and re-export control laws and regulations. We may suspend or stop providing our Services to you if you do not comply with our terms or policies or if we are investigating suspected misconduct.

I am not sure what they mean by interface. It could mean you can only access the service through the user interface provided by the browser.


Problem with Google Analytics module: "undefined index"

This is a support request on Drupal.org for this here.

Since it is not really a bug or feature request though it is technically on topic here so the summary of that issue is:

Make sure that you have run update.php.
If that didn't fix the problem then try re-saving your google analytics settings (it would be a good idea to confirm that they are what they should be before saving).

Also I would recommend that if you get error messages like that to search google and the drupal.org issue queue for the module(s) in question.


Using migrate module to import to a list_boolean field

See this comment on this issue:
https://www.drupal.org/node/1729996#comment-9511751

"I found a way to import, you must set the "on" and "off" values.

I went to my field in my content type and set the "on" value to 1 and
the "off" value to 0.

In the migration mapping I made a callback function for this field and
convert my true value to 1 and the false value to 0, you could do this
instead creating a new feature.

This way worked perfectly here.

I don't know if it is a really necessary feature."


Please check ReadMoreControl module, this might help you..By this module you can add Read more links to other supported view modes


You could add a theme preprocess function for blocks to add some logic pushing variables into your block template. You can then check against those variables to output the title as a link etc.

THEMENAME_preprocess_block(&$vars) {
 //logic here to add variables
}


Programmatically change placeholder text of form input

I was able to add the placeholder text by entering

    $userform['name']['#attributes']['placeholder'] = t('Username');
    $userform['pass']['#attributes']['placeholder'] = t('Password');

After looking at the results of die(print_r($userform)); more closely I saw that the username input was called 'name', and password was 'pass'


How would I store a reference in a custom FieldType in Drupal 8?

So you're actually asking two questions.

Should I use a field type or a relation?

Both works. Field type requires much less storage (everything is in the field table), but it's hardcoded to one specific use case. The alternative is basically https://www.drupal.org/project/relation or you could also use something like https://www.drupal.org/project/paragraphs, https://www.drupal.org/project/field_collection if you only have a source -> target reference (relation can to n-n references). For all, you'd create a relation/paragraph/collection type with your additional fields. More flexible, can be configured and doesn't require custom code, but each  reference is another entity that has to be stored and loaded.

You will have to decide what's better for your case, depends on performance vs. flexibility requirements, how many variations (you probably don't want to create 10 field types..) and so on.

If a field type, how do I create it.

That's actually fairly easy in Drupal 8. You just extend from the default entity reference field type (EntityReferenceItem), override methods like schema() and propertyDefinitions() to define what properties you have and how they are stored. Then you write a widget and formatter for it, extending from the widget/formatter that's closest to what you want (e.g. autocomplete or select for the reference selection).

The advantage is, all the actual reference things will just work through the parent classes, you just have to implement your additional properties.


An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function

The above issue was occuring due to conflict with other module Ajax Screen Lock
Disabling it solves the problem.


Where is the documentation for core associative arrays?

Render arrays are defined (in Drupal 7) with the hook_element_info hook.

To see what attributes a render element can accept you can check the MODULE_element_info function that defined it.

For example looking at system_element_info we can see that the page render element accepts a #show_messages attribute and that it contains a boolean value.

For more information you can also look for the template_preprocess_ELEMENT function for the element.

template_preprocess_page in our example.


Reoccurring weekly billing that only a user can see, based on a schedule in another node

I will suggest using these modules:
https://drupal.org/project/nodeaccess (to restrict node access per role or per user)
https://drupal.org/project/elysia_cron (flexible cron jobs)

Create separate cron job with flexible schedule where you can put all you custom logic with related nodes.


Drupal 7, Is there a module that detects file structure changes?

There is quite a few:

https://drupal.org/project/md5check (7.x.1.0 - actively maintained)
https://drupal.org/project/hacked (7.x.2.0-beta -seeking new maintainer)
https://drupal.org/project/sentry_server (6.x.1.x-dev -  seeking co-maintainer)
https://drupal.org/project/file_integrity (abandoned)

I've included those abandoned and seeking new maintainers, in case you want to revive them or use them as starting points for your own project.

However, as noted by Clive, this is easier to set up and maintain outsite of Drupal.  Here  is a broad outline of what you need:

First, recursively run through every file and sub-folder on the server within the current directory of the script and generate a file containong the "master" hash for each.  Repeat this whenever you update your site by installing new modules, etc. or updating old ones.

Create a script (in your favourite scripting language) to do the following, and activate it with cron at regular intervals. Make sure that it is not remorely executable (store it outside the web root).

Load configuration file (list of files to exclude from scan, etc.)
Recursively run through every file and sub-folder on the server within the current directory of the script.
Generate a hash for each file and compare with the master hash
Alert (e.g. by email) if different.

Based on: How to detect if your webserver is hacked and get alerted. They also have a script (WebsiteCDS) that does this taht you can download.  I haven't used it, and can't vouch for the quality of their code.


Instantiating Fields: via UI, API or Drush?

You can use Features to export your UI-created field configurations and version control the result. It's much faster to create and modify field instances in the UI unless you're extremely familiar with the Field API. I used to create fields programmatically but I feel like my time would have been better spent using the UI and occasionally exporting with Features for VCS/simpletesting.


Setting custom block.html.twig templates in preprocess function (not based on twig naming scheme)

I managed to get it working by using

function mytheme_theme($existing,$type,$theme,$path){
        return [
                'wide_grid_block' => [
                        'path' => drupal_get_path('theme','mytheme').'/templates',
                        'template' => 'wide-grid-block',
        'render element' => 'elements',
        'preprocess functions' => ['template_preprocess','template_preprocess_block','comment_preprocess_block','mytheme_preprocess_block'],
                ],
        ];
}

function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
if($variables['elements']['#configuration']['id'] == 'page_title' || $variables['elements']['#configuration']['id'] == 'product_selector'){
        $suggestions[] = 'wide_grid_block';
}


Delete content in a user registration field after X number of days

Are you sure this is the right way to proceed?
I think it would be better if you use a custom field with 2 properties: the registration code and a timestamp which holds the time until the value is valid.

And every time when you want to use the value, you check the timestamp. Also with this version you could easily set up a cron or advancedqueue job to delete old values.


7 - Display translated content using Flexslider Views Slideshow

Your problem might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


phpunit test: drupalGet a public node returns 404

BrowserTestBase do not run against your installation, they do a new installation and then run against that.

There is no content, no modules, pretty much nothing there by default, everything you need to need to create and install.

If you're looking for a way to run tests against your installation, you might be able to override the set up and tear down process. Or look at using behat: http://behat-drupal-extension.readthedocs.io/en/latest/intro.html


The technique you need is easy, the full details can be complicated (depending on exactly what you want the JS to do). You can attach a custom JavaScript file from without your module in three steps:

Create the JS file.
Define a library.
Attach the library to the form element.

The JavaScript should typically live in a folder named js at the root of your module: js/my-great-jscode.js.

To create your library add a [module_name].libraries.yml file to the root of your custom module.  In there define the library:

my-library:
  version: 1.x
  js:
    js/my-great-jscode.js: {}

Then to attach the code to your form element you add #attached => library to the render array.

$the_textarea=array(
  '#type' => 'textarea',
  '#required' => FALSE,
  '#ajax' => array (
  // Function to call when event on form element triggered.
  'callback' => array($this->componentCallbackObject,$this->componentCallbackFunction),
  'event' => $this->componentEvent,
  ),
  '#attached' => [
    'library' => [
      'my-module/my-library',
    ],
  ],
);

There is more detail in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module on Drupal.org


How to import a display mode configuration from a custom module

Features may help you solve this problem - https://www.drupal.org/project/features . If you have Features enabled, and the module include a mymodule.features.yml file in it, it can gracefully handle updating existing configuration like this without throwing the nasty error. You can do a drush fr mymodule and it will import the new configuration without having to delete existing. As 4x4 was mentioning, this wouldn't be ideal for configuration site owners are changing, but if it's something you're updating and maintaining as the developer, it's an ideal route to go.


How to get the last updated time stamp of a field in field collection

There is no timestamp for field collection items. (Drupal 7)


Using rewrite in .htaccess may change how external URLs are handled by Apache, but it won't change how Drupal generates URLs itself. For that you need to change the base URL. Take a look at https://stackoverflow.com/questions/5879190/how-to-set-the-base-url-in-drupal


If it's not in the source, it's in the DB. At a guess, this is code that someone entered using the PHP filter, but the PHP filter is not active so it's showing up as text.

As to where it is in the DB, there's many possibilities. I'd use brute force to search the DB in its entirety. (That's easy for me to say as I have a copy of SQLyog to hand. I'm sure there are other tools that provide this functionality, though: I think PhpMyAdmin has it.)

Addendum: looks like it's in a custom pane, so the table panels_pane is the most likely culprit. Ideally you want to find how it's getting inserted onto the page. Do you have the module Panels Everywhere enabled?


Best way to search and replace text from blocks

Are you referring to custom blocks, not those provided by modules? If so, the main data is in the body column of the block_custom table in MySQL.

You could use an SQL query to perform the replacement.

UPDATE `block_custom` SET `body` = replace(body,"findstring","replacestring");

Credit: ChrisBrunner.com


Overriding menu.html.twig just for the primary menu

Answering my own question here, this will probably be useful for those looking to debug twig.

Activate devel Kint (part of the Devel module) on the modules page or with Drush
In your site /sites/default/services.yml change the following settings:

parameters:
  twig.config:
    debug: true
cache: false
auto_reload: true
Then in the template you want to debug, place this code in it:

{{ kint() }}

Now you get a nice tree of variables that prints out similar to what you would get if you did an old style kpr(get_defined_vars()); in Drupal 7.

I see from the debug printout that the name of the menu is simply main.
Now I change the overridden template in my custom theme's template folder to menu--main.html.twig
Voila, the template is only specific for the primary main menu now
Customize as a themer to your hearts content.
Throughout this process, don't forget to clear cache and change / remove any debug code when you are done.

In addition to this, with debugging active, Chrome prints out possible template suggestions a la devel_themer so you don't necessarily have to use Kint.


Try the Double field module

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

  For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea

  Consequently, in all there are 4 x 4 = 16 widget types.


Why is Rules Link checking all Rules Links on every page load?

What you have noticed (= repeat a check on every Rules Link available on the page), is simply how the Rules Link module works, especially if used in combination with the Views module, as in your question here.

As an example, refer to (my) question about "How to show authorized users a link for relevant Views results using the Rules Link module?". The accepted (my own) answer to that question includes an example of a Views result that looks like so:

User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

Actually the last column (with "Unlock user" for only the first 2 rows) is what got created via the Rules Link module. And to achieve this result, I used the "Configure Rules" tab to specify the relevant "Access Conditions". Don't be confused ... 'Access' here is not about permissions! Instead they are like an extra refinement of the permissions: they can be used to specify when to show the Rules Links, whereas this "when" is expressed using Rules Conditions (only).

I specified these Rules Conditions (which must both be satisfied), using the Add condition link (right above "Reactions"):

Data comparison, with:

Data to compare: [user:uid]
Operator: is greater than
Data value: 0

Data comparison, with:

Data to compare: [user:status]
Data value: Blocked

The 1st condition will ensure the link is NOT shown for Anonymous. And the 2nd condition will ensure the link is only shown for users for which the value of the Active column is No.

These Access Conditions of the Rules Link are actually saved as a regular Rules Component (using a Component Plugin type of "Condition set (AND)" and with machine name rules_link_condition_unblock_a_blocked_user).

So with the above in mind, and after I enabled "Show debug information" (within Rules Settings), I got a Rules Evaluation log which looks like this:

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.532 ms The condition data_is evaluated to TRUE [edit]
1.831 ms The condition data_is evaluated to TRUE [edit]
1.839 ms AND evaluated to TRUE.
1.86 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.251 ms The condition data_is evaluated to TRUE [edit]
0.368 ms The condition data_is evaluated to TRUE [edit]
0.376 ms AND evaluated to TRUE.
0.394 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.277 ms The condition data_is evaluated to TRUE [edit]
0.394 ms The condition data_is evaluated to FALSE [edit]
0.402 ms AND evaluated to FALSE.
0.419 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.233 ms The condition data_is evaluated to FALSE [edit]
0.241 ms AND evaluated to FALSE.
0.258 ms Finished executing of and Rules link: Unblock a blocked user condition.

Some more details about the above logging data:

I got exactly 6 groups of logging records (1 for each Views result) of Rules logging data (each of them starting with the line "Executing and Rules link: Unblock a blocked user condition.").
Only for the first 2 groups it says "AND evaluated to TRUE." (i.e. the 2 rows for which the Rules Link-link is to be shown), while for the remaining blocks, they all say  "AND evaluated to FALSE." (i.e. the rows for which the Rules Link is to be hidden).

But, for the Rules Link module to be able to correctly (yes or no) show such link for each Views result, it has to evaluate both Rules Conditions (those 2 data comparisons in my case, you were lucky ... you seem to only have 1 Rules Condition for each Views result ...). Or, to use your own words (as in your question): "repeat a check on every Rules Link available on the page".

Open (followup?) question: what happens if there are multiple pages of views results, i.e. when are those Rules Conditions evaluated for subsequent pages (when the page is to be actually shown, or at the very beginning when the very first page is shown)?


How to show all template suggestions for a page without using Devel Themer?

You can put this in your settings.php
$conf['theme_debug'] = true;

This outputs html comments on your page which will help you with debugging how the theme suggestions are selected.


Dynamically fetch feeds and html content from other website and show

Feeds is the way to go. It includes an HTML parser and can fetch data from existing URLs.

Here are some links to parsers for Feeds that can suit your needs.


Recognize js files in the library folder

Just putting the files in a directory won't do any good.

You have to either put a reference to your file in your module.info file, or use drupal_add_js somewhere, depending on what you're trying to achieve.


Email all Organic Group members when a subgroup is created

I managed to use make a custom rules file for OG Subgroups that achieves what I need it to. It adds the rule 'Get subgroup group members from group audience' to a 'Custom' rule group:

This makes the users of the subgroup available to rules. You can then loop through the users and send an email to each of them:

In order to do this I created  custom 'og_subgroups.rules.inc' file in the root of the OG subgroups module. This is the code I used inside it:

<?php

/****************
Adds the ability to get the members of the parent group from a subgroup using rules
/****************

/**
 * Implements hook_rules_action_info().
 */
function og_subgroups_rules_action_info() {
  $items = array();

  $items['og_subgroups_get_members'] = array(
    'label' => t('Get subgroup group members from group audience'),
    'group' => t('Custom'),
    'parameter' => array(
      'group_content' => array(
        'type' => 'entity',
        'label' => t('Group content'),
        'description' => t('The group content determining the group audience.'),
      ),
    ),
    'provides' => array(
      'group_members' => array('type' => 'list<user>', 'label' => t('List of subgroup members')),
    ),
    'base' => 'og_subgroups_rules_get_members',
    'access callback' => 'og_subgroups_rules_integration_access',
  );

  return $items;
}

/* NEW FUNCTION ************************************************/

// This callback creates the hashed string by using the parameters provided through rules' UI
function og_subgroups_rules_get_members($group_content) {

// get the nid from the passed value of the content being added
$nid = $group_content->nid->value();

// trying to manually call the get inherited users function from og_subgroups.common.inc
$inherited_users = _og_subgroups_get_inherited_users("node", $nid);

$members = array();

foreach ($inherited_users as $inherited_uid => $data) {
  // Get the group members the group content belongs to.

  $user=user_load($inherited_uid);

  // push the returned user to the array of members
  array_push($members, $user);

}

// return the users
  return array('group_members' => $members);

}

/**
 * OG Rules integration access callback.
 */
function og_subgroups_rules_integration_access($type, $name) {
  // Grant everyone access to conditions.
  return $type == 'condition' || user_access('administer group');
}

For those of you who prefer patches here is the patch I created: Patch on drupal.org


What are the technical implications of choosing asynchronous or synchronous billing cycle?

The "implications" are that it mimics how you want to charge your customer for access. If you want to provide a revolving 30-day access to some content, an asynchronous billing cycle might make the most sense. Whereas if you're charging for a service and want everyone to have the same billing cycle, then you'd end up prorating the first month to get to the first point of your billing cycle.

At a technical level, cron should be running in daemon mode (or at least every 5-10 minutes) since your license provisioning requires it. You shouldn't have to do anything different.


The following SSH command responded with a non-zero exit status (drupal-vm)

It seems to be related to a bug in VirtualBox 6.0.6. I downgraded to 6.0.4 and it now works.

Source: https://github.com/dotless-de/vagrant-vbguest/issues/278#issuecomment-486505824


Views Search is displaying no results behavior by default

I assume you are using the "On empty input: Show none" option of the search terms filter.
In this case the view is actually still running but returning no results due to the filter, so you get the empty text displaying.

To stop that you can change the "Exposed form style" to "Input required".

Then the view will not run until a search term is entered, which means no unwanted empty text.


Copy a user directly in database from another database (from production to dev-site)

Databases shouldn't be copied upstream, they should only be copied downstream, for the exact reason you are seeing.

This is a bit of a problem in Drupal 7.

If you need to move content up from dev -> production, like new nodes or you want to move configuration, then the best way to do it is either manually, or to set up something like the migrate module to migrate your content.


Is there any module that can automatically convert a module to be used on a different version of Drupal?

I will not say that it is fully automatic, but Coder Upgrade, which is a sub-module of Coder, will do a lot of the grunt work for you.  However, it is not a 100 % solution, there are always some loose ends to tie up.  It is a good idea to use Coder Review afterwards to highlight the areas that need special attention. After that, it should be a simple case of installing the Drupal 7 version of the module, test it, and fix the remaining nits "by hand".

You can download and install it as part of your staging site or use the web-based version: http://dupgrade.com/

It is one way: Drupal 6 to Drupal 7.  I know of no tool that goes in the other direction.

See also: https://drupal.org/node/224333 for an overview of the changes from Drupal 6 to Drupal 7.


Using jQuery .ajaxstart with views exposed filter

I found another js file that was causing the error, decided to live without it and everything works after removing it.

So, if someone encounter errors like this, change the the default theme and see if that solves the problem, then you know if the issue is within your custom theme or somewhere else.