correct way to implement multipule users registration form

First you need to use Profile 2 module and create two separate profiles for employee and employer roles.

Then you can use module Auto Assign Role or Profile2 Registration Path to allow users select which role do they want to register with.


How should I define a MENU_LOCAL_ACTION menu item, and which is the involved page callback?

Router items can inherit properties from parent paths.

In this case, the page callback is inherited from the 'admin/people' path:

$items['admin/people'] = array(
  'title' => 'People',
  'description' => 'Manage user accounts, roles, and permissions.',
  'page callback' => 'user_admin',
  'page arguments' => array('list'),
  'access arguments' => array('administer users'),
  'position' => 'left',
  'weight' => -4,
  'file' => 'user.admin.inc',
);

The fact that the menu item is a MENU_LOCAL_ACTION doesn't actually come into it, the same is true of any type of item.

So if you define a router item like this:

$items['mymodule/path'] = array(
  'title' => 'Something',
  'page callback' => 'mymodule_page_callback',
  'access callback' => 'mymodule_access_callback',
);

And then define one like this:

$items['mymodule/path/sub-path'] = array(
  'title' => 'Something',
  'type' => MENU_LOCAL_ACTION,
  'access callback' => 'mymodule_access_callback',
);

The page callback will be inherited from the 'parent' item.


Adding more fields to the registration process

Since D7, field management is included in the core. Almost every kind of content has now the ability to be managed with fields.

You can go to admin/config/people/accounts/fields to manage user fields. There is also a tab for managing the display.


Well, you didn't write the required version. I found a module Ecwid shopping cart. This module has drag and drop features for items and ajax support everywhere.

For more information, have a look at Ecwid Demo.


Not able to see < character in front end

At the end, I found a work around for the problem. In the word link configuration form we can find a "Disallowed html tags" input text box. We can add a  tag there, so now, whenever I want to include the < character in my text, I wrapp the  tag around it.

I know it is not the cleanest solution but it is enough to keep going until they fix the module.

Hope it can help to someone else.


Renaming a Drupal feature requires additional steps than rename a custom module.

Solution 1 (without un/install)

Backup the DB.
Put the site on maintenance mode.
Rename the feature with an IDE or bash script (don't access/edit any content of the site while you are doing this).
Run:

drush php-eval 'registry_rebuild();'
drush updb -n. (forces drupal to reload caches related to module/features)
drush cc all

Solution 2 (more proved but requires un/install)

Backup the DB.
Follow the steps to rename the feature on this thread.

To replace the new name (the human and the machine name) on each file, I suggest you to use an IDE like NetBeans (or similar).

You can also use cool unix commands like sed and find to do it.

Try to make a code review after the changes to make sure that the rename was done on the right places.

Note: to make sure that the name I choose for a module/feature is not already used, I use the following command:

drush pm-list --type=Module --no-core --status=enabled --pipe | sort


How to get search to display an error when no search terms are entered

The form submission callback for the search form is the following function.

function search_form_submit($form, &$form_state) {
  $keys = $form_state['values']['processed_keys'];
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    // Fall through to the drupal_goto() call.
  }

  $type = $form_state['values']['module'] ? $form_state['values']['module'] : 'node';
  $form_state['redirect'] = 'search/' . $type . '/' . $keys;
  return;
}

If, when you don't enter anything, Drupal searches for search, there must be a module that alter the content of $form_state['values']['processed_keys'] when it is an empty string.


Is it possible to override a core function instead of just altering it?

Personally I would make an inheritance from this core plugin, extend it in my own class (classes), and change in the views to use my custom plugin.


Get results from content indexed from other site with search api

My guess is that you will not be able to do this with the standard search view process.  I believe that views does some linking of results to content that exists on the site.  So remote content will be filtered out.

That said, you can get what you want if you use the native Solr query requests.  These return the raw json (or xml) data from the server.  You can use this with custom code to display your results.

See the solr tutorial on how to create queries.

A site I used to manage used this with Angular.js to manage some really complex searches.


Groups audience list shows NONE in Organic Group module

I just changed the following to get my work Admin -> structure -> content type -> custom content type(i.e. Opinion) -> manage fields -> changed the WIDGET name to Select list of the field name having FIELD TYPE as Entity Reference


Node Referenced entity fields not showing in views?

For displaying the authors details within a Twig template see How can you render fields from an entity reference in node templates? [Drupal 8] - for creating a views block this page might help you: https://www.drupal.org/node/1841004


The 'Type' corresponds to the database table used for queries. This option creates the 'FROM' part of the SQL query. That is really the only part of a view that cannot be easily changed after the initial creation.

See https://www.drupal.org/node/2287909 for some more information about the basics of Views 3.


When two rules attempt a page redirect, which will actually happen?

try changing the order (weight) of each rule under its settings:

Weight

Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight.

EDIT:
it's a little convoluted, but you could create a temporary variable within the node to control things - for example, a hidden boolean field or flag that is changed to true when editing - the rule checks for this as a Data Comparison in a condition. Have the change field and redirect Rule set the boolean but not redirect, then create two rules on save - one if the field is set, and one if the field is not. For the rule if the field is set, then add an action that resets the fields value.


How to get these content types to appear in my view based on role?

You'll need to add a restrictions in your views. There's an access restriction section there where you can set it by role. Select which roles can view it, then save. That should work. Please refer to the picture attached where to find the permission access. Also, try Content Access module to restrict content type per role.


Why not all menus are available in context settings page?

In the context module, blocks in the Blocks reaction are grouped by the module that creates them. In this case, it is the System module that provides the Main Menu that you're looking for.


Author Fields into a content type template

Should I use include for this use case or not ?

This is not possible, you can't mix different templates like node and field because they have different variables.

  If I have too, what I'm doing wrong ? Why the item.content is not been
  load ?

item.content is only loaded in field, not in node template.

  If I should not use it in this use case, what should I do instead ?

You should define the user field you need in preprocess, examples for the two fields already defined:

function template_preprocess_node(&$variables) {
  $variables['author_name'] = drupal_render($variables['elements']['uid']);
  $variables['author_picture'] = user_view($node->getOwner(), 'compact');

A basic example to use this in your own hook:

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['user_field1'] = $node->getOwner()->field_field1->value;

And in twig

{{ user_field1 }}


write code in your module like this way.

Declaring the block

function mymodule_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current posts'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

Retrieving data

    function mymodule_contents(){
      $query = db_select('challenges','c')
$query = db_select('challenges','c');
$query->join('node','n','n.nid = c.cid');
$query->join('field_data_body','f','n.nid = f.entity_id');
$query->join('field_data_field_challenge_pic', 'fp','n.nid = fp.entity_id');
$query->join('file_managed','fm','fp.field_challenge_pic_fid = fm.fid');
$query->fields('n',array('nid','title','created'))
      ->field('f',array('f','body_value'))
      ->field('fp',array('fm','uri'))
      ->condition('c.cid','$user->uid','=')
        ->execute();
      return $query;
    }

Generating block content

function mymodule_block_view($delta = '') {
  switch($delta){
    case 'current_posts':
      $block['subject'] = t('Posts');
      if(user_access('access content')){
        //Use our custom function to retrieve data.
        $result = mymodule_contents();
        //Array to contain items for the block to render.
        $items = array();
        //Iterate over the resultset and format as links.
        foreach ($result as $post){
          print $post;
        }

        if (empty($items)) { //No content in the last week.
          $block['content'] = t('No posts available.');
        }
        else {
          //Pass data through theme function.
          $block['content'] = theme('item_list', array(
            'items' => $items));
        }
      }
    return $block;
  }

}


Including JS files in template.php to control weight/order/group

You can try JS injector module which provides an UI for that


Alphabetical sorting of terms (not using a view)

The easiest way indeed is using views.

If you really don't like to do so, you could create a custom module, implement hook_menu_alter() to alter the page callback of the taxonomy page:

/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] => 'MYMODULE_my_taxonomy_page';
  }
}

Then write your own version of the taxonomy module's function taxonomy_term_page($term) (using the above example, you would call it MYMODULE_my_taxonomy_page).

Within this function you can alter the call of taxonomy_select_nodes and add a fourth parameter, specifying the desired sort order:

$order = array('t.title' => 'ASC')

Note that this is working only, if you did not use a field replacement for the title property (e.g. using the title module). Then you would have to write an own version of the taxonomy_select_nodes function as well.


How do I prevent Drupal from sending an email to the admin every time a new user is created

Do the email sent to the admin have the link to activate the user's account?

If so, go to: example.com/admin/config/people/accounts

Check the REGISTRATION AND CANCELLATION paragraph (should be the 2°): if Visitors, but administrator approval is required is checked, every time a user create an account an email is sent to the admin to let him approve/refuse the user new account.


How to get search results sorted by language in solr?

