Displaying Profile2 edit page with Panels

I guess panel and display suite both dont provide this use case. you could use hook_theme and then render function. Example code

   function modulename_theme(){

        return array
        (
                    'user_profile_form' => array
            (
                'render element' => 'form'
            ),
        );
    }
function theme_user_register_form($variables){
    $form = $variables['form'];
    $output='
';
    if(isset($form['profile_main'])){
     $output.= drupal_render($form['profile_main']['field_profile_main_fname']);
     $output.=  drupal_render($form['profile_main']['field_profile_main_lname']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_phone']);

}
    $output.="
";
$output='
';
if(isset($form['profile_main'])){
    $output.= drupal_render( $form['profile_main']['field_profile_main_gender']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_dob']);
 }
}
    $output.="
";
    $output.= drupal_render_children( $form);
    return $output;
}

Then on css you could add float left and width on divs to make it 2 columns


Make block appear on some pages but not others

I believe your only option is to use a PHP snippet to set the visibility.

Under Visibility settings select Pages on which this PHP code returns TRUE (experts only) copy and paste the snippet below.

<?php
if (arg(0) == 'user' && !arg(2)) return TRUE;
?>

For this to work you would also need to enable the PHP filter module.

Note that it's not generally recommended to use the PHP filter, but in some cases it might be the easiest solution.


Solution is to implement theme_form_element_label.

Changing one line from:

$attributes = array();

to:

$attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

in your implementation makes it possible to use '#label_attributes' just the way you would use normal #attributes.

NOTE: If your parent theme defines this function already, then you need to copy function from parent theme, not from form.inc.

Full implementation, to put in template.php:

function mymodule_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  // NOTE: CHANGED LINE BELOW!
  // If there are attributes already, use them. If not, create empty array.
  $attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}


GOT IT! After googling for a while I came accross this: http://drupal.org/node/224170

This clarifies that

"When a % symbol is used in a menu element (see example), the text that follows will be used to build the name of wildcard loader function.

In the example above, "%node" tells drupal to pass the value of the second element to the function node_load(). _load is always added by Drupal to construct the wildcard loader."

So as long as the notification_type_load() function wasn't implemented it lead to a bug :)


how to import cck data from drupal6 to drupal7?

You could use the Migrate module along with the Drupal-to-Drupal data migration module

Migrate

  The migrate module provides a flexible framework for migrating content
  into Drupal from other sources (e.g., when converting a web site from
  another CMS to Drupal). Out-of-the-box, support for creating core
  Drupal objects such as nodes, users, files, terms, and comments are
  included - it can easily be extended for migrating other kinds of
  content. Content is imported and rolled back using a bundled web
  interface (Migrate UI module) or included Drush commands (strongly
  recommended).

Drupal-to-Drupal data migration

  migrate_d2d provides a framework based on the Migrate API for
  migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the
  Drupal 7

Another option would to use the feeds API to import data. You could create feeds of the contents in drupal 6 and use feeds API to create the required contents in Drupal 7

Data export import is another module that does import and export of content.

Node export this another module that can be used along with Feeds


How to automatically generate anchor ids to CKEditor added headers

in JS, id set from the h2 label two first words :
const headings = document.querySelectorAll(
  ".article--full h2, .article--full h3"
);
const tocElements = createTocElementsArray(headings);

function createTocElementsArray(headings) {
  const tocElements = [];
  for (const item of headings) {
    if (item.id === "") {
      item.id = item.firstChild.data
        .split(" ")
        .slice(0, 2)
        .join("-");
    }
....
}


Reload page after applying commerce coupon

One solution here is to add a custom JS behavior to your module that looks for the AJAX callback context of applying a coupon. Upon such context, you can refresh the page or update the DOM as you see fit.

(function ($) {
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {

    //Look for the context of a coupon form AJAX callback
    //If there's no error message, assume successful coupon application
    if($(context[0]).attr('id') == 'commerce-checkout-coupon-ajax-wrapper' && !$(context[0]).find('.messages').hasClass('error')) {
      //@TODO: Reload page or other JS to refresh coupon usage
    }
  }
};
}(jQuery));


Including JS after the JS specified in theme info file

You can specify the #scope attribute to control where the JS gets added. For example, you could place it in the footer, which (more likely than not) would come after your theme's JS:

'#attached' => array(
  'js' => array(
    'http://somepath/0.0.2/contact-0.0.2.min.js' => array(
    'type' => 'file',
      'weight' => 1000,
      'scope' => 'footer',
    ),
    drupal_get_path('module', 'moduleName').'/js/contact-config.js' => array(
      'type' => 'file',
      'weight' => 5,
      'scope' => 'footer',
    ),
  ),
),

Alternatively, you could implement hook_js_alter() to change the 'final' ordering of the JS files added through #attached, drupal_add_js(), .info files, etc.


Drupal Commerce Entity Query Line Item Prices

You can use Entity API that provide  a unified way to deal with entities and their properties, please read README.TXT there. Handbook is poor.


How to output $variables without loading everything?

Devel is a great tool for debugging. It comes with krumo() function which works similar to print_r() but doesn't output everything, only up to certain depth (I think 3 or 4 levels).


How to make Taxonomy replacement tokens available to the HTML email action in Rules?

Make sure to add a Rules condition Entity has field (related to your field you indicated via the "through a select field..." in your question).

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

Your question seems to be related to using such field in a Rules Action (instead of a Rules Condition). However, have a look at the sample rule in included in my answer to "How to specify a Rules condition related to select list values?". That rule doesn't have a "Rules Action" that uses that field (as you seem to try to do). Though using the Rules UI to (eg) edit the message I'd want to display in my sample rule, within the list of tokes available for Replacement patterns for created content, one of them is actually [node:field-optionlist]. And the 'created content' in my case is because of the Rules Event node_insert that's used in my sample rule.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

PS: To have such field available to use it in any other Rules Condition also, I always add such Entity has field condition BEFORE any other Rules Conditions, if any.


I have created simple module to Integrate nodejs and build chat server for drupal users  d7 nodejs chat


I think you have 2 main options:

You can use some custom PHP to control the blocks visibility. Something like:

global $user;
$account = user_load($user->uid);
if($account->profile_type[LANGUAGE_NONE][0]['value'] == 'some value') return true;
return false;

Or I think this is a good use case for the Context module. This allows you to create different "contexts" that your blocks should appear in. An example from the Context help file says:

You want to create a "pressroom" section of your site. You have a press room view that displays press release nodes, but you also want to tie a book with media resources tightly to this section. You would also like a contact block you've made to appear whenever a user is in the pressroom section.

Add a new context on admin/build/context
Under "Conditions", associate the pressroom nodetype, the pressroom view, and the media kit book with the context.
Under "Reactions > Menu", choose the pressroom menu item to be set active.
Under "Reactions > Blocks", add the contact block to a region.
Save the context.


View: Link to content is always rendering in the default language

It's a bug and it's being worked on, the solution is provided and it's currently labeled as Needs review. Perhaps you can apply the patch and test yourself:

Entity Links fields does not have translation support

In Drupal 8.4 and earlier versions it was possible to use the workaround of Path field and using Custom text field to construct the link:

{% trans %} View more {% endtrans %}

The Path field output correctly translated links with correct path prefix, see here: Translate Content: Link to Content field on Views in Drupal 8. But in Drupal 8.5 the Path field is no longer supported, so you have to patch or wait for the update to gets released.


Is it possible to completely hide the admin menu for a role, while still grant it some admin permissions?

Uncheck "Use the administration toolbar" for the 'demo' role under Users > Permissions.


How can I provided simplified custom exposed filter options for a field in Views?

I've done something very similar to that with the following process:

Implement hook_views_api() in a custom module

function MYMODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/includes/views',
  );
}