You could build your search with the apachesolr_views module (https://www.drupal.org/project/apachesolr_views), allow all languages and then group by language in the view.


Prevent cron from flushing the cache indiscriminately?

The cache is flushed by the system_cron() module, so basically the only way to stop it happening is to hack the core system module (very bad), or use something like Elysia Cron to schedule that particular cron job to run on a slower schedule. One of the module's features is:

  Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.

It's worth bearing in mind that system_cron() performs some other tasks as well (cleaning up deleted files, clearing the queue and batch tables, etc.), so using this method will slow down those tasks too.

Although it's a bit long winded, and not very future-proof, perhaps the only way to get to a satisfactory solution would be to implement a cron hook in your own module, which performs the tasks of system_cron() minus the cache flush. Then you can schedule the system_cron() to run on a slower schedule that suits your caching needs.


How do I interpret the line of codes ( \ No newline at end of file) and (+ - core/jquery.once)

The message "No newline at end of file" is a warning GIT throws up when there is not a newline as the last line in a file. You can solve this by adding a newline at the very end of the file.


Programmatically customise fields in node views

I want to share the solution I found, in order to help future readers.

In Drupal 7 the concept of "formatter" helpt to control the output of a field. For example this tutorial allow you to programmatically define a custom formatter for a given field.

Then by UI site admins (by admin/structure/types/manage/<nodetype-name>/display) are able to chose that formatter (or others) for any specific field.

If you want to declare a default formatter for a field, the best way seems to be while the install phase of the module.
In that moment (At least in my case and in all tutorial I found on the Internet) you use a field_create_instance method to add a specific instance of a given field. According to the official documentation, you can also add the display options that exactly allow you to define the formatter to be used for a specific display (or the formatters if want to declare for more than one display).


Try $store=$_GET['catid']; instead as PHP is case-sensitive.


How can I monitor for bot accounts accessing drupal paths without permission?

You could try adding bot protection to your registration form,

e.g with reCaptcha

Other worthwhile things are blocking the bots in your webserver,

e.g nginx

https://github.com/mariusv/nginx-badbot-blocker or
https://github.com/oohnoitz/nginx-blacklist/blob/master/blacklist.conf

Custom options include using the Flood control API,

e.g flood_is_allowed and flood_register_event with ip blocking (e.g system_ip_blocking_form_submit) or user_block_user_action on the node/add or 403 page.


How to set multiple values to an unlimited Term Refence field with Rules

Part 1: Understanding the problem

Your action Set a data value can only set 1 value, which explains what you currently experience, i.e the last one.

Try to replace that action with an action "Add an item to a list".
When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

However, you also have to add a prior action like "Fetch entity by ID", before this "Add an item to a list".

For more details, have a look at the tutorial "Lists and loops", starting from around 9:00.

Part 2: Fixing the problem

Below are more detailed instructions, where appropriate with references to the equivalent that is shown in that video. And a corrected Rule and Rules Component (in Rules export format).

Step 1: Simplify the Rule

In the Rule that calls your Rules Component, apply these changes:

Delete all Rules Actions you had added (sorry ...).
Only add 1 action, which is to invoke the Rules Component with 2 appropriate parameters, i.e.:

for Node(s) from Entity Reference use node:field-reference as its data selector
for List of Allergens from Ingredients use node:field-allergens as its data selector.

Here is an export of what I recommend as your (corrected) Rule:

{ "rules_copy_all_terms_to_another_node" : {
    "LABEL" : "Copy all terms to another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "ingredients" : "ingredients" } }
        }
      }
    ],
    "DO" : [
      { "component_rules_add_a_term_to_a_node" : {
          "node_referenced" : [ "node:field-reference" ],
          "list_of_allergens_terms" : [ "node:field-allergens" ]
        }
      }
    ]
  }
}

Step 2: Rework the Rules Component

In your Rules Component, apply these changes:

Remove the action to "Set a data value" (we'll use Rules Action "Add an item to a list" instead, as detailed below).
The 2 parms you passed to the Rules Components seem OK (I just slightly renamed them to improve readability).
Add a loop, to iterate over each term contained in the list of terms (which is passed as a parameter), and add the extra Action for each item in this loop, like so:

Add an action Fetch entity by ID, whereas you want to fetch (= load) a taxonomy term, similar to what is shown in the video around 10:40. And the ID of what you want to fetch is the 2nd parm of your Rules Component, followed by ":tid", similar to what is shown in the video around 10:50, though your Rules Component should use "data selection" to select your 2nd parm (the video just uses a data identifier of "1"). Make sure to remember what you use as variable name here similar to what is shown in the video around 11:20, let's assume you name it "(allergens_term_fetched".
Add an action to Add an item to a list, similar to what is shown in the video around 11:40. The data list to which an item is to be added in your case is node-referenced:field-allergens (instead of node:field-tags as shown in the video). While doing so, the next thing is similar to what is shown in the video around 12:00: the "item to add" should be "(allergens-term-fetched" (if you used that name I suggested). You probably also want to check the "enforce uniqueness" (see video around 12:40, though the video does not check it), and for "insert position" I'd use "append the item to the end" (see video around 12:55).

Note: the Rules Condition in your Rules Component is fine (and also similar to what is shown in the video), no changes needed to that.

Here is an export of what I recommend as your (corrected) Rules Component:

{ "rules_add_a_term_to_a_node" : {
    "LABEL" : "Add a term to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_referenced" : { "label" : "Node(s) from Entity Reference", "type" : "node" },
      "list_of_allergens_terms" : {
        "label" : "List of Allergens from Ingredients",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-referenced" ],
          "type" : { "value" : { "recipe_sheets" : "recipe_sheets" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "list-of-allergens-terms" ] },
          "ITEM" : { "next_allergens_term" : "Next Allergens term" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "next-allergens-term:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "allergens_term_fetched" : "Fetched Allergens term" } }
              }
            },
            { "list_add" : {
                "list" : [ "node-referenced:field-allergens" ],
                "item" : [ "allergens-term-fetched" ],
                "unique" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

Step 3: Time for QA-testing

Only believe what you've seen with your own eyes ... So use the Rules UI to import my corrected Rule and Rules Component. If you didn't do so yet, make sure you have a content type with the same machine name ingredients (doesn't matter what the content type of the entity referenced node is). And also make sure both content types have a term reference with machine name allergens. If the import fails, it must be because those machine names don't match, or the fields are missing (so fix that and retry the import).

After the import completed, and you have at least 1 node of each type (with an entity reference), it's Party Time ... Make sure your taxonomy terms include terms like salt, pepper, strawberries, bananas, whatever.

FYI: in my experimental setup, the combination of the above Rule and Rules Component seemed to work as requested in the question here ... one of my terms for testing was ... Champagne.

Voilà ... No custom code, sweat, no?


Calendar - Non repeating events displaying in multiple months, how to fix it?

It would be a guess as its hard to say without more details but its most likely to do with contextual filters not set up correctly. For month I have them set up as follows:

Provide default value: current date
Granularity: month
Dates to compare: Start/End date range
Add multiple value identifier: Yes
Content: Dates - start date (field_event_date)
Method: OR

For week its exactly the same except using week granularity and so on for days and years. Make sure you dont have any other calendar views (even disabled ones were playing tricks on me before). Also make sure your sort is based on the same date field as the contextual filter.


Sorting in views not working for drupal commerce products

This isn't working as configured because you're using separate product reference fields per content type. This instructs the query to attempt a sort based on non-existent values for those rows where the content type does not have the expected reference field. To sort this View properly, you'd need the base table to be the Products and then some sort of a reverse reference to content referencing those products.


How to easily display a 12 by 12 matrix of input field for integers?

Might be worth trying CCK table field or Table Field

Both seem to do a very similar function, I would give them both a try on a local dev environment


What this is is an autocomplete field. My guess is if you want to recreate it for another field within the same module then you will indeed need to hack Location module. You'll want to look at the autocomplete callback for the state/province field as well as the autocomplete properties set on the field itself.

However, this may be difficult to do with cities, which is probably why it hasn't been done in Location. If you want to an autocomplete field for cities that actually adheres to the cities wiin a state/province, or even if it doesn't adhere, it will require a full list of cities within each state/province. That's a pretty hefty task if you ask me, but it certainly isn't impossible. I would check around the Location issue queue to see if this has been discussed before. Maybe you can gain information on why it was never done and what the drawbacks may be to developing this.


Node body not preserving HTML formatting?

Your input format is likely "Filtered HTML", or something other than "Full HTML". Check the input format (below the body textarea when editing the node).


In Drupal 7, teaser view doesn't show the image filed because the image filed in the content type can have multiple images?

The Display Suite Module offers you to choose the number of items to show on each viewmode.


Creating a fallback field to load conditionally

If field_secondary is also an image field, then you can check if it is empty in your Twig template:
For example, in node--article.html.twig:
{% if content.field_secondary is empty %}
  {{ content.field_image }}
{% else %}
  {{ content.field_secondary }}
  {{ content.field_image }}
{% endif %}

{{ content.without('field_image', 'field_secondary') }}

(Your actual template will have more HTML in it.)


In your theme_preprocess_page function use this

drupal_add_library('system', 'ui.tabs');

Here is a list of all the libraries for 'system' https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_library/7


Webform validation are working but they some error

This line:

if($form_id)

is doing nothing. Form ID is never something that will be considered FALSE. PHP Manual says:

  When converting to boolean, the following values are considered FALSE:

  the boolean FALSE itself
  the integer 0 (zero)
  the float 0.0 (zero)
  the empty string, and the string "0"
  an array with zero elements
  an object with zero member variables (PHP 4 only)
  the special type NULL (including unset variables)
  SimpleXML objects created from empty tags

Form ID is a string, name of a function really, and as such can never be empty or "0".

This means your function always enters the code block under if, and appends your validator to all forms. Most forms does not have submitted index defined, hence warning.

You probably wanted something like

if($form_id == 'some_form_ID_you_know_and_I_do_not')

and in validator something like

if( isset($form_state['values']['submitted']) and !empty($form_state['values']['submitted']['title']) ){


If you are in Drupal 7, all you need is using Link and Linked field modules


WSOD for logged users after upgrading some module

go into you database, set the status to 0 on the rows for each of the modules you mentioned. Reinstall each module one by one to find the problem module.

you could also try adding this to the top of index.php (remember to remove it later)

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);


Yes, it is best to disable this in production for the performance reasons mentioned.

I think the only times you would want to rebuild the feature list is when you are using the features and/or modules lists (as designed). Spending the resources to reload that when clearing cache for themeing purposes would be unnecessary.


How to redirect user after submitting an article?

Yes, form_alter and a custom submit handler was the solution.

function _custom_admin_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = '_custom_admin_article_form_submit';
    }
  }
}

function _custom_admin_article_form_submit($form, FormStateInterface $form_state) {
  drupal_set_message(t('Thank you for submitting an article.'));

  $url = Url::fromRoute('<front>');
  $form_state->setRedirectUrl($url);
}


Drupal put more values in #markup $form type

The #markup property simply provides a string output.

Why dont you just concatenate your output into a variable.

$output = $image;
$output .= $link;

Then...

'#markup' => $output

Checkout the coding standards for Drupal around concatenation.
https://www.drupal.org/coding-standards#concat


Drupal 7: check login password with DB password

You can tweak the existing user login form by implementing hook_form_alter or one of its friends (see link). It allows you to add your own password validation functions.

If you don't know which form ID to use, you can add this code to a custom module to get all used form ids printed out:

mymodule_form_alter(&$form, &$form_state, $form_id) {
    dpm($form_id);
}

You need the Devel module, and appropriate permissions to see the output of dpm().

But there's more. You have to think about password changes, password retrieval, account creation, etc. To let users log in (with your own password check) you need to have a valid Drupal user account for every user. It's not enough to just validate the password against your own database. A possibility would be creating the user accounts in the background once the password check was positive.

A completely different approach: Import your existing users into the Drupal users table, and let them know they have to go through password retrieval.


I finally had time to make a custom module for that: ctool_views_extender

In your MODULE.module:

<?php

use Drupal\views\Plugin\views\display\Block as CoreBlock;
use Drupal\MODULE\Plugin\Display\Block;

/**
 * Implements hook_views_plugins_display_alter().
 */
function MODULE_views_plugins_display_alter(&$displays) {
  if (!empty($displays['block']['class'])) {
    $displays['block']['class'] = Block::class;
  }
}

In src/Plugin/Display/Block.php:

<?php
/**
 * @file
 * Contains \Drupal\MODULE\Plugin\Display\Block.
 */

namespace Drupal\MODULE\Plugin\Display;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Drupal\ctools_views\Plugin\Display\Block as CtoolsBlock;

/**
 * Provides a Block display plugin that allows for greater control over Views
 * block settings.
 */
class Block extends CtoolsBlock {

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);
    $filtered_allow = array_filter($this->getOption('allow'));
    $filter_options = [
      'background' => $this->t('Background')
    ];
    $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

    $options['allow'] = array(
      'category' => 'block',
      'title' => $this->t('Allow settings'),
      'value' => empty($filtered_allow) ? $this->t('None') : implode(', ', $filter_intersect),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $options = $form['allow']['#options'];
    $options['background'] = $this->t('Background');
    $form['allow']['#options'] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
    $form = parent::blockForm($block, $form, $form_state);

    $allow_settings = array_filter($this->getOption('allow'));
    $block_configuration = $block->getConfiguration();

    if(!empty($allow_settings['background'])){
      $form['override']['background'] = array(
        '#type' => 'managed_file',
        '#title' => $this->t('Background'),
        '#description' => $this->t('Enter background image'),
        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
        '#upload_location' => 'public://backgrounds'
      );
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
    // Set default value for items_per_page if left blank.
    if (empty($form_state->getValue(array('override', 'items_per_page')))) {
      $form_state->setValue(array('override', 'items_per_page'), "none");
    }

    parent::blockSubmit($block, $form, $form_state);
    $configuration = $block->getConfiguration();
    $allow_settings = array_filter($this->getOption('allow'));

    if (!empty($allow_settings['background'])) {
        $background = $form_state->getValue(['override', 'background']);
        $configuration['background'] = $background;
        // fix bug in Drupal which does not put the image as permanent
        $fid = $form_state->getValue(['override', 'background'])[0];
        /** @var \Drupal\file\Entity\File $file */
        $file = \Drupal\file\Entity\File::load($fid);
        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'ctools_views', 'image', 1);
    }

    $block->setConfiguration($configuration);
  }
}

Then all you need to do is output it in a twig template. I use another module that I made to simplify things (get_url_from_fid on github or How to get path of image from file id on SE)

{% set background = '' %}
{% if configuration.background.0 %}
  {% set background = 'background-image: url(' ~     get_url_from_fid(configuration.background.0) ~ ')' %}
{% endif %}

<div{{ attributes.addClass(classes) }} style="{{ background }}">

Cheers!


How to publish content based on a Date field in custom content type in Drupal 7?

There is a patch to make the Scheduler "Publish On" date render itself as a field: http://drupal.org/node/1203958

This presents a new Checkbox called "Show Scheduling options in vertical tabs", which you can uncheck to display as a field.  Then you give it some weight so it shows up where you want it to.

It's been working for me in production for a month or so.

EDIT: Here's a better way to make this happen with both Scheduler and Rules.

Create a Rule, "After saving new content"
Add a condition of "Content is of type"
Add an "Execute PHP" action with this:

$node->publish_on = strtotime("[node:field-datefield-here]");
scheduler_node_insert($node)
Create a Rule, "After updating existing content"
Add a condition of "Content is of type"
Add an "Execute PHP" action with this:

$node->publish_on = strtotime("[node:field-datefield-here]");
scheduler_node_update($node);


Validate CCK field to not allow links/URLs

Ok, So I have worked out how to do this.

First install the Field validation module.

Then go to the 'manage fields' page for your content type. To the right of each field is a 'validate' link. Click on validate for the field you wish to add validation for.

Click 'PHP code' and note the 'Be careful, it is powerful and also dangerous.' warning!

Enter a rule name such as 'dont allow URLs'.

In the PHP code box enter the php you wish to validate. I made an array of all the the top level domains etc I didn't want users to use, and checked the input against this in a foreach loop. The code I used to do this is:

$mystring = $this->value;
$arr = array("http", "https", "www", ".com", ".org", ".net", ".info", ".mil", ".mobi", ".edu", ".gov",  ".biz", ".ac", ".ad", ".ae", ".af", ".ai", ".al", ".am", ".ao", ".aq", ".ar", ".as", ".at", ".au", ".aw", ".ax", ".az", ".ba", ".bb", ".bd", ".be", ".bf", ".bg", ".bh", ".bi", ".bj", ".bm", ".bn", ".bo", ".br", ".bs", ".bt", ".bw", ".by", ".bz", ".ca", ".cc", ".cd", ".cf", ".cg", ".ch", ".ci", ".ck", ".cl", ".cm", ".cn", ".co", ".cr", ".cu", ".cv", ".cw", ".cx", ".cy", ".cz", ".de", ".dj", ".dk", ".dm", ".do", ".dz", ".ec", ".ee", ".eg", ".er", ".es", ".et", ".eu", ".fi", ".fj", ".fk", ".fm", ".fo", ".fr", ".ga", ".gd", ".ge", ".gf", ".gg", ".gh", ".gi", ".gl", ".gm", ".gn", ".gp", ".gq", ".gr", ".gs", ".gt", ".gu", ".gw", ".gy", ".hk", ".hm", ".hn", ".hr", ".ht", ".hu", ".id", ".ie", ".il", ".im", ".in", ".io", ".iq", ".ir", ".is", ".it", ".je", ".jm", ".jo", ".jp", ".ke", ".kg", ".kh", ".ki", ".km", ".kn", ".kp", ".kr", ".kw", ".ky", ".kz", ".la", ".lb", ".lc", ".li", ".lk", ".lr", ".ls", ".lt", ".lu", ".lv", ".ly", ".ma", ".mc", ".md", ".me", ".mh", ".mk", ".ml", ".mn", ".mo", ".mp", ".mq", ".mr", ".ms", ".mt", ".mu", ".mv", ".mw", ".mx", ".my", ".mz", ".na", ".nc", ".ne", ".nf", ".ng", ".ni", ".nl", ".no", ".np", ".nr", ".nu", ".nz", ".om", ".pa", ".pe", ".pf", ".pg", ".ph", ".pk", ".pl", ".pm", ".pn", ".pr", ".ps", ".pt", ".pw", ".py", ".qa", ".re", ".ro", ".rs", ".ru", ".rw", ".sa", ".sb", ".sc", ".sd", ".se", ".sg", ".sh", ".si", ".sk", ".sl", ".sm", ".sn", ".sp", ".sr", ".ss", ".st", ".sv", ".su", ".sx", ".sy", ".sz", ".tc", ".td", ".tf", ".tg", ".th", ".tj", ".tk", ".tl", ".tm", ".tn", ".to", ".tr", ".tt", ".tv", ".tw", ".tz", ".ua", ".ug", ".uk", ".us", ".uy", ".uz", ".va", ".vc", ".ve", ".vg", ".vi", ".vn", ".vu", ".wf", ".ws", ".ye", ".za", ".zm", ".zw", ".name", ".pro", ".aero", ".asia", ".cat", ".coop", ".jobs", ".museum", ".tel", ".travel");
    foreach ($arr as &$findme) {
           $value = strpos($mystring, $findme);
           if ($value === false) {
           } else {
               $this->set_error();
           }
    }

Check the tick box that says 'Set errors using field API'

In the last text box you add your custom error message. E.g.

Please remove all links/URLs for example: 'www', '.co.uk'& '.com'. Please check that you have a space after each full stop.

I hope that this helps somebody else.


who is responsible for printing [safe_value]

To augment MZ's answer, while a node_load() will load the node, a node_build_content() is required to get all these extra types of fields.  In this case, that would be the Field Module's Text Module that creates this sanitized field based upon the filter in use on that field.


How to Add Block with Page on the same view?

In Views, click on +Add button and select Attachment. (This part is optional, if you have a view block already created you can just attach that).

Make your attachment look like your block.

Now go to your page view in the FOOTER add Global: View area and select your attachment or block.


I believe the problem is that you are using the sample phpunit.xml.dist instead of copying it to phpunit.xml and then making a few teaks for your installation.
Part of the phpunit.xml file is setting up the autoloader to find test classes and modules (they are not in the normal autoloader). And you tend to get some really weird errors if you don't set up the DSN for the database (to run Kernel and Functional tests).
I would do the following (adjust paths as needed ; I'm looking at a core-dev project right now and not a live site).

In your install, do composer require --dev drupal/core-dev:~9.1.0. You may want to tweak the version number, depending on you you have core defined.
Make sure you are running the binary from vendor/bin in your install.  I suggest looking into direnv.
Copy phpunit.xml.dist to phpunit.xml and edit

SIMPLETEST_BASE_URL
SIMPLETEST_DB
BROWSERTEST_OUTPUT_DIRECTORY
to reflect your installation.

Then cd to core, and run
../vendor/bin/phpunit -c phpunit.xml --testsuite unit

This should start to loop through the Unit tests. Abort that if they look like they are working, and then do
../vendor/bin/phpunit -c phpunit.xml --testsuite kernel

Then, if that looks OK you can start to run your own tests.
All of that said, it is much easier to run individual tests through PhpStorm. You just need to got through the preferences to point to the right PHP interpreter, and set a few things for phpunit.
In your case, it may be better to just start the drupal:9.1.0 container, and then shell into it for initial testing before updating the Dockerfile.


You can use the following code.

foreach($field_groups as $field_group){
    ctools_export_crud_enable('field_group',$field_group->identifier);
}


How can the Feeds module fetch a file from a dynamic URL?

As I know Feeds doesn't have something like that, its maybe a feature that you can propose on they issue list.

A workaround its to create a small module that will work as a proxy for your dynamic address.

You will have something like that :

<?php

function proxy_menu() {
  $items = array();
  $items['proxy-url'] = array(
    'title' => 'Proxy for danymic url',
    'page callback' => 'proxy_get_contents',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return  $items;
}

function proxy_get_contents() {
  $url = 'http://www.example.com/report/%start-date%/%end-date%';
  $request = drupal_http_request($url);
  if ($request->code == 301 || $request->code == 304) {
    return $request->data;
  }
}


$image = array(
  '#theme' => 'image_formatter',
  '#image_style' => 'thumbnail',
  '#item' => array(
    'uri' => $user->picture->uri,
    'alt' => '',
    'title' => '',
  ),
);
$block['image'] = $image;


Internal relative links in Menu by using http:/alias/path/to/link

You should be able to go to /admin/structure/menu, select the menu you wish to add the link to, and list links. At the top select Add link and enter the title and link. You can use either the alias or system path. Then on the list, place the new menu item where you want it. It should not overwrite the existing menu entry.

Do not prefix the links with http:.


Using jQuery from Google CDN doesn't work

In Drupal 6, you cannot use drupal_add_js to add external JS files. You need to use drupal_set_html_head. Thankfully, in D7 this has been fixed.

drupal_set_html_head('<script type="javascript" src="https://www.google.com/jsapi?key=my site"></script>');
drupal_add_js('google.load("jquery", "1.6.4"); google.load("jqueryui", "1.8.16");', 'inline');


It can be done this way, i don't see any reason to to use each() function.

 $(document).ready(function(){
        $('.Testimonials').text('sample text '+$(this).text());

      }); // END doc ready

It will add text before each element having class Testimonials.


Drupal CSS broken in Internet Explorer 7/8, but works as static page

Do you have CSS and Javascript caching enables? IE7 & IE8 can only load a certain amount of external files and you maybe exceeding the limit. Retry with CSS and JS caching enabled.


A similar situation was encountered by a user who reported that clearing his browser cookies solved the problem.


Term translations not working as View's path contextual filter

Implementing hook_language_switch_links_alter() is definitely the way to go.  Here is the code along with two (2) helper functions, assuming there are display variants for each language.

/**
 * Implements hook_language_switch_links_alter().
 *
 * This is a workaround for Path Translation not supporting Views' contextual filters.
 * Alter the language switcher to switch between path/to/[term] and different
 * paths for different languages.
 */
function mymodule_language_switch_links_alter(array &$links, $type, $path) {

  // Load the current view if there is one.
  $view = views_get_page_view();

  // Act only if we're looking at the view in question.
  if (($type == "language_content") && isset($view) && ($view->name == 'myview')) {

    // Skip situations where there's no argument.  This is handled by Path Translatoon.
    if (isset($view->args[0]) && ($view->args[0] != mymodule_get_myview_view_all_term($view))) {

      // Iterate across all language links.
      $language_active = $GLOBALS['language']->language;
      $displays = mymodule_get_myview_view_language_displays();
      foreach ($links as $language_current => &$link) {

        // Skip the active language.
        if ($language_current == $language_active) {
          continue;
        }

        // Set the path for the current language.
        $path = $view->display[$displays[$language_current]]->display_options['path'];
        $link['href'] = strtok($path, '/') . '/' . $view->args[0];
      }
      // Break the foreach reference.
      unset($link);
    }
  }
}

/**
 * Returns the list of displays for the view in question, keyed by language.
 *
 * @return array
 *   The list of displays.
 */
function mymodule_get_myview_view_language_displays() {
  return array(
    'en' => 'page_myview_en',
    'fr' => 'page_myview_fr',
  );
}

/**
 * Get the language-specific term representing all items.
 *
 * @param view $view
 *   The previously loaded view in question.  Optional.
 * @return string
 *   The term.  If there's no translation in the current language, "all" is used.
 */
function mymodule_get_myview_view_all_term($view = NULL) {

  // Load the view if it wasn't provided.
  $view = (is_null($view) ? views_get_view('myview') : $view);

  // Get the current language and the display names for each defined language.
  $language = $GLOBALS['language']->language;
  $displays = mymodule_get_myview_view_language_displays();

  // Return the language's "all" term, or the default if there isn't one.
  if (isset($view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'])) {
    return $view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'];
  }
  else {
    return 'all';
  }
}

Note that this doesn't handle the translation of the term itself within the path, only the part of the path leading up to it.  For now, that will always be in the default language. This is the separate issue Views contextual filter validation: Support ET-translated taxonomy term name.


"languages" is not found in regional settings

You're misreading the instructions (they're correct) and as a result, you're looking in the wrong place.  It is not in "Regional settings".

Start by clicking on "Configuration" on the admin toolbar. Then scroll down the page until you see a box with the heading "Regional and language".  Inside that box, below "Regional settings", you should see the link to "Languages"


You seem to me trying to make it more complicated as necessary. You can simply use the arg function http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7

in your example domain http://domain.example/community/communityname

arg(0) = community;

arg(1) = communityname;

so why not just use arg(0) and arg(1) in your dynamic link url


How can I run PHP code without writing a module?

Yes, there is, but given your description I wonder if it will help you:

Install module Devel
Go to http://yoursite/devel/php
Enter your code and execute it.


dropdown menu doesn't always show up in corporateclean

I see, where the problem is. In the parent menu you also have to select "show as expanded" option to display the child menu in drop down or whatever configuration you have.

Steps (if you may need):

Goto Structure->Menus
Select the Menu and click list links
Find the parent menu and edit it
Inside that you will have option to choose "show as expanded", Check that
Clear the cache and you are good to go.


You should do like this

$format = db_result(db_query("SELECT format FROM {filter_formats}
                              WHERE name = 'Messaging plain text';"));
$content .= check_markup($node->title, $format);

The problem is that you need to use the format id not the format name.


Alternative Top Menu bar for logged in users only via their Role

When you create a menu, a block should be created at the same time (https://drupal.org/taxonomy/term/32478). Go to Admin, Structures, Blocks and place one of those menus in the area you want it to appear - under Role restriction at the bottom of the block configuration, you can decide who has access to that specific menu. Repeat for each menu - this way, the menu appears in the same spot, but a different menu will appear for different roles.


As per your "after I re-enabled the modules": try to (temporary) increase your PHP memory limit (eg with 25%) to see if you get different results ... Doing so might get to work it as normal again.

That's one of the typial things I (temporary) do if such kind of issues come up (typically after enable of 1 or more extra modules due to which the current memory limit is not sufficient anymore).


Why is my website often put in maintenance mode by itself?

Usually, a Drupal site enters in maintenance mode by itself because is having problems to access to its database or when is set on that mode through the option located at "admin/config/development/maintenance".

If you are not able to log in on the site, that could indicate Db problems.

Check...:

at "admin/config/development/maintenance" is checked the option "Put site into maintenance mode". Or with drush: drush vget maintenance_mode
the settings.php if the Drupal database parameters are ok.
the status of the Drupal database, (if the user:password are correct, if the database server is online).
the error logs (MySQL, PHP, Drupal).


$query = db_select('form_submissions', 'sfs')->fields('sfs', array());
    $subquery = db_select('form_submissions', 'sfs')->fields('sfs', array('address'))->groupBy('address')->having('count(address) > 1');
    $query->condition('address', $subquery, 'in');

    $submissions = $query->execute();


HybridAuth: How to bypass 'allow access' button

I am also face the same problem, But am using ulgoin module. After login You must first authorize LinkedIn integration to use related features.

In this button available in user edit page. Once you have synchronized your details , in the above message not appear in the second attempt.

Thanks


You can either use hook_preprocess_node() and if the content type is company_profile, change the styling. Or you can have a node--company_profile.tpl.php file and render that particular content type the way you want.

Then you can use CSS to do get things done. If you use a grid based layout such as 960.gs, this would be easier.


CKeditor has empty node body for some nodes

If anyone is ever having this problem, you should check your response headers for requests sent by ckeditor. It will attempt to send a request to /ckeditor/xss to run XSS filters and if that fails it will silently just hide the entire contents of the form. In the response header I noticed a Location parameter that is only available when the form fails. The location parameter was: /user/login?destination=ckeditor/xss. This obviously means that ckeditor's request for the XSS filters is being intercepted by some other module and sending it to the login page.

In my case, the problematic content was unpublished nodes. I have yet to find the exact module causing the redirect for ckeditor, but disabling the XSS scan in includes/ckeditor.utils.js on line 163 worked perfectly to solve all my issues (seen on post #9 here https://www.drupal.org/node/2069871)


You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}


You need to accept the $form (and $form_state) parameters as part of the function signature, and not overwrite the form, rather add to it:

function gestionvideos_configuration($form, &$form_state) {
  $form['#submit'][] = 'gestionvideos_configuration_submit';

  $form['config'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration du plugin VOD'),
    '#description' => t('Pour fonctionner, le plugin a besoin de s\'interfacer avec votre compte VOD infomaniak.

                Pour des raisons de securites, il est fortement conseille de creer un nouvel utilisateur dedie dans votre admin infomaniak avec uniquement des droits restreints sur l\'API.

                Pour plus d\'information, veuillez vous rendre dans la partie "Configuration -> Api & Callback" de votre administration VOD.
    '),
    '#default_value' => variable_get('config', ''),
  );

  return system_settings_form($form);
}

Choosing a different name than 'config' for your variable might also be wise. It's always preferable to provide a pseudo-namespace to variables as a prefix, usually the module name (e.g. gestionvideos_config). Don't forget to add the default value as in the above example as well, otherwise next time you go to the form it will have forgotten your config option.

If the above doesn't work for whatever reason, then the bug is somewhere else; try systematically disabling custom/contrib modules until you find the culprit.


How to check if field value has changed on a node?

You could use the Rules module for this. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?".

By using the rule included in that answer, you can discover scenarios such as these:

Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

Here is a simplified version of the rule that should be pretty close to your case (to only show the inserted values):

{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just replace the machine name "field-email-addresses" by the machine name of your field that contains the eMail id of the user (prior to import), you should be able to experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise).


Aggregated CSS & JS files revert to old version

Couple things to look into. An external cache (Varnish/Boost/etc...) could be referencing the old files. This issue will help with the variable_set's with css/js aggregation https://www.drupal.org/node/886488#comment-9668583. Also see this issue: https://www.drupal.org/node/1014086. I'd guess it's an external caching issue based off of what your describing but I can't say for sure due to the flaws in core that have still not been fixed.

In all honesty advagg will fix these issue for you. Drupal.org uses it due to issues with deployments https://www.drupal.org/node/1412130 https://www.drupal.org/node/2446971


The $user variable may not be set in this context - it is not automatically available as a local variable.

Try adding global $user; before the code.


Programmatically create user and add complete address field values

That was simple - it should be $user->field_contact_information->country_code = 'US';


Bootstrap theme: editing the registration page

Take a look at drupal api documentation. Customizing forms is quite easy.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7

Just hook into that user_registration_form and for example add into class index bootstrap classes col col-lg-*. Or you can add #prefix and #suffix to wrap things into columns etc. And install Devel module to examine form's structure.

I'm not sure if it possible to use page--user--register.tpl.php to modify layout. Possibly you could create that and add col col-lg-offset-* col-lg-* to whatever element is the container for page[content] variable.


How to resolve conflict between zen theme breadcrumb function and Path Breadcrumbs?

So, more obvious than I'd like to admit: there is a Path Breadcrumbs settings tab where you can configure the theme settings as well as per theme breadcrumb settings. Enabling the theme breadcrumbs for my custom theme solved the problem!.


filter entity reference by another entity reference field in create content

It appears like you are looking for Reference field option limit module. Your case is their first example:

Example 1: countries and cities
Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

And yes, it works with nodes just as well as with taxonomies, as both kinds are entities.


How do I customize the comment reply link?

Have a look at the code of the AJAX comments module. It does simmilar things. There's a good chance that you can learn from theire code.


How to render a user register form for a Profile2 type

After looking through the Profile2 Git repository viewer for v1.3. I believe you want to do something like the following using profile2_attach_form. The `profile2_attach_form has the following API comment and function signature:

 /**
 * Attaches the profile forms of the profiles set in
 * $form_state['profiles'].
 *
 * Modules may alter the profile2 entity form regardless to which form it is
 * attached by making use of hook_form_profile2_form_alter().
 *
 * @param $form
 *   The form to which to attach the profile2 form. For each profile the form
 *   is added to @code $form['profile_' . $profile->type] @endcode. This helper
 *   also adds in a validation and a submit handler caring for the attached
 *   profile forms.
 *
 * @see hook_form_profile2_form_alter()
 * @see profile2_form_validate_handler()
 * @see profile2_form_submit_handler()
 */
function profile2_attach_form(&$form, &$form_state) { /* ... */ }

So, you could use it as follows by slightly modifying your code:

$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
    'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));

If you need to tweak any profile entity form displayed in some of your registration page(s), you may want to implement the specific FORM_ID version of hook_form alter, hook_form_profile2_form_alter().

EDIT 01/15/2015

minor API clarification and code cleanup from comments.


How to set the front page with Mobile Switch

Have you tried Context Mobile Switch in comination with Context? And if you want to implement a small custom module then you can add the global $conf variable and inspect it for which property to switch on.


If you're willing to make "products of type X" "products with taxonomy term X" instead, you could probably get away with using Commerce Taxonomy Conditions. With it, you can create a product discount that applies 1) if an order has a certain quantity of a taxonomy and 2) if the current product has a certain taxonomy term.

If that didn't suite you, you could model the correct discount/inline conditions from that code... ripping out the taxonomy bits and replacing them with Drupal Commerce product types.


We have solved this issue with two modules

Ajax Comments

  Provides ajax comments to Drupal sites (commenting like a social networking sites: Facebook, Google+, vk.com etc).

Block Refresh

  Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.

You can view the real sample at http://beinghuman.org/.


How do I handle third-party API credentials in settings?

The key module provides a framework for abstracting key storage from modules. The module provides 2 key providers (plugins) out of the box: config and file. It is possible to implement a key provider plugin for some arbitrary storage such as what the encrypt module provides.

Note that a web site's actual security risk for using a particular key provider depends more on security procedures and infrastructure.


Using print_r($thread); in your code gives this.

stdClass Object
(
    [thread_id] => 2
    [subject] => Testing
    [last_updated] => 1443004733
    [has_tokens] => 0
    [is_new] => 0
    [last_reply_to_mid] => 2
    [participants] => user_187,user_298
)

The below gives an array of the participants names.

    $participants = $thread->participants;
    $msg_users = explode(",",$participants);
    $prefix = 'user_';

    $authors = array();
    foreach ($msg_users as $msg_user) {
        if (substr($msg_user, 0, strlen($prefix)) == $prefix) {
        $msg_user = substr($msg_user, strlen($prefix));
        $msg_user_names = user_load($msg_user)->name;
        $authors[] = $msg_user_names;
    }
}

And something like the below gives  the date.

print date("Y-m-d\TH:i:s\Z", $thread->last_updated);

I'm sure you can work out what to based on that.

ps. I've wanted this exact thing so thanks for the snippet :)


How to make Feeds import only one post at a time when cron run?

There's no way (without hacking the Feeds module) to set this. You can affect how often the Feed updates, so if it's a feed with lots of posts set it to update more often and run cron more often, and that way fewer items will be imported per run because there won't be large amounts of new data to import each time.


How to get Panels to override node with "no extras"

The problem is (I think) that when you added content (Whichever Variant -> Content -> Gear -> add content) you clicked Node and then Node content.  Node Content will display all of the content of the node (Title, Body, and all Fields).  If you just want to display the body choose Node body.

Then in another Pane (Panel Biggest -> Region -> Pane Smallest) you can add your other fields.

Here's a video that talks about Panels and Panels Everywhere and can help show this in action.

http://www.youtube.com/watch?v=v6zMcfTxkhc

Hope this helps!


You should be able to get this to work using the Rules module, using the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. I'm not sure (actually I really doubt ...) if using Rules event " Content is viewed " (not " Node is viewed " ...) will work (typically that's 'too late'). Refer to "How to specify a Rules event like "Content is 'going to be' viewed"?" for more details on that.

If you can think of something to use a (new) URL like http://new.domain.com/new-page_url?newslug=with-different-slug (instead of http://new.domain.com/new-page_url/with-different-slug), then you can make the value of the URL argument (= the value of the newslug argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

PS: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


Importing large content with Feeds and cron

Are you running the actual site cron? If not, run it.

As for the Ajax errors when running a manual import, are you sure that it isn't continuing to import despite these? My large imports will time out the browser connection when I manually import in feeds, but they will actually still continue to process.

Also, could you try changing your setting from "As often as possible" to "Every 30 minutes", to ensure the crons aren't running over each other?


Creating a page only to be accessed by registered users

You could do that using Drupal's role based access control system.

For example, assign the role of "author" to the author users.
You can then restrict access to the "Author Resources" page by user role.
e.g

Create a page using the Views module and adding an access restriction.
Create a page using hook_menu and restrict access to that role in the "access callback"


How to visit a specific node using behat

You can do two things in this scenario:

You can instruct it to click on "Accomodation Foo" (which should be the linked node title) on this page, to go to the node when the path is unknown.

If you have pathauto installed and configured, you can assume the path, so if it is [node:title], the path in this case is likely 'accomodation-foo'.

I use both in different cases, depending on the scenario. I keep the test node titles small and predictable so I know what the path (should) be. If the path isn't found, it is also a good way to test if Pathauto is creating the URLs you expect.

Here is an example one I wrote not too long ago:

Feature: Page Content Type (Anonymous)
  When I view the website
  As an anonymous user
  I should be able to view basic page content and its fields

  Background:
    Given "page" content:
      | title                     | status  | body             |  field_subtitle       |  field_summary            |
      | Published page            |       1 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
      | Unpublished page          |       0 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
    And I am on "published-page"

  Scenario: An anonymous user should be able access published basic page content
    Then I should not see "You are not authorized to access this page."

  Scenario: An anonymous user should be able to view the title
    Then I should see "Published page" in the summary region

  Scenario: An anonymous user should be able to view the subtitle
    Then I should see "This is the subtitle" in the summary region

  Scenario: An anonymous user should be able to view the page summary
    Then I should see "This is the page summary" in the summary region

  Scenario: An anonymous user should not be able access unpublished basic page content
    When I go to "unpublished-page"
    Then I should see "You are not authorized to access this page."


Storing a URL from a basic page using a custom module

In your custom module, try to implement the hook_preprocess_page

function my_module_preprocess_page($vars) {
  print_r(current_path());exit;
}

This will retrieve the current URL of the site.


How to define a new cache context for a node

You will need to define a cache context in yourmodule/src/Context. This will be a class implementing CacheContextInterface, as described in the docs here (see 'How to recognize, discover and create?).

If you search for implements CacheContextInterface in your code base you should be able to see some examples. The class will provide getContext() and getCacheableMetadata() methods.


How can I add Taxonomy Term to a Node's Breadcrumb?

Themers who don't want to use a custom module to implement a BreadcrumbBuilder can change the breadcrumbs in a preprocess hook.

Example how you can add a link before the last link:

function mytheme_preprocess_breadcrumb(&$variables) {
  $breadcrumb = &$variables['breadcrumb'];
  $lastlink = array_pop($breadcrumb);
  array_push($breadcrumb, [
    'text' => 'New Link',
    'url' => '/newlink',
  ]);
  array_push($breadcrumb, $lastlink);
}

If you add a taxonomoy term from a node you would have to add both as cache tags and a cache context on the url to make this work.


base_url in settings.php with mobile version

How is your /sites folder structure? You can create subdomain m.example.com, and implement the mobile version in there.

There are different approaches in implementing the subdomains in drupal. it may be multisite and shared database or multisite with different databases and single code and different databases .

what you are looking for is a shared database but different themes (multiple codes), Here is good discussion about this.


Problems to integrate a form into a block

You've got _function on the end of ios_lang_checkbox_nameform_function...just change that line to:

$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');.

The string passed to drupal_get_form() needs to be exactly the same as the function name itself, no need to put _function on the end :)


I have gone thorugh drupal migration many times and it takes much time if DB is heavy.So Take a breath and keep it going.....once 100% migration is done then you proceed.
And also D2D module provides option to select which content types you want to migrate first.In this way you can divide your migration into parts and process will be fast then previous.
Good Luck :)


How do I automatically remove spaces from a path in the blog module

Using Pathauto you can replace spaces with a character of your choice (and do a lot of other stuff too), like for example a dash. Once you have enabled the module go to admin/config/search/path/settings and start configuring the module.


I did not figure out to do this, but a workaround was to actually make a separate field called summary and remove the default body and add a new body field without a summary.


How do I send user credentials and get the access token?

Moqbel,
Here is a Drupal 8 Android app code that uses Android accountManager to send user credentials and get the access token. https://github.com/onedrupal/One-Drupal-Android

Whan a token is expired, AccountManager can be used to get a fresh token.
https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java At the launch of the activity AccountManager.getAuthTokenByFeatures is called

mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

Here is the AccountAuthenticator https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);

It uses cookie auth by using endpoint /user/login?_format=json at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/provider/MyServerAuthenticator.java

But Android AccountManager also works with OAuth.

from https://developer.android.com/training/id-auth/authenticate

  The only way to discover whether a token is expired or not is to
  contact the server, and it would be wasteful and expensive for
  AccountManager to continually go online to check the state of all of
  its tokens.

  Because expired tokens are such a common occurrence, and fixing them
  is so easy, many applications just assume the token has expired before
  even asking for it. If renewing a token is a cheap operation for your
  server, you might prefer to call AccountManager.invalidateAuthToken()
  before the first call to AccountManager.getAuthToken(), and spare
  yourself the need to request an auth token twice.


In Drupal 7 you can have different field settings for different content types. This was not possible in Drupal 6.


You don't need an additional module. When you configure the node reference field you can use a view to select the nodes. Its under the advanced section.


Views image fields render slow causing overlaping results

This is not a views or a Drupal issue...

Things to do are:

Make sure the image size in terms of KiloBytes is not huge. If you
have fairly large sizes this will affect your site speed in general,
especially on mobile devices.
Make sure you are using an appropriate Image Style. Meaning the size of the image you are rendering, in terms of pixels is not
bigger than the container you are rendering in it.
In any case to remove this overlapping effect set a static height to the container the image is rendering into. In this way the text
is not going to overlap even if the images are still rendering.

Hope this helps.


How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

The Global Redirect module does what you want (and more).

  ... Checks if the Clean URLs feature is enabled and then checks the
  current URL is being accessed using the clean method rather than the
  'unclean' method.

It redirects the node/xx to content/your-content etc if clean URLs feature is enabled.


How to bypass/skip payment after checkout in Ubercart?

One way to do this using the combination of ubercart custom payment module and ubercart discount coupon module, i.e creating a coupon of 100% discount and to bypass the payment process you will need the ubercart custom payment module (by default it provides the rule that can use it).
Ubercart Discount Coupons: Coupons can apply either a fixed price discount or a percentage discount to the order subtotal or to selected product prices.

Coupons are configured at Store administration > Coupons. Global settings for the module are configured at Store administration > Configuration > Coupon module settings.

Ubercart Custom Payment module:

provides a "Free Order" payment method, and a default Rules configuration is provided to enable this.


Change a Node Reference field value with VBO

Ok what worked out was having 2 parameters. One the node I'm altering, the other an integer field to input the node ID. Then I set up a "Fetch entity by id" action using the integer parameter. I use the entity variable provided by the fetch action to set the node reference field.


To get the field value without the label:

{{ content.field_name[0] }}

  BONUS

  If your field allows for multiple values, just increase the 0 to get the
  other values.

  {{ content.field_name[1] }} {{ content.field_name[2] }} ... and so
  on.


Recoverable fatal error on nodes after leaving Maintenance mode

You probably included an object as an argument to one of your query conditions. If you print_r the $args at the line number in the database.inc file, you find out what the placeholders are set to.


How to allow a particular user to take quiz very next day in drupal

I would suggest to make use of rules:

Create user role (by hand) which always access to quiz let say QUIZER
On Event "I want to enter Quiz"
Look up Time Last entered date from current olr
Check if allowed to go on
Add role quizer to current user
On event "I'm stopping the Quiz"
Remove role quizer from current user
Save Time last entered Quiz in user profile


Error after installing and enabling "Rooms-Drupal Booking for Hotels, B&B and Vacations" and dependent modules

The dr8 part of your table name seems suspicious ... since you're using Drupal 7, while that dr8 might refer to something related to Drupal 8.

If that's not what is causing your problem, and as per the last phrase in your question ("... a better solution for Room Reservations ..."), then have a look at these alternative modules (with a stable release) for managing reservations in D7 (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI.

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict.

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.


How to force D8 "Configuration synchronization" to send HTTPS download URL

I forgot the SSLEngine On Apache directive in the configuration of the VHost listening on port 443.

With it, the Location header sent by Drupal contains now https scheme.


Drupal 7 globalredirect not working for /node/ redirection

For your first problem why are you not simply using Clean URLs, which is built into Drupal? I'm assuming you're using version 7.x.

I'm not absolutely certain about adding the .html added to your url aliases and whether that will break something, but I'd imagine you could easily fix that by using some mod_rewrite and just appending .html to all your clean URLs.

What I mean then is in your Drupal system your URL aliases will be /Services/TrainTickets. Essentially you'll still be using default/core clean URLs for all your paths. In .htaccess file though you can use mod_rewrite to append .html to all your paths.

For your last problem re: blocking access to all /node/x paths, the first thing I thought of was again to use mod_rewrite to redirect to a custom built 404 Page Not Found page, instead of having to use a Drupal module. However, I've never tried this and am not certain this approach would work. I took a quick look though and it appears someone else thought of this too:

https://www.drupal.org/node/164526#comment-7919767

One issue I see right away is that you'd want to ensure that the path is a node view page (i.e. node/x) and nothing more (e.g node/x/edit - which would mean you're logged in), otherwise you'll run into some issues when logged in and trying to edit content.

Maybe try it out? Worth a shot.


This is a bug in Drupal 8 core, currently being worked on in several different core issues, many of which have working patches.
If you need the functionality now, you have two options:

Try the patches from comment #22 (or more recent) on Issue #2923634 and the patches on Issue #2752443.  Read the comment thread on #2923634 to get a full understanding of what's going on here.

Or use the well-vetted patch from comment #139 on Issue #2118743 which has been postponed in favor of option 1 above.

I'm using the patch from option 2 (#2118743) successfully. Please note that this does go against the standard core contributor recommendations. But the reason is because #2118743 has a single, well-vetted and working patch for something that is only enabled / used during development, and instead of needing to test out various combinations of two separate patches that are still under development. Once the better solution (#2923634 and #2752443) get fixed in core, #2118743 should be obviated and no longer required.


Executing view twice with different filters returns same results

The second argument to views_get_view is $reset:

  If TRUE, reset this entry in the load cache.

So second time around you just need to pass that:

$view = views_get_view('my_view');
$view->set_display('default');

...

$view = views_get_view('my_view', TRUE);

That will reset the static cache and the data will be fresh.


Commerce product with customer defined attributes

Absolutely.  What you need is the Commerce Customizable Products module.

That allows you to set up Line Item Types that are entirely fieldable!  You can add text fields, select boxes, radio buttons and any field you want to be displayed as the user is adding the product to their cart.

Once the module is enabled, do the following

Add a new Line Item Type at /admin/commerce/config/line-items
Add any fields you need to it (in your case, just a text field)

Make sure to check the box that asks whether this is a field you want added to the 'Add to Cart' form

Finally, go to the 'Manage display' tab of the content type you have that displays your product, and go into the settings of the 'Product' field.  You will see a new option which allows you to choose a 'Line item type' to display.  Select the one you just created, Update, and Save!

Final result:

Let us know if this works for you...


Rules in Drupal 7: EntityMalformedException in custom PHP

You need to remove the first line $update_node = node_load($node->nid); because nid does not exist yet in node object then remove the last line as well node_save($update_node);.

Also, replace each $update_node variable with $node which is available by rules module.

Your final code should look like the following:

$lat1 = floatval($node->field_geo["und"][0]["lat"]);
//SOME MATH HERE
$node->field_winkel_dorf["und"][0] = array("value"=>$winkel);


You need to use Views handlers https://api.drupal.org/api/views/views.api.php/group/views_handlers/7.

Basically, you need to extend the handler class that is used by that field which in your case is field_image.

In order to start and make your custom handler work you need two basic functions to tell Views you mean some business with them. These are  hook_views_api() and hook_views_data_alter() function.

MODULE.module

/**
 * Implements hook_views_api().
 */
function uc_addons_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'uc_addons') . '/views',
  );
}

MODULE.views.inc

/**
 * Implements hook_views_data_alter().
 */
function uc_addons_views_data_alter(&$data) {
  dsm($data);
}

The hook_views_data_alter() function needs to be inside your MODULE.views.inc file.

Lastly of course is your handler w/c adds your field by extending the base handler as you can get more idea from the link. Also from my experience, the saving of values from fields are taken care by Views already.


Drupal 7 custom submit handler not getting triggered

Another form alter may affect this form and maybe detach your sumbit handler.

Try

$form['#submit'] = array('mymodule_eck_ent_submit');

And see if it fires.


Take a look at The White Screen of Death (Completely Blank Page) to learn more about the WSOD and how to troubleshoot it.


How to create custom search filter for entity list

You are using an entity list builder? There is no standard support for filters/sort, if you want to implement something you have to do it yourself.

All content lists that use filters like admin/people and admin/content are views, expose your entity type to views if it is a content entity type.

One special case is admin/structure/views, which is a config entity list builder that has support for filters. But that's actually a client-side implementation done with javascript.


how to separate taxonomy hierarchy in pathauto with slashes

There is a clever way to do this by using join:/

In my case, I used:

[node:field-taxonomy-skolski:parents:join:/]

where field-taxonomy-skolski is the field for choosing the term from the taxonomy tree.
Forward slashes will be stripped, though there is a setting under

Administration » Configuration » Search and metadata » URL aliases » URL aliases - settings

at the bottom of the page for PUNCTUATION drop-down. Set to slash (/) "no action" instead of "remove".


Display a key from unserialized data field

You need to add an Global PHP field and put the following code in output value to get the identifier field value.

<?php
 $result = unserialize($row->data);
 print $result['identifier'];
?>

Note : You should exclude Data field from display.

Since you very cautious in not using PHP, did you try the following option, change the ckeditor_skin to identifier. But it will produce the output as 76561198181833179['identifier'].


Attach custom css library to entity print output

I am answering my own question for the ones who might probably face similar issues.

The 2nd method as described at https://www.drupal.org/node/2706755 where we attach the library to entity_print works.

I had a custom entity-print--node.html.twig in which I missed printing the css styles using the variable {{ entity_print_css }}


You shouldn't need a specific class to complete this.  Just assign the div to something like

@media (max-width: 991px) {
    #menu{display: none;}
}

If you need to add the class to the div you can use jquery.

$('div').addClass('mobile-only');


How can I override the Calendar module's theme functions?

You can create your own custom module and define your own copies of these preprocess functions.

For this example we'll call your module mysite.

In your mysite.module file you would define:

mysite_preprocess_calendar_mini(&$variables)
mysite_preprocess_calendar_month(&$variables)

And then modify the contents of the variables in these functions as needed. Copying the existing preprocess functions might be a good place to start if you're not sure what you want to modify.

Check out the preprocess documentation for some more information about how this system works.


How to create a view with 1 item in left column and 2 in right column?

If you are having panels module installed than the best would be to use the Panels fields as following:

Set the display style in your View to show Panel Fields.
Add the fields you want to show in your view.
Configure the settings of Panel fields as:

Select Panel layout: Two column stacked
Assign fields to the respective section (e.g: top, right, left), as per your requirement.

Save the view.

Check the attached screenshot for reference:


Getting latest node to display as front page

Your best bet is to use Views and attach a PAGE format. Then for display format: "full content". Its not overkill since your page would be cached anyways. But if your really not keen on using views, your best bet is to create a new tpl file for your theme and gear it towards the frontpage via: node--front.tpl.php (not sure if it was like that, but google it) Then return the latest node filtered by content type.


Maybe Apache server doesn't include "mod_rewrite".

Try do below code in the console:

sudo a2enmod rewrite
sudo service apache2 reload

I think this help to you!


Is it a problem when entity field storage info is not registered in the key_value table?

It will depend on what exactly is reported from getChangedList() but what is happening is that a module needs to update the entity schema with something like:

\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('the_field_name', 'node', 'node', $field_storage_definition);

Everything you need to know is in the change record: https://www.drupal.org/node/2554097

There is also an effort underway to provide additional information on the status page: https://www.drupal.org/node/2554911


How to get uid from a node on which is commented?

I could load the $nid via the comment and confer the uid's like this:

function mymodule_comment_view($comment) {
 $nid = $comment->nid;
 $node = node_load($nid);
 if ($comment->uid == $node->uid){
    //do something
 }
}


hook_form_alter() can take care of this by setting #access element on menu item operation links.

function MYMODULE_form_menu_overview_form_alter(&$form, $form_state, $form_id) {
  foreach($form as $key => $value) {
    if(strpos($key, 'mlid:') !== FALSE) {
      $form[$key]['operations']['edit']['#access'] = FALSE;
    }
  }
}


Add text message under "Add new comment" title

You can override field--comment.html.twig template.

https://api.drupal.org/api/drupal/core%21modules%21comment%21templates%21field--comment.html.twig/8.8.x

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    // you can add your markup here
    {{ comment_form }}
  {% endif %}

clear the cache after add new template file


Rules: How to modify an existing condition programmatically

So turned out it was quite easy:

  $hk_delivery_rule = rules_config_load('commerce_shipping_service_hong_kong_delivery');

  foreach ($hk_delivery_rule->conditions() as $condition) {

    if (isset($condition->settings['second_price'])) {

      $condition->settings['second_price']['amount'] = $hk_threshold;

    }

  }

  $hk_delivery_rule->save();


Drupal 8 is a better platform , it has a better structure , more features in core , it is based on symphony2 and so the module development is different from what you knew in drupal 7. template engine also is changed to twig so again you have to change your point of view about how used to theme before .

Another thing must be mentioned before making your decision is that there are too many module for drupal 7 and you can find a module for almost any job but cause drupal 8 is new , many modules are not still developed for this version.

All in all I should suggest you that it is a good idea to migrate to drupal 8 but if you have a deadline for your project this may not be a good decision to start it with drupal 8 ,cause it will take some times to be adopted.


Encountered a similar problem when trying to render the Forgot Password form in a block.

Since the form builder for the form is in user.pages.inc, the solution is to load the include file at the same time you do the drupal_get_form() to retrieve the form. e.g.

module_load_include('inc', 'user', 'user.pages');

If you are calling the form via a hook_menu implementation, you will need to use the 'file' and 'file path properties'.


Render entity reference field with link in node template

If the field is configured to display and available on the node, in node.tpl.php, you should be able to use:

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


Diff module not tracking fields that existed before module was installed

Did you read the README for the module and go through the module configuration? See CONFIGURATION section of the readme.

2) Field revisioning settings

   Global settings per field type can be found here:

   http://www.example.com/admin/config/content/diff/fields

   "Show field title" toggles field title visibility on the comparison page.

   "Markdown callback" is the callback used to render the field when viewing the
   page in the "Marked down" page view.

   "Line counter" is an optional. This shows the approximate line number where
   the change occurred. This is an approximate counter only.

   Other fields add additional settings here.

This Diff Issue Queue item describes a similar "No visible changes." problem encountered by another user.

From the issue it sounds like the diff comparison view, which is typically "Standard comparision preview" settings == "Full content" needs to be configured to show the fields you want, or be the correct view_mode for the content.


Features - keeping Git up to date when changing features on production

Great question. I work in a Drupal agency where we see this all the time.

Imaging this scenario:

Locally you've made some amends to a site that overrides a bunch of features. Locally you can run feature updates, placing the changes from the database into the code and then get ready to push live. But when you go to push live, you see there are feature overrides existing on the live site. There can be feature overrides for a number of reasons but the most often one is fields and blocks moving. If there are additions in your code they will be ok, but if you need to revert one of the features to say, move a field, then it gets a bit tricky.

My personal solution to this is to download the latest live database and run feature updates from that database locally, then merge the code changes. Then when you push your code you will have your changes and your live sites overrides in the code.

This isn't perfect, but it's workable.

Why not just run feature updates on the live server and pull that code change locally for a merge? Most, usually all, servers don't allow write permissions in live environments. So cloning the db locally is often necessary for this.

It's also worth trying to structure you features well, it's an art not a science! I usually leave ALL blocks out of features as they always get overridden. Also don't make a feature for all content types or all views as that will easily be overridden. Yes you can make too many feature, this is where your experience will come into play and it gets easier the more you do it.

Our senior dev also hook_update_N which may be worth looking into.


Adding content to a database table during module install

As alternative of implementing hook_install(), if the module needs to be sure those data are present in the database before it runs, you can implement hook_enable(). The difference between those hooks is that hook_install() is executed once, when the module is installed; hook_enable() is executed all times the module is enabled, which happens also when the module is installed. Using hook_enable() requires you to first verify the data are not already present in the database before to write them.
Implementing hook_enable() is what the Forum module does to create the taxonomy vocabulary, and the taxonomy reference field it uses. (See forum_enable().)

Keep in mind that if you need to insert too much values in the database, then you should find another way to do it, as code taking too much time to be executed would cause a PHP timeout, and the code would not be complete the data insertion.
The alternative is using batch operations, or queue operations.


The code shown in your question can never work: you need, at least, change the function name from "MYMODULE_leaflet_map_info_alter" to the actual name of your module.

PS: debugging is the art of taking away all possible reasons why something doesn't work as expected. This is for sure 1 of the possible reasons ...


How to get the raw value of the url in a link field

Instead of rendering the URL object with toString() use the method Url::getInternalPath:

$url = $link->getUrl();
if ($url->isRouted()) {
  $path = $url->getInternalPath();
}


Does DRUPAL_CACHE_PER_PAGE count pager pages (i.e. frontpage?page=3)?

Yes.

See drupal_page_get_cache() in bootstrap.inc:

if (drupal_page_is_cacheable()) {
  $cache = cache_get($base_root . request_uri(), 'cache_page');
  if ($cache !== FALSE) {
    $cache_hit = TRUE;
  }
  return $cache;
}

request_uri() returns the whole path including any GET arguments.


how to refer to fields with multiple values in node--content-type template

I managed to accomplish this by appending [value] to the end of the field_tag array. Then by using the 'count' function I created a for loop to iterate through each value like so

$j = count($content['field_tags']);
for( $i = 0; $i < $j; $j+= 1){
    if(render($content['field_tags'][$i]) != ''){
        print "";
        print render($content['field_tags'][$i]);
        print "";
    }
}

Note: For some reason I had to insert a check for if the tag was empty because the array ended up being a lot larger than the number of the tags.


Create Block using views module and show in sidebar.


How do I create customer/order relationship with entities?

You should look at Drupal Commerce, a suite of modules that sets up e-commerce in Drupal.  You will have a much easier time adapting Drupal Commerce to fit your needs than you will writing a store from scratch in Drupal.


Yes, as Neo mentioned, the toolbar utilizes menu permissions so it only displays items available to the user. So if the user has permissions for Use the administration toolbar & View site reports (or whatever permission needed for a sub-item in the admin menu), they will see only the report menu items.


Views to Display Nearby nodes according to user current location(latitued/longitute)GPS

Having messed with many Drupal mapping modules, I've found IP Geolocation Views & Maps to be the best overall helper (along with Leaflet, which I love). Give it a shot! It has lots of options, supports lots of maps, has geolocation stuff built in, marker clustering and some other stuff.