Create includes/views/views_handler_filter_MYMODULE_country.inc somewhere with code similar to this (the MYMODULE bit isn't necessary, just a bit of low-tech namespacing):

class views_handler_filter_MYMODULE_country extends views_handler_filter_in_operator {

  /**
  * Get value options for the select list.
  */
  function get_value_options() {
    // Replace $this->value_options with an appropriately filtered list.
    $this->value_options = function_to_build_filtered_list();
  }

}

Register that file with the autoloader by adding this to MYMODULE.info:

files[] = includes/views/views_handler_filter_MYMODULE_country.inc

Finally, implement hook_field_views_data_alter() to force Views to use your new handler, changing the $field['field_name'] condition (and other similar strings based on field_address) to whatever makes sense for your site

function MYMODULE_field_views_data_alter(&$result, $field, $module) {
  // Limit country exposed filters.
  if ($module == 'addressfield' && $field['field_name'] == 'field_address') {
    $result['field_data_field_address']['field_address_country']['filter']['handler'] = 'views_handler_filter_MYMODULE_country';
  }
}


Protect previous migrated field values on system of record migration

My solution was to use the prepare($node, stdClass $row). This basically takes the current values and joins them to the new ones.

https://www.drupal.org/node/1222668#comment-4795190


You also need to update the node_revision table. You either need to create a new revision for that node or update the latest one.


Get select field value inside of a module

Update as @berdir suggested in the comments, the best way to get a field value is:

$node->get('field_location_type')->target_id

In addition, you could also use Field::getValue method if you want an array representation.  Something like:

$entity->field_location_type->getValue()[0]['target_id']);

In addition if you need the term name (Option A ) from the id you can do this:

  $tid = $entity->get('field_location_type')->target_id;
  $term = \Drupal\taxonomy\Entity\Term::load($tid);
  // $name should have 'option A' or 'option b'
  $name = $term->getName();

Update: one way to figure out what methods are available  to you is to use xdebug in PhpStorm. If you set a break point after $field = $entity->field_location_type; you can then type $field-> and then hit ctrl and space the editor will provide suggestions based on the type of $field Here is a screen shot:


How do I get the user's email in the user profile template?

I solved this by following way.

$account = menu_get_object('user');
$mail = $account->mail;


Have a look at the documentation for hook_install. It says:

  Note that functions declared in the module being installed are not yet available. The implementation of hook_install() will need to explicitly load the module before any declared functions may be invoked.


Increasing performance of cache_form on high traffic sites

Checkout https://www.drupal.org/project/apdqc if you're on D7; this is my config for it in the settings.php file.

$conf['apdqc_cache_default_compress'] = 2;
$conf['apdqc_cache_compression_level_cache_form'] = 3;


How to automatically enable custom modules upon theme activation?

As @4k4 mentioned there's ongoing development to Allow themes to declare dependencies on modules which hopefully lands in core with 8.6.0. Until then you are a little bit out of luck, except you find a place somewhere in your theme to trigger the following line of code:

\Drupal::service('module_installer')->install(['MYMODULE']);

Alternatively you could provide a second module which provides some button in the back-end which on-click triggers the above line PLUS the following two lines all at the same time.

\Drupal::service('theme_installer')->install(['MYTHEME']);
\Drupal::service('theme_handler')->setDefault('MYTHEME');

The background behind the issue mentioned above is that themes can't provide Drush 9 commands. As Drush 9 commands depend on certain services. But themes ain't allowed to provide these services. See the following issue: Allow themes to provide services.yml which was closed as won't fix.

The reason to close the service-issue (in a nutshell) is to keep things clean (from an OOP point of view) and don't let themes become other modules. Themes should provide templates, styles, scripts. Whereas modules should provide everything OOP-related, including services.

And as themes now (because of this decision) can't provide Drush commands anymore there must be away to allow them to rely on companion modules to provide useful commands/scripts and libraries for (sub-)theme development and maintenance. Which then will probably get activated automatically upon theme activation. So let's look forward and contribute to get this into core ASAP!


Is it possible to add a class to an image field of a node wise

Have you checked the already built-in classes drupal adds to fields in the HTML? That is the way I style a single content view.
Is this https://drupal.org/node/1795294 the module? In the description they explain how to add a class.

PD: I wanted to leave a comment but do not have enough reputation to do so.


Update user email in custom module : validation API returns "Your current password is missing or incorrect"

The violations you're seeing come from core's ProtectedUserFieldConstraint. The constraint is applied when the current user tries to update their account fields without supplying a password. The validator method has a built-in flag to disable this check when needed (e.g. when a user resets their password).
To set the flag, set the _skipProtectedUserFieldConstraint to TRUE (e.g. $user->_skipProtectedUserFieldConstraint = TRUE;) and the validator won't enforce supplying a password when changing the current user fields.


Can Drupal 8-compatible Drush be installed in Windows?

Although it's a year and a half since this question was posted, as we get closer to a production release of Drupal 8 I can see it getting a few hits. So here's my answer...
Yes, it certainly can!
Although as of this writing it appears Drush 8.x (in particular the latest dev on branch master) is the recommended version for Drupal 8 development.
See: Drush Installation/Upgrading instructions
I'm running WampServer 2.5 (PHP 5.6.13RC1, MySQL 5.6.17, Apache 2.4.9) on Windows 8.1 and use Git Bash shell from the Git for Windows installation. I have Composer 1.0-dev set up globally.
I was able to upgrade successfully1  following the first installation method on this page, Composer - One Drush for all Projects.
Steps

Install from the command line:
$ composer global require drush/drush:dev-master

Modify the path to Drush in your system environment variables (here's a helper). On my system, Drush was installed in c:\Users\Username\AppData\Roaming\Composer\vendor\drush\drush.

Reboot Windows

Troubleshooting: Check loaded php.ini
The only problem that cropped up post-install was that the PHP settings being loaded by the CLI (and accessed by Drush) are out of sync with those loaded by WampServer. I found I had to copy my PHP settings from phpForApache.ini to php.ini in the currently loaded PHP version folder in c:/wamp/bin.2
Is Drush telling you you don't have X extension enabled, when you know you do? Run drush core-status to check on the path to php.ini on your own system.
A note about the Windows zip package
I had previously used the Windows zip package to install version 6.x. As of this writing there is a package available for version 7 - scroll down to the bottom of the installation page - but not 8 (unsurprisingly since AFAIK it is heavily under development). I wonder if having previously gone through this process somehow eased this upgrade by setting up some necessary extras - probably not;  I just don't know. Maybe I just become a big, fat skeptic when things work too easily on Windows.3
See also:
Installing Drush on Windows (Drupal.org)
How to Upgrade Drush to work with Drupal 8 (Manjit Singh)

1 Because this is Windows, it should be noted that I've only installed in the last couple of days, and have so far only used it for basic tasks such as creating databases, installing a site, clearing the cache tables. No problems so far, but that doesn't mean they won't crop up.
2
I don't recall having to copy the PHP settings over before, and this is going to be a bit sticky when I alter these settings or switch between PHP versions, but so far I haven't found a way around this.
3 The author above (Manjit Singh) seemed to have a similarly pain-free upgrade, which makes me less skeptical. :)


Using entity_lookup inside an entity_generate migration process plugins

It seems that you actually can use entity_lookup inside entity_generate. The problem here was with the wrong indentation bellow plugin: entity_lookup. Yup... it was that kind of "bug" (feeling embarrassed) :)


How to count the number of consecutive days on which verified users accessed the website?

Overriding the built-in Last access field is not possible with Rules, so I added a new user Date field Last day online that stores a day, month and year. Recall that I had already created another user integer field Consecutive days. Here is the magical Rule:

{ "rules_extra_consecutive_day_online" : {
    "LABEL" : "Extra consecutive day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1", "3" : "3" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-user:field-consecutive-days" ], "value" : "0" } },
          { "data_is" : {
              "data" : [ "site:current-user:field-last-day-online" ],
              "value" : "yesterday midnight"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-consecutive-days" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_consecutive_days" : "New consecutive days" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-consecutive-days" ],
          "value" : [ "new-consecutive-days" ]
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-last-day-online" ],
          "value" : "today midnight"
        }
      },
      { "schedule" : {
          "component" : "rules_reset_consecutive_days",
          "date" : "+2 days midnight",
          "param_user" : [ "site:current-user" ]
        }
      }
    ]
  }
}

This is what the Rule does in words:

First, check that the current user is verified, and make sure the user's Consecutive days field is zero or the user's Last day online is yesterday.
If the above requirements are satisfied, then increase the Consecutive days, change the Last day online to today and schedule the component Reset consecutive days.

Underneath is an export of the mentioned Rules component. It resets the Consecutive days field if the Last day online field is less than yesterday (which means that the user was not online on at least one day).

{ "rules_reset_consecutive_days" : {
    "LABEL" : "Reset consecutive days",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "data_is" : {
          "data" : [ "user:field-last-day-online" ],
          "op" : "\u003C",
          "value" : "yesterday midnight"
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-consecutive-days" ], "value" : "0" } }
    ]
  }
}


Suggested way to setup drupal to handle multiple subsites / subdomains?

Have you considered using the multisite setup?

  This is particularly useful for managing the code since each upgrade
  only needs to be done once. Each site will have its own database and
  its own configuration settings, so each site will have its own
  content, settings, enabled modules, and enabled theme. However, the
  sites are sharing a code base and web document root, so there may be
  security concerns with multiple administrators

I've used this for setting up one codebase and then creating multisite installs of the codebase for clients who want similar websites. Multisites can be done as either subdomains (ie subdomain.domain.com) or subsites (ie domain.com/subsite). Each multisite install has its own database, and can have its own modules or theme even, but if there is core functionality you can put it in the root codebase and it will be shared across all multisites.


custom.info

PS. Do not include <?php ?> tags.

; $Id:
name = Custom
description = Custom validate node delete permission
package = Custom
core = 6.x

custom.module

  <?php
    /*
     * file
     */
    function MYMODULE_form_alter(&$form, &$form_state< $form_id){
      switch($form_id){
        case 'node_delete_confirm':
          $form['#validate'][] = 'my_custom_validate';
          break;
      }
    }

    function my_custom_validate($form, &$form_state){
      $nid = $form_state['values']['nid'];
      $node = node_load($nid);
      if(/* conditions */) {
        // some procedure to check fields
        $message = t('You have not any permission to delete this node!');
        form_set_error('nid', $message);
      }
    }
  ?>

Place this files into /sites/all/modules/custom/*.* and activate it on module administration page.
Enjoy.


You simply need to click on the Cancel button nearby the Save button


How to show the uploaded managed_file in the edit page?

Inspecting the $foo variable showed that I was supposed to use just $foo->image instead of $foo->image->fid.

Probably because I have the following lines in my _form_submit:

if (isset($form_state['values']['image'])) {
    $file = file_load($form_state['values']['image']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'foo', 'foo', $foo->tkid);

    $foo->image = $file->fid;
  }

Notice the part that says $foo->image = $file->fid;


If you install an official dev version (not a git checkout, but downloaded from the website), it has a date information. If there is a newer stable or dev version, you will be informed.

However, development releases are exactly that. Some work, some work well and others might not work at all.


How to add additional tabs to user profiles

I believe you can implement hook_menu in a custom module and use MENU_LOCAL_TASK as the type, and the path needs to start with user/

function HOOK_menu() {
  $items['user/mypage'] = array(
    'title' => t('My Tab'),
    'type' => MENU_LOCAL_TASK,
    //'page callback' => 'mymodule_mypage', //mymodule_mypage should be a function that returns HTML for the content area
    //'page arguments' => array(0, 1, 2), // 0 is arg(0), 1 is arg(1) etc...
  );
  return $items;
}

For all the array elements see this page


It depends on what your result stores. It can be like entity with relation or just field:

1) $result->_entity->set('field_Name', 'xxxxxxxxxxx');

2) $value->node__field_Name = 'xxxxxxxxxxx';


How to create a page to custom display of particular node type and add it to node context menu?

First question:
First you are going to want to set your views path to: node/%node/specialized-display. Then, in the contextual filter, under "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED" check off: Specify validation criteria. Finally, select "Content" from the dropdown and select your node type.

Second Question:
This guide explains how to add contextual links, all you are going to need a basic custom module with a routing.yml file. You can set the route to the view. Hint, Drupal console's drupal debug:router is a great way to find the route to your view. https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links#s-rendering-contextual-links

Third question:
I've had my best luck with the sub-pathauto module to make the aliased routes. https://www.drupal.org/project/subpathauto

Thoughts...
I am using this setup on two sites so far and this works pretty well. Sub-Pathauto seems to behave fairly well. I do have one tip though, when initially building my views, I disable it, so that I can ensure everything works before I add the extra layer.

Other thoughts...
This could be done through traditional custom views processing. If you have a big site, it may be the way to go. I haven't tested Sub-Pathauto at large scale, this is currently something I am experimenting with.


Theming book navigation block to generate drop-down menus

There is a specific theme function, which is used from the Book module for outputting its own block of links to book pages. I am not sure if it suits your case, but you can always use that code to build your own theme function.

The theme function is called from book_block(), using the following code:

  if (variable_get('book_block_mode', 'all pages') == 'all pages') {
    $block['subject'] = t('Book navigation');
    $book_menus = array();
    $pseudo_tree = array(0 => array('below' => FALSE));
    foreach (book_get_books() as $book_id => $book) {
      if ($book['bid'] == $current_bid) {
        // If the current page is a node associated with a book, the menu
        // needs to be retrieved.
        $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
      }
      else {
        // Since we know we will only display a link to the top node, there
        // is no reason to run an additional menu tree query for each book.
        $book['in_active_trail'] = FALSE;
        $pseudo_tree[0]['link'] = $book;
        $book_menus[$book_id] = menu_tree_output($pseudo_tree);
      }
    }
    $block['content'] = theme('book_all_books_block', $book_menus);
  }

The theme_book_all_books_block() function is empty, because the theme is using a template (book-all-books-block.tpl.php); as far as I can see, there isn't a preprocess function for that template file.


Why multilevel dynamic local tasks doesn't work?

You said your file is called module.links.tasks.yml. The correct filename is module.links.task.yml (note links word is pluralized, but task is not).


Drupal 7 hook_validate not called with custom form template

SOLUTION: Was only needed to add print drupal_render_children($form); at the bottom of the template file.


How to troubleshoot my VBO operation which freezes at 50% every time?

Try to (temporary) increase the available memory with like 10 or 25%, and see if you get past that nr of 46748 (possibly even past 46766). If it doesn't help, it won't hurt ...

BTW, even though this question is not about using Rules in combination with VBO, you might want to also watch the video about "More details about VBO settings" (especially what is explained between (about 04:00 and 05:00). It provides some extra hints / tips to process like 100.000 nodes at once, which is quite a challenge to get to work (memory requirements, etc).


Need to change User Pages Title and Breadcrumb in drupal 7?

Before trying to implement through code, give a try to these modules:

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

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


The token used to get the user who wrote the content is not [user:name]. This is the username of a user account that you are trying to view, so this might not be available on the node page as we are not referring a user.

To display the author name you should use [node:author:name].

If you install the token module you could go to the Help > Token (admin/help/token) page and see the available tokens.

For more details and a list of the available tokens, see this page.

EDITED As per suggestion in comment.


How can I get a views exposed filter to persist across multiple views?

It sounds like you would need to save the value somewhere. Next when a page load event happens (on any page of your site) you need to load the value into the field. I think you might need to create a cookie to do this.


How do I get all the referenced taxonomy terms without the field name?

You can iterate through all the fields on the node and add conditions to check that the field is an entity reference field, and that the target type is taxonomy_term:

// Iterate through each field on the node entity to get all the tagged
// taxonomy terms on the node.
foreach ($entity->getFields() as $field) {
  // Only look for fields that are entity reference fields.
  if ($field instanceof EntityReferenceFieldItemList) {
    // Get the field settings.
    $field_definition = $field->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    // Check that the field targets are taxonomy terms.
    if ($target_type == 'taxonomy_term') {

      // Do stuff..

    }
  }
}


Advanced CSS/JS Aggregation Module Breaks My Site Layout

I faced the same issue, here is some steps to check:

check if your css loaded and optimised in your page source code some files like /sites/default/files/css/css_QnKw33sohmgUyVqs9lGXvHTJTZsphXTkXdkVVmt25ts.css if it's no check if there is any errors in your console, if this is the case Check your status page and log messages, and permissions
If it's yes all files well loaded this is was my case i had some css errors that's why even my css files loaded not taking any effect:
So i had to check / validate all my css files and correct any errors.
I used this https://codebeautify.org/cssvalidate.
there is a lot other websites to validate your css.
I hope this help you !


How do I test for node type to print a variable from template.php?

Each template has a different set of variables available. The variables available in a given theme is generally documented in the comment section at the top of the file. You can consult this documentation on http://api.drupal.org.

The node type is not directly available as a variable in the page.tpl.php. However, you have the $node object which has a type property:

function MYTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'NODETYPE') {
    $variables['greeting'] = 'Custom Greeting';
  }
}


The Drupal database layer wraps around PDO and uses prepared statements, so yes, the insert statements are sanitised and protected from SQL injection attacks.

This quote from the Prepared Statements docs says it best:

  The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

The same is true for all of the database functions in Drupal 7 (db_select, db_delete, etc.). The only one that is still potentially insecure is db_query() which will execute any arbitrary string you pass to it. Even with db_query(), though, you can pass in parameters so your query is safe.

The Database abstraction layer docs have some more information.


theme_image_style() doesn't output what is expected

Drupal 7 provide Image style functionality which allow administrator to set predefined size and can apply image style to any image in site.

  Using image styles you can scale, crop, resize, rotate and desaturate
  images without affecting the original image. By default three sizes
  are defined: 'thumbnail,' 'medium', and 'large'. The thumbnail style,
  for example, is shown with the teaser for image posts and when
  browsing image galleries.

In your code, you have defined $img = theme('image_style', $params); which mean that you are applying image style to your image.

When we apply image style to any image, it will create a new image in styles/[stylename]/public directory and does not affect the original image source.

There is no stylename in your http://mysite.local/sites/default/files/styles//public/images/image.jpg url after style part of url, so I guess $presetname is not properly defined in your code.

You can try below exammple:

$params = array(
    'style_name' => 'thumbnail',
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );
$img = theme('image_style', $params);


How to uncheck a checkbox programmatically?

After a lot of trial and error, I found out:

Imagine a checkbox with name 'Coffee' has one option: ['Y' => 'I want an espresso'].

To uncheck this selection, enter:
$form['Coffee']['Y'][#checked]=false


Importing Drupal Commerce Orders, Customers, Ship to and Bill to addresses

There's also Migrate Module ; but your question is vague regarding the source you are migrating from.  This module supports different sources to migrate from

https://drupal.org/node/1006986


What is the correct way to pass values from PHP code to javascript in Drupal 8?

There are a number of ways you could do this. I will you tell you one.

Create a controller class that has a method that is responsible for printing an array of numbers. Hit that endpoint via a javascript get request and do something with the returned data.

So you would create a routing file:

your_module.routing.yml

your_module.create_numbers:
 path: '/your_module/{numbers}'
 defaults:
   _controller: '\your_module\Controller\YourCustomControllerClass::createNumberArray'
 requirements:
   _permission: 'access content'

YourCustomControllerClass.php

<?php

namespace 'your_module\Controller';

class YourCustomControllerClass extends ControllerBase {

 /**
 * Return a JSON response based on the number param
 * @param $number integer The number passed into the route.
 * @returns JsonResponse
 */
 public function createNumberArray($number) {
   $numbers = [];
   for ($i = 0 ; $i < $number; $i++) {
     $numbers[] = $i;
   }
   return new JsonResponse($numbers);
 }

}

Now you can hit your route from Javascript. The cool thing about this is that your route can create dynamic arrays. If you notice in the routing file the numbers is in {}. That means it is dynamic and is passed in as an argument to the createNumbersArray method. It can then use it to create an array of any length.

your_module_graph.js

var numbers = 10;

// Note numbers can be set to whatever you want.
var jqxhr = $.get( "/your_module/" + numbers, function(data) {
  // data will be a JSON object containing an array of numbers.
  var parsedJson = JSON.parse(data);
  // Now do what you want with parsedJson. Build your graphs etc.
});

I haven't tested that but have done similar things a lot lately and I'm quite confident that if not that exact code, the approach in general will suit your needs. As mentioned earlier there is no one way to do this but with Symfony now a core part of Drupal 8 it really is built for doing stuff like this. That is, taking HTTP requests and returning data.

Hope that helps.


How can I export users, forums and comments to another Drupal site?

If you want to export into a live site where there already exists forums, topics, nodes, comment users that you not want to overwrite, I suggest you check out the
Drupal-to-Drupal data migration module.  It will let you move the data and refactor it in the process.


How do I change the HTML structure of the primary links in Drupal 7?

It's useful to refer to the API documentation when you have an idea of what to do in version 'X' of Drupal and you want to translate the method to work in version 'Y'.

In this instance, the following API page will prove useful:

http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7


It can, yes. We've used it extensively to import contacts (nodes) into a homebrew CRM.

After creating your Feeds Importer, you should see "Mapping" as the last item in your settings panel to the left. After configuring the rest of your importer to work with your export's format, the Mapping Settings of the processor will allow you to map source fields in your dataset to target fields in your actual destination content type. Your nodes should have the appropriate fields filled in on import.


Webform Conditional fields showing by default

@kine456: My problems with webform conditional were very occasional. I mean sometimes they were there and other times they just disappeared.

I am also using webform template. On the templates, the conditional fields always worked but not so on the webforms inheriting from the template.

Thankfully, conditional fields have been built into webforms. I downloaded and currently use version#7.x-4.0-alpha6. No problems to report so far


You can use cron to achieve this,

Use hook cron in your custom module and write the codes to publish and unpublish based on your conditions
You can use Elysia Cron to schedule this cron job to run in every month or every first day of a month. Or you can configure cron in your server to set exact timings.


You can't trust JsFiddle when it comes to running Javascript in Drupal, because Drupal uses the Immediately Invoked Function Expression (IIFE), a well known pattern in JS. Raw code you supply the fiddle with may not always work in the application.

See managing JS in Drupal. Your code needs to be wrapped first. My guess? You have console errors regarding $ is undefined.

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(".cal-full").mouseover(function() {

        $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_hide');

    });

$(".cal-full").mouseout(function() {

        $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_hide');

    });
    });
    }
  };
})(jQuery, Drupal);

If this is Drupal 8, you will also need to require jQuery and related dependencies from your module or theme, so they are attached to the page before your script.


RSS feeds: How to reformat/rewrite/restyle? Using views? e.g. convert youtube text list of videos into thumbnails?

Yes Views will be the perfect module choice for you, there are many ways to tweak the output with Views & it has built in Feeds support.  Google about drupal views rss feeds, you'll find a ton of info.  When you install views there is an example rss feed view you can enable and take a look at to see how its done.  As for the thumbnails if your using emfield you should have the option to display thumbnail when tweaking the field output from within the View.

Good luck!


You can get PHPUnit tests to run by bootstrapping Drupal within each of your test files. It's not ideal, but it does work.

define('DRUPAL_ROOT', 'your/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

// Bootstrap Drupal.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Proceed with PHPUnit tests as usual from here.
class MyTest extends \PHPUnit_Framework_TestCase {
  ...


Add (create) content access control with Reference from URL

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

This means that you can set the Enter own value for the add image field for the authenticated user only.

The image below shows the settings screen in the module for a field named Nationality.


How do I extend a configuration form without using hook_form_alter()?

Solution:

I came out to this solution:

I created a custom_1.routing.yml file and write the following code in it.

#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_1\Form\CustomConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomConfigForm.php file in custom_1/src/Form/CustomConfigForm.php.

    namespace Drupal\custom_1\Form;

    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;

    class CustomConfigForm extends ConfigFormBase {
      public funtion getFormId() {
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames() {
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
          // Form code here
         return buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

Now, I have to merge some more form fields from another module custom_2. To achieve this, I followed the following steps.
I created a custom_2.routing.yml file and write the following code in it.

#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_2\Form\CustomTwoConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomTwoConfigForm.php file in custom_2/src/Form/CustomTwoConfigForm.php.

    namespace Drupal\custom_2\Form;

    use Drupal\Core\Form\FormStateInterface;
    use Drupal\custom_1\Form\CustomConfigForm;

    class CustomTwoConfigForm extends CustomConfigForm  {
      public funtion getFormId(){
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames(){
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
           $form = parent::buildform($form, $form_state);
          // Form code here
         return parent::buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

This resolve the issue for me without using hook_form_alter().

Thanks


image style not applied porgrammatically

The solution is

  return  theme('image_style',array('style_name' => $style, 'path' => $image_uri));

but this not work first because the image style for that file created before , first I should remove it then try this  ;)


is it ok to have multiple versions of jquery?

Try using the jquery multi module. Drupal core relies on specific versions of jquery, but this module allows you to control which environments use which version.
https://drupal.org/project/jqmulti

You shouldn't add jquery manually, nor should any modules. Drupal adds its own in core. Your errors may well be related, but that's hard to tell from the info you give. Do you know which module has added this?


How can I remove emoji from all user input?

All user input is a bit much. Only common ground I can see is that all user input goes thorough some kind of forms. And the only thing that for sure happens before anything tries to save, is validation*.

Functions listed in #validate can alter form state. Example definition shows they take form state by reference:

function test_form_validate($form, &$form_state) {

So the "only" thing you would have to do is to recursively iterate over all $form_state['values'], and apply your removal function. It should be pretty safe, because by the very nature your function will not affect numerical inputs in any way.

Other approach might be a bit faster. You can use #element_validate - prepend your removal function to validation array of each and every text field. Sadly, form element types may be added by modules, so you would have to prepend it to every element anyway (forgetting any significant boost due to validation only data that needs it, and paying a price of more function calls), or carefully inspect your modules and make sure you know what else, except textfield and textarea can accept text data (machine_name element is already safe, I omitted it on purpose).

All in all, I would prefer to just switch my MySQL to utf8mb4 charset, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

make a backup (obvious, but hey)
upgrade if needed
for each database, table and column that has it set already, change to CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci
Set default-character-set = utf8mb4 for [client] and [mysql] in my.cnf
Set (in the same file)

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

Hack Drupal to use it. What you want is around line 53 of /includes/database/mysql/database.inc

Hacking Drupal is usually not encouraged, but in this particular case we cannot expect a patch, so this is the only way to give users what they want. Also, it's method way less CPU consuming that altering all inputs.

* Of course you may create your own submit handler and make it a first one, but making sure it's always first is hard. Other module developers may try to have their handlers first, too. And if they decide to, for example, log something to MySQL, your fix becomes futile. Using validation is a bit of abuse, but it's an only way I would trust in this scenario.


Can I have Composer or something else download a Git repo as a dependency of my contrib module?

You can edit file composer.js

find "web/libraries/{$name}": ["type:drupal-library"], change to

"web/libraries/{$name}": [
                "type:drupal-library",
                "type:bower-asset",
                "type:npm-asset",
                "vendor:npm-asset",
                "vendor:bower-asset",

            ],

add repositories

{
            "type": "package",
            "package": {
                "name": "serratus/quaggaJS",
                "version": "0.12.1",
                "type": "drupal-library",
                "source": {
                    "url": "https://github.com/serratus/quaggaJS.git",
                    "type": "git",
                    "reference": "master"
                },
                "dist": {
                    "url": "https://github.com/serratus/quaggaJS/zipball/master/serratus-quaggaJS-v0.12.1-14-g862df88.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "^1.0.20"
                }
            }
        }

and run composer require "serratus/quaggaJS"


did you implement hook_views_data and then defined you table there? if yes then did you define relation for uid?
you can copy code from views/modules/node.views.inc

  // uid field
  $data['node']['uid'] = array(
    'title' => t('Author uid'),
    'help' => t('The user authoring the content. If you need more fields than the uid add the content: author relationship'),
    'relationship' => array(
      'title' => t('Author'),
      'help' => t('Relate content to the user who created it.'),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'field' => 'uid',
      'label' => t('author'),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_user_name',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
    ),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
  );


How to create a view that links an image from a field collection item to the field collections host node

Edit the image field and link image to 'content'

Another method:

    1. Add the nid field in view.
    2. Edit the image field, Go to the rewrite result and check "Output this field as a link". and put node/[nid] token in it.


Calling a view from code gives no results

The View set_arguments() method takes an array as it's first parameter; currently you're passing a string/int.

This code will work.

$view->set_arguments(array($account->uid));

I think you're right about the C-style access to a string-as-an-array-of-chars in PHP. The following code prints the letter e, which would certainly support that theory.

$x = 'test';
print $x[1];

I must say I'm surprised that Views doesn't check the validity of the parameter passed to it, but hey ho!


Custom block displayed via Contexts not being shown to anonymous users

I found the source of the problem.

I had used hook_block to create the block. I had specified BLOCK_CACHE_GLOBAL for the cache settings of the block which means the blocks were cached the same way irrespective of the page or the user.

I changed the cache setting to BLOCK_CACHE_PER_PAGE and it solved the problem. (The block hosted an openx ad which was only displayed on pages with certain taxonomy terms.)


Contact form redirects to homepage without showing submission information

You can use hook_form_alter to hook into the contact form and change the default submit behaviour. So instead of redirecting when the form submits, you can just omit that part and display the status message.

function mymodule_form_alter($form, &$form_state, $form_id ) {
  if ($form_id == 'contact_site_form') {
    // Use our own custom submit function for the contact form.
    $form['#submit'] = array('my_custom_submit');
  }
}

function my_custom_submit($form, &$form_state) {
  drupal_set_message(t('Success.'));
}


Disable Node's Show summary in full view in D6

I've written a form_alter function for node edit form that has solved my problem:

function my_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'page_node_form') {
        $form['body_field']['teaser_include']['#default_value'] = FALSE;

        $prefix = $form['#node']->teaser;
        $str = $form['body_field']['body']['#default_value'];

        if (substr($str, 0, strlen($prefix)) == $prefix) {
            $form['body_field']['body']['#default_value'] = substr($str, strlen($prefix));
        }

    }
}

Also the teaser_include as in the question is from the node edit form which is accessible from this checkbox:


How to change the output field date in a view?

If you are asking for the how to get year from date and use the year in view query alter then

You can use strtotime();

$year = date('Y', strtotime($field_data_field_issuu_date.field_issuu_date_value));

Another way in view you can use custom date format on display and show only year and use that value.(Depends on requirement)


Problem using ColorBox with Media Galllery

Actually all you should need to do is change... Well, you'll need to change two things actually:

Rename sites/all/library to sites/all/libraries
Rename colorbox-master to colorbox

The final output should look like this: sites/all/libraries/colorbox

And don't forget to flush the caches after you make the changes, just to make sure the system recognizes them. ;)

Hope that helps... :)


How to add field classes from within template_preprocess_node

Ok my somewhat dirty solution was to pass a classes array from template_preprocess_node to template_preprocess_field:

function template_preprocess_node(&$vars){
  if(!isset($vars['content']['field_name']['classes_array'])){
    $vars['content']['field_name']['classes_array'] = array();
  }
  $vars['content']['field_name']['classes_array'][] = 'custom-class';
}

function template_preprocess_field(&$vars){
  if(isset($vars['element']['classes_array'])){
    $vars['classes_array'] = array_merge($vars['classes_array'], $vars['element']['classes_array']);
  }
}

If there's a more 'official' way to do this, please feel free to enlighten me and I'll re-award the answer :)


A user-friendly, fast way to delete the same field from several content types at once?

You can execute this code manually

field_delete_field('your_field_machine_name');


Why are most of my Timefields blank when editing a node?

Some of the starting pointers I can think of.

Ensure there is no custom code altering the form field. Search for hook_form_alter/hook_form_FORM_ID_alter in your custom modules.
Check your drupal error logs, if there is any error log related to timefield.
Check your browser console, if there is a JS error.
Check the timefields module issue queue if there is already such error reported, that would be the best place to start from.
Try installing timefields module on vanilla drupal and check if the same issue persist, in that case add this in the issue queue of module.
Make sure all timefields get data when saved for first time, debug using devel module,go to 'devel/php' page and run dpm(node_load('your_node_id'));, see inside node object if those fields have value or not.
"Like s there anyway the possibility to keep the values of the fields somewhere, so I could populate the missing fields via javascript?" Yes, you can only if field values are getting saved to database, in fact simple would be to do at php level something like

function my_module_form_alter($form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    if(isset($form[#node]->nid)) {
      $form['yourtime_field']['#default_value'] = $form['#node']->yourtime_field['und'][0]['value'];
    }
  }
}

But this is not the solution, this will be re-attempt of what drupal already trying to do. Best would be to identify why values are not showing by default.


Class not found error on creating a custom service inside a module

This issue resolved after I included the full namespace from Drupal\module-name and placed the file inside the src folder. I included the namespace earlier, but I missed placing the corresponding "Helper" file in the src directory.


Location Contextual Filter: Distance/Proximity

The correct answer is this:

?distance%5Blatitude%5D=42.279594&distance%5Blongitude%5D=-83.732124&distance%5Bsearch_distance%5D=1&distance%5Bsearch_units%5D=mile


You may want to take a look at the Radioactivity module and see if it works for you.  It defines a "hotness" for a node, and a "halflife" that the "hotness" wears off at.  This attempts to account for popularity over time, instead of raw page views.

For example, a popular blog post from a few days ago will be more "hot" than a wildly popular blog post from last year that had more page views.

Time-decay is configurable, and it integrates with Views.


Create an author archive page with views

You'll want to create a view of articles and add a contextual filter for the node reference field.

How are you attaching the view to a node? Is it a views attachment? Is it a panel pane á la Page Manager? That will determine the specifics of how your view parses the argument out of the URL.


index.php is added in front of paths for anonymous users

This is mainly an SEO issue. Search engines seem to like unclean URLs with index.php. Once they found one all internal links on your site also contain index.php and so they sometimes crawl the entire site in this namespace.

You have to return a 301 redirect for any unclean URL to stop this. Install the module Redirect and go to the module settings /admin/config/search/redirect/settings:

  GLOBAL REDIRECTS

  [x] Enforce clean and canonical URLs.

  Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing
  trailing slashes, ensure the language prefix is set and similar
  clean-up.


How to load module include files in .test file?

You have a flaw in your code, module_load_include works by including files relative to the module base dir, so you should do

module_load_include('inc', 'password_policy', 'constraints /constraint_uppercase');

to include password_policy/constraints/constraint_uppercase.inc

When you do

module_load_include('inc', 'password_policy', 'constraint_uppercase');

You instead try to include password_policy/constraint_uppercase.inc which doesn't exist.


Override image dimensions set by image style

You could alter the width and height properties of your image(s) using CSS, it depends on the (base) theme you use in which file these CSS rules should be entered. However, the image produced by the image style is still used (so, this might not be quite mobile friendly).

Another option is to use the Image Style Selector (ISS) module, which provides an extra field on your node edit page that you can use to select an extra image style (to apply on the image on for instance your front page). When displaying the node on the front page you can hide the original image field and display the ISS field (the result is that your image will be shown using the style selected in the ISS field).


How to list blogs by anonymous in blog module

The blog route blog/%user_uid_optional route provided by the blog module performs a few checks in blog_page_user_access():

  // The visitor must be able to access the site's content.
  // For a blog to 'exist' the user must either be able to
  // create new blog entries, or it must have existing posts.
  return $account->uid &&
         user_access('access content') &&
         (user_access('create blog content', $account) ||
          _blog_post_exists($account));

The $account->uid part of the conditional check will preclude access to blog/0 even if anonymous users can create blogs posts.

A module evoking hook_menu_alter() you can override this route behavior by providing your own access callback that excludes the $account->uid check:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog/%user_uid_optional'])) {
    $items['blog/%user_uid_optional']['access callback'] = 'MYMODULE_blog_page_user_access';
  }
}

function MYMODULE_blog_page_user_access($account) {
  return user_access('access content') && (user_access('create blog content', $account) || _blog_post_exists($account));
}


No default selection in a select item on commerce checkout pages using hook_form_alter

The documentation says:

  If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.

So take the default value out and make sure that the form code includes '#required' => TRUE,

I also read somewhere that you must use drupal_get_form() to build the output for a form otherwise the additional form processing functions will not run.  I did not use hook_form_alter() to modify shipping services but instead used hook_commerce_shipping_service_info() in a custom module to give me more flexibility.


It can be done in the views admin interface in the next way:

Exclude existing fields from display
Add new field Global: Custom text
Display new fields in Custom text filed using tokens

See example


How to bulk delete selected content/nodes?

Using the VBO module as suggested in the prior answer is indeed the way to go, BUT ... if you add the Rules module to that also the possibilities for what you can do are virtually only limited by your own imagination. Read on for more details on that ...

Step 1: Create a Rules Component

Have a look at this example of a Rules Component (in Rules export format):

{ "rules_delete_nodes_containing_a_specific_value_in_a_text_field" : {
    "LABEL" : "Delete nodes containing a specific value in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "text_field_value" : { "label" : "Text Field Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[text-field-value:value]"
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "node" ] } },
      { "drupal_message" : { "message" : "Deleted node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022 (which contained the string \u0022[text-field-value:value]\u0022 in field \u0022field_free_format_text\u0022)." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a text field with machine name field_free_format_text.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node identifier and hit the Execute mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be updated.

After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.

Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I used the string "GetRidOfThisNode":

  Deleted node with id "48" and title "Demo field_free_format_text replacement" (which contained the string "GetRidOfThisNode" in field "field_free_format_text").
  Component rule: Delete nodes containing a specific value in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...

Attention: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.

Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

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

Happy VBO-ing while Rules-ing!


You need to change the menu under Structure > Blocks. Find the Main Menu block that is active and click its "Configure" link. The third option is Menu... change this to dropdown to your new-menu.


EntityQuery, query by referenced entity value,

As mentioned here it seems like you only need .entity like this:

->condition('field_category.entity.name', 'somevalue', '=');


How to restrict download file for authentication in drupal

You can try Field Permission Module

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Demo Video


Where to use setTrustedProxies() or how to set new trusted proxies

Drupal doesn't want you to place custom code in index.php to prepare a request before it is handled by the Drupal kernel. So it was made possible for modules to implement a middleware through StackedHttpKernel.

In this case such a middleware already exists, which reads the reverse proxy addresses from settings.php and adds them as trusted proxies to the request:

Drupal\Core\StackMiddleware\ReverseProxyMiddleware::setSettingsOnRequest:

  $proxies = $settings->get('reverse_proxy_addresses', []);
  if (count($proxies) > 0) {
    $request::setTrustedProxies($proxies, Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED);

So you can simply enable this settings in settings.php:

$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['a.b.c.d', ...];


Place op_update_should_be_create-2807275-2.patch into the module folder, in this case being the sites/all/modules/entity folder.

Then in your terminal cd (change directory) into the module folder.

cd /var/www/drupal/sites/all/modules/entity

then

git apply -v op_update_should_be_create-2807275-2.patch

In the discussion, Fago has commited this patch (2 months ago), but into the 7.x-.1.x only.

So I assume you're trying to patch the stable version, 7.x-1.8.

If you use/download the latest dev (7.x-1.x-dev) version, it will already have the patch.

Note: The rule of thumb, is to use the Stable version rather than the Dev version.


How to create a Node Info Bar (or Node Info Block)?

Views module covers pretty much everything you want. You only have have to solve "node views count" somehow (extra field, hidden from display).


If you just want to disable the content filter altogether, you can use:

config.allowedContent = TRUE;

Also, make sure you're clearing your Drupal cache AND browser cache. The CKEditor JS files are heavily cached by the browser and I wasted lots of time banging my head against the wall before I realized this.


How can I create a download link to a private file?

When I add the field 'File: Download link' to the view it works fine.

The views field handler for the 'File: Download link' has this snippet to check access:

if (!file_entity_access('download', $file)) {
   return;
}

and this snippet to construct the uri for the download link:

$uri = file_entity_download_uri($file);

The code for file_entity_download_uri():

function file_entity_download_uri($file) {
  $uri = array(
    'path' => "file/{$file->fid}/download",
    'options' => array(),
  );
  if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
    $uri['options']['query']['token'] = file_entity_get_download_token($file);
  }
  return $uri;
}

show the download token being added to the options query key of $uri which is returned.

Adding that to the PHP code field:

<?php
    $fid = $row->fid;
    $file = file_load($fid);
    if (file_entity_access('download', $file)) {
        $uri = file_entity_download_uri($file);
        print l(t('Download'), $uri['path'], array('query' => $uri['options']['query']));
    }
?>

results in a download link to the private file.


How to format the display of webform_select_options_info to include an image?

Well, I still didn't get a good answer on modifying the syntax here but here is working result. I have a check box, thumb, and title all showing as a list in webform. Still not completely functional as the function doesn't seem to work for anonymous users, although the Flag is anonymous and I'm using sessions.

 <?php
    /**
     * Implements hook_webform_select_options_info().
     */
     function webform_hook_webform_select_options_info() {
       $items = array();
       if (function_exists('webform_hook_user_flag_sample_requests')) {
         $items['webform_hook_user_flag_sample_requests'] = array(
          'title' => t("Sample Requests (User Flag list)"),
          'options callback' => 'webform_hook_user_flag_sample_requests',
         );
       }

       return $items;
     }

     function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
    // dpm($view);
       $options = array();

       if ($view->result) {
     //    $row_class = $view->style_options['row_class'];
     //    $attributes = $row_class ? " class='$row_class'" : '';
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }


Views Related Items Block when Taxonomy term is not on URL

Okay, I spent another day working on this and finally kind of got it working.

The goal here is to create contextual taxonomy filters that will retrieve all products with the same shape AND color as item "ABC123" as displayed on the browser URL, where item ABC123 happens to have a shape of "square" and color of "red".

Getting "square" into the taxonomy filter is easy,

create a view block
add a contextual filter of type "Content: Has taxonomy term ID"
since this is a block with no path, we need to give it a default value, do that and select "Taxonomy ID from URL" and "Load default filter from node page, that's good for related taxonomy blocks"
select the vocabulary you want (in this case "shape")

Now comes the hard part, we need to filter for "color" of item ABC123, but it is not on the browser URL in any shape or form. We need to somehow get the node contents of item ABC123, look into its "color" field, and then scan for all products with that color.

create a 2nd contextual filter of type "Content: Has taxonomy term ID"
click "Provide default value" and select PHP code

$title = arg(2, drupal_get_path_alias()); // arg #2 is title of item on URL
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'product'); // product is the machine name of my content type
->propertyCondition('status', 1)
->propertyCondition('title', $title);
// title is a node property, for other fields use ->fieldCondition

$result = $query->execute();

if (isset($result['node'])) {
$items_nids = array_keys($result['node']);
$items = entity_load('node', $items_nids);
}

reset($items);
$first_item = key($items);

$item = node_load($first_item);

$color = field_get_items('node', $item, 'field_color');
return ($color[0]['tid']);

For "Views Related Items Block", we also need to filter out ABC123, but that is an exercise left for another day.

Please note that this is the very first time I dabble into Drupal API calls, and the code above is clobbered together from various places on line. The code above make some assumptions (e.g. title is unique), is not efficient, may or may not handle translations and may not be totally secure. Reference at your own risk!


How can I theme the Bootstrap base theme search block?

Bootstrap theme is deeply bundled with glyphicons .. it guesses the icon from the button text.

You would need to override Bootstrap::glyphiconFromString() or Bootstrap::glyphicons(). I cannot tell you how to do this in your subtheme ...

If you removed the glyphicons, probably Theme::hasGlyphicons() will return FALSE and won't show any icon.

Workaround

You could replace the icon variable in template_preprocess_input, like:

function MY_TEME_preprocess_input(&$variables) {
  if ($variables['icon']) {
    if (array_key_exists('glyphicon-search', $variables['icon']['#attributes']['class'])) {
     foreach($variables['icon']['#attributes']['class'] as &$sValue)
     {
       if ($sValue == 'glyphicon') {
         $sValue = 'fa';
       }
       if ($sValue == 'glyphicon-search') {
         $sValue = 'fa-search';
       }
     }
    }
  }
}

or, I guess you have asked this question on do: https://www.drupal.org/node/2757463. There is a suggestion of overwriting the Input element:

Create a file at bootstrapsubtheme/src/Plugin/Preprocess/Input.php and add the following:

/**
 * @file
 * Contains \Drupal\bootstrapsubtheme\Plugin\Preprocess\Input.
 */

namespace Drupal\bootstrapsubtheme\Plugin\Preprocess;

use Drupal\bootstrap\Annotation\BootstrapPreprocess;
use Drupal\bootstrap\Utility\Variables;

/**
 * Pre-processes variables for the "input" theme hook.
 *
 * @ingroup theme_preprocess
 *
 * @BootstrapPreprocess("input")
 */
class Input extends \Drupal\bootstrap\Plugin\Preprocess\Input {

  /**
   * {@inheritdoc}
   */
  public function preprocessElement(Variables $variables, $hook, array $info) {
    $element = $variables->element;

    if ($element->icon) {
      $element->icon->replaceClass('glyphicon', 'fa');
      $element->icon->replaceClass('glyphicon-search', 'fa-search');
    }

    // Let bootstrap base theme preprocess the element normally now.
    parent::preprocessElement($variables, $hook, $info);
  }

}


How to create a view returning untranslated entities

I do not think you can filter for untranslated nodes. It is not exactly what you are asking but the way I did it is this:
1. Create a Content View
2. Add the field which can be translated (e.g. Body)
3. Add the field "Entity translation: Body: translated"
4. Choose one language of the translation (e.g. Current User's Language)
5. Click "Rewrite the output of this field" and type "X" in the Text box
6. Click "No results behaviour" and type "-" in the Text box
7. Repeat steps 3 to 6 for other languages if you want to check multiple

This should produce a table with the first column being the source language and the rest of the columns corresponding to the different languages of the translations. When a record has been translated an X will appear, otherwise a - will appear.


How to prevent comment posting when it has specific words in it?

You can try Spam module.

It runs filters on posted content, for example using regexps.

Another way is to write a Rule that examines posted comments and deny them if certain words are found, but unfortunately this module is only available for Drupal 6.

And also you can write a validate function to the comment form, examine the content on submission and use form_set_error if you detect those words. To do this just implemente the hook_form_alter (or the hook form alter with form id), add your valditation function:

$form['#validate'][] = 'you_custom_validate_function';


You can use custom content option in panel to add HTML...

Step 1 : Click on Add Content

Step 2 : Click on New Custom Content

Step 3 : Add HTML and select filter as Custom HTML

Step 4 : Save Changes


Found user with uid of 0 (zero) in users table... huh?

It is normal, as Drupal creates that entry when it is installed, for the anonymous user.  That is done from user_install() (Drupal 7), or system_install(), which contain the following code.

  // Drupal 7.
  // Insert a row for the anonymous user.
  db_insert('users')
    ->fields(array(
    'uid' => 0,
    'name' => '',
    'mail' => '',
  ))
    ->execute();

  // Drupal 6.
  // Inserting uid 0 here confuses MySQL -- the next user might be created as
  // uid 2 which is not what we want. So we insert the first user here, the
  // anonymous user. uid is 1 here for now, but very soon it will be changed
  // to 0.
  db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  // …
  // This sets the above two users uid 0 (anonymous). We avoid an explicit 0
  // otherwise MySQL might insert the next auto_increment value.
  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

That entry is normally used when joining the data contained in the "node" table with the data contained in the "users" table.

Not having that entry would cause Drupal not to work correctly in some circumstances.

If you need to restore the anonymous user data in the database, I would execute code similar to the one executed from Drupal. In particular, for Drupal 6, I would execute the following code.

If the data for the anonymous users already exists in the database, but the user ID is not 0:

db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

If the data for the anonymous user don't exist, even with the wrong user ID:

db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

If you want to automatically restore the anonymous user data, you could implement hook_cron() in a custom module, and execute code similar to the following one. (The code is for Drupal 6.)

function mymodule_cron() {
  $uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", ''));

  if ($uid === FALSE) {
    // The data has not been found in the database; re-create the row.
    db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  }

  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');
}

If you give to the module a lower weight, its implementation of hook_cron() will be executed before the other implementations, and this would avoid they will fail because the missing row in the database.


Add .htaccess file in your drupal folder and the issue with the clean url would be solved.

.htaccess file would look something like

#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value upload_max_filesize 40M
  php_value post_max_size 42M
  php_value default_socket_timeout 600s
  php_value max_execution_time 300s
  php_value max_input_time 600s
  php_value memory_limit 512M
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

Hope that the answer helps you to clean the URL and you wont have to add the query parameter.


mapping of menu Name "Main Menu" with variable name: primary_nav

$primary_nav is template variable in Garland's template.php file. It's a variable specific to this Drupal core theme. The HTML markup is rendered by the theme_links().

The main argument to the theme function is page template variable $main_menu, which is defined in theme.inc. This variable is set by menu_main_menu(), which will retrieve a menu id setting then use that to look up data in the menu_links table (noted by menu_name column).


What I was searching for was:

function THEMENAME_webform_element($variables)

https://drupal.org/node/1157306


Setting a date field via entitity_metadata_wrapper

I was able to get this to work in a roundabout way. I may have been able to accomplish the same thing with time(), but this read better for me as I could follow exactly what I was doing if I ever came back to the code in the future.

// Update the Acceptance Date of Current Agreement.
$acceptance_date = new DateTime(date('Y-m-d 00:00:00'));
$company_wrapper->field_acceptance_date->set($acceptance_date->getTimestamp());


Certainly, just go to the content types display settings, and pick the teaser build mode.
Drag the body to hidden, and set the blurb to be displayed. Done.


Create a node(filedepot folder) after user registers in site

This is how I managed it, and there was one problem regarding permission in folder creation. So I just assigned permission to create folder. and here is the code to create folder during user registration

function modulealter_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'filedepot_folder';
    node_object_prepare($node);
    $node->language = LANGUAGE_NONE;
    $node->uid = $account->uid;
    $node->name = $account->name;
    $node->title = check_plain($account->name);
    $node->filedepot_folder_desc[LANGUAGE_NONE][0]['value'] = 'This is private folder of author user.';
    $node->parentfolder = 4;
    $node->inherit = 0;
    node_save($node);
    watchdog('filedepot',"New folder created @name - new filedepot folder created.", array('@name' => $account->title));
}


How to prevent Cross Site Scripting when input using "Full HTML" mode of CKEditor

See the documentation:

  Finally, it should be obvious that the Full HTML input format, which
  does not use the HTML Filter, is insecure and should be offered only
  to those users who can be trusted not to ruin your site. Most sites
  will be better off deleting this input format.

https://www.drupal.org/node/213156

"A solution that we can encode the output in theme preprocessing hook. But it seems require us to add a lot of codes because our system may have many entity types and fields."

Don't do this in preprocessing. You can configure your own safe text format containing as many text filters as you want. If the built in text filters don't provide the security you need then add a custom filter.

Core ships with Full HTML so that site owners are able to create basic pages in CKEditor using almost all HTML features, which they can do anyway when they have access to the template files.


A view inside another View, updated with AJAX

Views Megarow sounds like it would be ideal for this situation as it opens up a new "accordion" page in the middle of your view like you desire.

You would need to build a new view page / panel page for the parent terms which list the books. This can be done in many ways but I guess a view for /categories/%tid would be the easiest.

The benefit is that you can really do a lot of stuff inside that page.. Blocks / Comments / Multiple Views etc. along with just listing books. If you already have pages for each category, it would be a case of creating a version suitable for loading inside the megarow.

It doesn't close the last category but I guess you could get past that with some basic jQuery.


Way 1: Use drupal template suggestion:

You can enable the template suggestions by following changes as mention in
https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Once you have the suggestions enabled you can see, drupal suggests few template possiblities for any page, you can use any of the suggested template.

https://cl.ly/1f2T0x1a1F2n

Way2: Declare custom template suggestions

Or you can customd define template based on any logic by implmenting hook_theme_suggestions_page_alter().

Example:

https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html


How do I get the raw URL as a field in Views?

As per the comment here http://drupal.org/node/458316#comment-6236984

In views 3.x you can use "Path" field with option "Use absolute link (begins with "http://")" in Rewrite results section.


need popup display of term definition in page contents

Check out the Popups API (Ajax Dialogs) module.


Adding an HTML data attribute to rows in Views

The easiest way that I found to create unique attribute per views row is to override the template file to exclude the outer div and output each row using Global: Custom text in the view excluding from display all fields and including them in the custom text field.

Here is in more detail

go to your view and click Advanced > theme > information
in style output line the bolded file name is the currently used template (let assume views-view-unformatted.tpl.php)
get the name next to the bolded file name (could be something like this views-view-unformatted--VIEWNAME.tpl.php)
copy /all/modules/views/theme/views-view-unformatted.tpl.php to your THEMENAME/views-view-unformatted--VIEWNAME.tpl.php
edit it and modify so it does not output the outer row div. It could look like this for unformatted style

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
    <?php print $row; ?>
<?php endforeach; ?>

edit all view field and check Exclude from display
add Global: Custom text and add all fields in the content using replacement pattern
your outer div in Custom text could look like this

[field_FIELDNAME]

refresh the cache and make sure in steps 1,2, your new template is used


How to run the cron within specified timebound only?

To run cron you have to have something that triggers the cron since php is a scripting language and only fires off when executed. What that means is you either need an outside resources to fire off the cron or you need to set it up server side.  You can set up a cron service on linux by following the guide on Drupal.org. If a scheduled cron task is not set up on the server side or some other mechanism then cron will simply run the next time a user goes to your site. This could have performance issues and unreliable cron runs.

Custom Module

If you don't want your cron task to run every single time cron runs then in your code you would set it up to check the current time and whether or not to run. This would require use of the date functions in php and allow you to decide whether or not to execute your code based off the time

Elysia Cron

Elysia cron will allow you specifically set which cron tasks run at certain times. This will require you to still set up a cron task so that cron can still fire.


How do I remove a node from the front page after a certain period of time?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below. These steps are based on the assumption that your content type is article (adapt to whatever else fits).

Step 1: Create a field to store the expiration date

Add a field to the article content type (to store the "expiration" date), with these specs:

Machine name (say) field_expiration_date.
Use "date" as field type, for which the date module (and data API) needs to be enabled first.
Allow only 1 date.

Step 2: Create a Rules Component

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_unpublish_a_node" : {
    "LABEL" : "Unpublish a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_be_unpublished" : { "label" : "Node to be unpublished", "type" : "node" } },
    "DO" : [ { "node_unpublish" : { "node" : [ "node-to-be-unpublished" ] } } ]
  }
}

If you do not want the node to be unplublished, you can also replace the Rules Action by another one to just perform a "remove sticky" for the node.

Step 3: Create a Rule using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, then "enable" the rule also):

{ "rules_schedule_the_unpublish_of_a_node_as_requested_by_author" : {
    "LABEL" : "Schedule the unpublish of a node as requested by author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_a_node",
          "date" : [ "node:field-expiration-date" ],
          "identifier" : "Unpublish-node-[node:nid]",
          "param_node_to_be_unpublished" : [ "node" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step. Make sure to only perform the import of this rule only after you completed step 1, if not the import will fail ... Should you want to use another machine name, then change field_expiration_date in the rule above to what you prefer, prior to importing this rule.

Be aware: the above rule is only triggered once, i.e. when the node (of type article) is first created (as in the question). It will right away schedule the unpublish of the node (as requested in the expiration date). If the node gets edited later on, and/or the expiration date is changed afterwards: too bad, that won't change anything to when the scheduled unpublish is going to happen.


Filter by content type and shared taxonomy terms

To create the view

Create a view with appropriate fields/whatever.
Add the first argument Node: Type.
Add the second argument Taxonomy: Term.
For the second argument select Transform spaces to dashes in URL.

To create the listing page
Option 1
Bite the bullet and create the page in code. You just need to iterate over the content types and terms, creating the links as you go.
Option 2
Create a normal view that lists the taxonomy terms. Use link rewriting in the view to output a link that's contains the term name and content type, and is easily identifiable. Eg. custom_term_list/news/International Politics. Use custom_url_rewrite_outbound() to translate this to /news/international-politics. Gotta be careful not to slow the site down here.
Option 3
Use a terms as nodes paradigm. (I think this would work.) Create a content type for which each node will refer to a term. This can be done with taxonomy_node, nat (Node Auto Term), or even content_taxonomy (and maybe others for all I know). Add a computed_field that calculates the name of the term with spaces turned to dashes (or whatever). Then it would be easy to make the listing. If you want the node term to be created automatically when a term's created, then you'll need to use one of the first two modules mentioned.
Those are the only approaches I can think of to create listing pages. I think I'd just go for the first one.


How to change an existing theme to a responsive bootstrap theme?

If you want to create a responsive site in drupal with bootstrap.then follow steps:

Install bootstrap theme.(https://www.drupal.org/project/bootstrap).
Copy the bootstrap_subtheme, Place in theme folder and rename with your subtheme.
3.Copy and include the css and js of the existing site to the bootstrap_subtheme.
See the structure of the existing site and create regions in the new theme according  to requirement and apply the css.
Check the section one by one and apply the css according.
Like this you can easily convert the non-responsive site to responsive.

Notes:

You will be create a regions in the tpl.php , this Link will help you.
In this theming there is no that much different to normal theming . if you install bootstrap then it automatically give you the responsive platform, only one difference you can use the bootstrap class in html structure and also use the bootstrap module. Follow This.