Strange sorting in one facet of Apache Solr Search results

Don't know exact path for D6, but you can got to facet configuration, configure display - and there will be sort options with ability to enable/disable sorts and reorder sorting.


Check if a node field has changed upon save

Clive is correct.
$node->original does give access to the original node values. I was able to accomplish what I needed like so

function my_module_node_presave($node) {
    $type = $node->getType();
    if($type == 'issue'){
            if(isset($node->field_pdf->entity) && !isset($node->original->field_pdf->entity) || empty($node->original->field_pdf->entity) || $node->field_pdf->entity->id() != $node->original->field_pdf->entity->id()){
                $node->field_indexed->value = false;
            } else {
                $node->field_indexed->value = true;
            }
    }


Error Finding Home page for Drupal 7 Site on Ubuntu Linux

You need to enable php in your apache conf. You can try

$ sudo a2enmod php5


How to disable field on register form but keep show in edit profile?

Drupal 7

In D7 you can edit each user field under Configuration > People > Account Settings > Manage Fields and untick the option Display on user registration form.

Drupal 8

In D8 after you add your fields under Configuration > People > Account Settings > Manage Fields go to  Configuration > People > Account Settings > Manage form display, scroll down and uncollapse Custom display settings, tick the Register option and Save.

Now you will see two sub-tabs on that page: Default and Register. Visit the Register sub-tab and rearrange the fields to disable the ones you don't want. This will apply to the Registration form only.

The Default settings will apply to the User Edit form, so you'll want to keep the field enabled there.


Forums 'Add Container' function not doing anything

I flushed the cache and it worked.
I created a flush.php file and ran it.

<?php
  drupal_flush_all_caches();
  drupal_set_message('cache flushed.');
?>

More information is available here.


How do I organize webforms in admin panel

How many Webforms do you have? I have worked on huge sites, and I have never had enough forms to even fill one page.

As for filtering, you can already go to /admin/content and filter by Content type = webform, or just go to /admin/content/webform.

If you need even more control over filtering, then you need to create a custom administrative View. With that, you can add filters for whatever you need, and pagination.

Group level access permissions are more difficult, but not impossible. Start here: https://www.drupal.org/project/permissions_per_webform. If that is not what you need, then look at the many other  modules available for controlling access/permissions.

Last, I think your question was voted down because of several things. First, it is not helpful to make general negative comments like "not well organized". Second, this is not the place to make demands for new features. Third, is the fact that you don't seem to have done even basic searches for the functionality you need.

Last, is your presumption that webforms need to be changed to suit your use-case. Drupal is very powerful because it is modular. Just because you need a certain set of features does not mean that those very specific features would be helpful to anyone else. You should be able to build the functionality you need, but the key word here is "build". Drupal gives you the power to add a GPS to a lawnmower, but that doesn't mean you can demand that every lawnmower sold has a GPS.


I realise the question is more than a year old...

Create a view with no content type filter.  Add fields for Title, Type, Link, and File field in that order.  In the Link field settings, check the Exclude from Display box.  In the File field settings, under No Results Behavior, use the token of the Link field in the Rewrite Output space.  The available tokens will be listed in an expandable space below the text field.  Tokens include all fields listed before the current field, which is why the order matters.  Set display to a table and turn on paging.

Views will automatically check access permissions, so this should do what you want.  This will pull in all nodes, filter by access, look for the file and use that link if it finds it, and then in the cases where that field is empty (content of another type) it will use the node link instead.


You could try Paragraphs which is an alternative to Field Collection.


There is as well:
http://drupal.org/project/nodeaccess_autoreference module
which is working in similar way. But I'm not sure if this solves your problem.


How do I send an email to all users that has flagged a node using rules?

The exported code assumes use of Flag module to have a flag type as "follow" attached to Blog content type.

As a summary:

set rule event as "After saving a new comment of type Blog comment".
leave condition as none.
set actions as

step 1: get all users
who have flagged "Fetch users who have flagged a Node".
step2: loop
through the list.

step2.1: send email

Here is the export for my Rule configured as per your requirement.

{ "rules_email_on_blog_comment" : {
    "LABEL" : "Email On Blog Comment",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "blog", "email" ],
    "REQUIRES" : [ "flag", "rules", "comment" ],
    "ON" : { "comment_insert--comment_node_blog" : { "bundle" : "comment_node_blog" } },
    "DO" : [
      { "flag_fetch_users_node" : {
          "USING" : { "flag" : "follow", "node" : [ "comment:node" ] },
          "PROVIDE" : { "users" : { "users" : "Users who flagged" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "[list-item:mail]",
                "subject" : "New Comment",
                "message" : "There is a new comment on the flagged blog post",
                "from" : "[site:mail]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


How to theme table inside vertical tabs?

Not sure if it's the right way to do, but you would create a new form element with the table, instead of adding a table directly.

function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // create a new form element with the table
      $form['tabs'][$id_tab]['table']['#markup'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

Option #2:

function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // set the table as a value of each vertical tab item
      $form['tabs'][$id_tab]['#value'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

This will give following output:


How to manage a field collection in a table?

Yes, with the Field Collection Table module:

  Provides a table formatter for the Field Collection module.


Where is the location of developer/globals.php

That is because there is no such file in the codebase. It is documented separately. When the API site is built, it combines documentation from code comments in Drupal core and the documentation project.


Doubt with display a query using Custom Field Module in View

You can set up relationships in views to pull data from other tables should you have to.  There's a screencast from Drewish here on how they work and how to set them up.

Basically, you'd need to set up a relationship based on a part of the current data in the row.  After this, more data is exposed to you in the fields section of views.

If I'm misunderstanding your question and you'd just like to embed a view withing a view, then check our the Views Field View module.

  This module allows you to embed a view as a field in a view.

  This view can accept arguments from fields of the parent view using
  tokens.


I have found out what was going on. Omega builds the mobile page by changing the side-by-side layout of regions to a stacked layout. The region with the search field and button was layered behind another region in the same zone. Once I removed this layering, there was no issue. An easy fix.


There are two level of caching in Drupal.

1.) Dynamic Page Cache

You have to provide the correct cache metadata on the json response.

For example use the cache properties from a config or content entity

$response->addCacheableDependency($entitiy);

or build a cacheable metadata object and add this to the response:

$build = [
  '#cache' => [
    'contexts' => ['url.query_args'],
    'tags' => ['node:1', 'node_list'],
    'max-age' => 300,
  ],
];
$cache_metadata = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);

You can use this in a custom controller or implement this in an event subscriber to alter responses from other modules (core or contrib).

2.) Internal Page Cache

The module Internal Page Cache caches all responses for anonymous requests regardless of the cache metadata. You can uninstall this module to disable this cache.

Alternative solution

On the client side append a different query string on every request to get a fresh response:

node/123?_format=json&time=123456789

This will disable the Internal Page Cache and parts of the Dynamic Page Cache.

Reference: https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services


Change Classes in Nav-Tag of Custom Menu

You'll need to enable Twig template debugging output to do this. Once you do that you should see a number of template suggestions upward in the DOM for the <nav> tag. For example:

   * block--mainnavigation.html.twig
   * block--system-menu-block--main.html.twig
   * block--system-menu-block.html.twig
   * block--system.html.twig
   x block.html.twig

(Note this assumes you are using Drupal's block system to render the menu.) Above are a number of suggestions. If I look in a likely candidate from above, for example, block--system-menu-block.html.twig, I see markup like this:

<nav role="navigation" aria-labelledby="{{ heading_id }}"{{ attributes|without('role', 'aria-labelledby') }}>

You can grab any of these templates from core and then override by using a copy of the template in your theme and then alter the markup per your requirements.

If you are using Twig Tweak to render the menu, then in that case, you can just add your own custom <nav> tag like so, usually in a page template such as page.html.twig:

  <nav role="navigation" aria-labelledby="off-canvas-menu" class="main-menu" id="off-canvas-menu">
    {{ drupal_menu('main', 1, 4, TRUE) }}
  </nav>


How to allow for files of any extension to be uploaded?

You can use Allow  all file extension Module

  This module reverts Drupal 7's file upload widget to the Drupal 6
  behavior, and trusts the site administrator to be smart enough to
  allow uploads with any file extension. It also lengthens the allowed
  file extensions box from 128 characters to 2048, allowing you to
  specify a larger number of extensions.

  While I realize this is somewhat insecure and would have liked to add
  more functionality to this module, this isn't something I should have
  needed to do at all, and I don't have a whole lot of time to spend on
  it. If there are any bugs, I'll try to fix them, but beyond that, I
  won't be adding new features to it. If you would like add new features
  to this module, I would gladly accept a co-maintainer (or even
  transfer ownership to someone else).

  Warning: The ability to leave the allowed file extensions box blank
  was removed for a reason. If you leave it blank and allow random users
  to upload files of any type, you'll have an insecure site. As such,
  you are strongly cautioned only to allow trusted users to do this.


How to pass a Flag field's value to a Rules Component triggered by the flag?

Step 1 - Add parameters to the Rules Component

Make the "Date from" and "Date to" available as extra parameters to the Rules Component. Here is an example of such Rules Component (in Rules Export format, if you have the Rules UI enabled you can import it in your own site).

{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "flag_from_date" : { "label" : "Flag from date", "type" : "date" },
      "flag_to_date" : { "label" : "Flag to date", "type" : "date" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022 (with Date from = [flag-from-date:value] and Date to = [flag-to-date:value])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nFYI: the \u0022From date\u0022 (from the flag) is [flag-from-date:value] and the \u0022To date\u0022 (from the flag) is [flag-to-date:value] ...\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

The above Rules Component uses these 2 parameters (together with some other parameter "Group"):

"Flag from date" (label), with machine name flag_from_date, and data type "Date".
"Flag to date" (label), with machine name flag_to_date, and data type "Date".

Note how both parameters are shown within "USES VARIABLES" (that's where they are 'defined'). But also note how within the message body of the eMail both parameters are used (referenced), with any "_" in the machine name replaced by "-".

Step 2 - Make the Flag fields available in the Rule

Before you can use the "tokens" related to the Flag fields in a Rules Action (as in Step 3 below), the Rule needs to be made aware about those Flag fields. To do so, simply add those 2 Rules Conditions in the rule that is triggered by Rules Event "When something is flagged" (with this flag):

Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is field_flag_a_group_date_from.
Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is field_flag_a_group_date_to.

Step 3 - Pass the Flag fields values from the Rule to the Rules Component

After you completed Step 1, Rules "knows" that for any Rules Action that performs the Rules Component, it is required that a value is specified for those 2 parameters that the Rules Component needs (expects).

So if you add a Rules Action like "perform the Rules Component" (from Step 1) to your Rule (not Rules Component!), you will be prompted to specify a Data Selector for each of the 2 parameters (labelled "Flag from date" and "Flag to date"). Here is the trick to complete the rule (puzzle?): if you first completed Step 2 (and only then!), you will be able to:

use flagging:field-flag-a-group-date-from as the Data selector for the "Flag from date".
use flagging:field-flag-a-group-date-to as the Data selector for the "Flag to date".

Here is an example of such rule, which passes the values of those Flag fields to the Rules Component that is performed in the Rules Action (in Rules Export format):

{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_from" } },
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_to" } }
    ],
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : {
          "group" : [ "flagged-group" ],
          "flag_from_date" : [ "flagging:field-flag-a-group-date-from" ],
          "flag_to_date" : [ "flagging:field-flag-a-group-date-to" ]
        }
      }
    ]
  }
}

If you have the Rules UI enabled you can import this rule in your own site (after you adapted the machine names of the flag fields to fit yours).

Note the 2 Rules Conditions that were added in the above rule (as detailed in Step 2). And how those fields are then also used within the Rules Action that performs the Rules Component (from Step 1).


Using custom test helpers in your test cases

If getRecord() and testGetRecord() are methods of the Garbage class, then you have a misplaced } bracket.

Alternately, testGetRecord() will have no idea what to do with $this, since it's not part of a class definition. It would need to be a method of a subclass of DrupalUnitTest, or DrupalWebTest. As-is, PHP will choke on it.


How to add an attribute to User reference

Alternatives could be Paragraphs, Multifield, Inline Entity Form or Double Field.


how can i re-direct a user of a particular role, if that user tries to access a page containing certain content type?

You can consider Rules for this requirement.

You can add new rules for event such as "viewing a page" & put conditions to match user type & content type. In action you can add page redirect.


Drupal makes a distinction between regular files and managed files. The first are only stored on the filesystem, the second are stored in the database (managed) as well.

If you use a manged file (type = 'managed_file') the $form_state will contain a file id (fid) of the newly stored image.

Also note that file_save_upload takes the file path as the first parameter, so 'image' means nothing there. And that you still have to store your image as a permanent file after file_save_upload():

$file = file_load($logo);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'your_module', 'using_entity_type', $entity_id);


Drush, post receive hooks and git branches/tags

Your tag 7.x-1.01 could be the problem ... In most Drupal projects the tag would be 7.x-1.1 (Without the zero)


I find existing answers rather confusing.

Views (as we know) is extremely cool module. It supports localization plugins.
Go to page admin/structure/views/settings/advanced to see for yourself:

Preferred way to translate Views is to use Internationalization Views module which depends on i18n_string (i18n package) module.
How to use? Just enable Internationalization Views and go to translate page for your view.

You also may be interested in i18n_string settings here: admin/config/regional/i18n/strings.
Core localization plugin just do t() for Views titles, headers, footers etc. It's not so flexible and secure, but as a developer you can choose this method in some cases.
How to use? Nothing special here. Your strings will appear in Drupal translate interface after the first request.

You can disable localisation at all or create your own plugin if you need.


Extra fields for edit form as opposed to front end

hook_entity_extra_field_info() is invoked when either an entity is rendered, or when an entity form is shown to users. See user_entity_extra_field_info() as example.
function user_entity_extra_field_info() {
  $fields['user']['user']['form']['account'] = [
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  ];
  $fields['user']['user']['form']['language'] = [
    'label' => t('Language settings'),
    'description' => t('User module form element.'),
    'weight' => 0,
  ];
  if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
    $fields['user']['user']['form']['timezone'] = [
      'label' => t('Timezone'),
      'description' => t('System module form element.'),
      'weight' => 6,
    ];
  }
  $fields['user']['user']['display']['member_for'] = [
    'label' => t('Member for'),
    'description' => t("User module 'member for' view element."),
    'weight' => 5,
  ];
  return $fields;
}

Any field that is part of the $fields['user']['user']['display'] array is shown when the User entity is rendered and can be re-orderer from /admin/config/people/accounts/display. (Member for is the label used from the code I previously shown.)

Any field that is part of the $fields['user']['user']['form'] array is added to the entity form and can be re-ordered from /admin/config/people/accounts/form-display. (User name and password, Language settings, and Timezone are the labels used from the code I previously shown.)

In the case of nodes, it's not different. You just need to remember that instead of $fields['user']['user']['form'] you need to use $fields['node']['content type']['form'], and replace 'content type' with the effective content type for which you need to add fields to the entity form. In the case you need to add fields to the entity form of every content type, you should use code similar to the one used in node_entity_extra_field_info().
foreach (NodeType::loadMultiple() as $bundle) {
  // Add the description for the extra fields.
  // $extra['node'][$bundle->id()][...] = ...
}


Assign to node all child terms if parent term selected

You can use the Taxonomy Term Reference Tree Widget module

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.

How to use this module

Enable the Term Reference Tree module.
Go to the Manage Fields tab of any fieldable entity (such as a content type, taxonomy term, or user.
Add a new field with a type of Term Reference.
In the widget select box, select Term reference tree.

Note that you can also change any Term Reference field to use the Term Reference Tree widget, by editing that field and selecting Term Reference Tree on that field's Widget Type tab.


How can I make the Book Navigation also show the Summary of the Child Page?

--- Potentially not the best solution -----

I haven't tried this but looking at api.drupal.org I think you should be looking at overriding  template_preprocess_book_navigation the variables processed in this preprocess are used in book-navigation.tpl.php ( u are interested in changing output of $tree which is an unordered list by default) I think you can override the preprocess for book_navigation and use a different callback for $variables['tree'] instead of book_children. Your new callback would be based on book_children but additionally load teaser for those child pages.

I myself would like to see a better solution for this coz sometimes core design decisions are not what we need and would like to know if there are better solutions other than overriding theme engine and replacing a call to a core function with a custom one ( in this case book_children ) Let me know if you find a better solution or if this works.

Needless to say this will affect output of all book pages where book-navigation.tpl.php is used.

Cheers


Cannot log in site despite having credentials from settings.php

Okay I see what happened now.

I was trying to login to Drupal and not to the database, but I was getting the DB password from settings.php.

On the Drupal sites I setup in the past I used the database user and password as the Site Maintenance Account’s credentials, so I’m used to them always correlating. Since someone else set this one up they put the user and pw to something different. It's probably a security hole to do it the way I was doing it so I guess I need to fix that.


In your View, check the taxonomy argument and set the validator to Taxonomy Term. From there you can specify the argument type (and vocabulary where the term is expected to come from). Set the argument type to "Term name/synonym converted to Term ID" and that should help.


Auto-add today's date and time to new Entity title upon creation?

Option #1

For Drupal 7 you're looking at the Automatic Entity Label module if you're after a particular entity.

  "Automatic Entity Label" is a small and efficient module that allows
  hiding of entity label fields. To prevent empty labels it can be
  configured to generate the label automatically by a given pattern.

Possible option #2

Another option is available if your Entity has actions exposed to Rules.  Simple create a rul that reacts on entity creation, and set some conditions as per usual.  Then, in the actions do the following:

1) Add an action for Set data value

2) Find your entity (node for example) and look for :title under data selector (e.g. node:title)

3) Click continue

4) On the next page, set the data value to be whatever you need with tokens (so your example could be something like as [node:title] - [site:current-date])


Changing form field requirement via ajax

Thanks to @Clive for pointing me in the right direction.

I've managed to accomplish what I want with the following changes to the form_alter function:

$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change',
  'wrapper' => 'version-release'
);
$form['field_version']['#prefix'] = '
';
$form['field_version']['#suffix'] = '
';
$typeValueChangedByUser = $form_state->getValue(['field_type_app_details', 0, 'value']);
$typeToCheck = $typeValueChangedByUser ? $typeValueChangedByUser : $form['field_type_app_details']['widget']['#default_value'][0];
if ($typeToCheck  === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

And the following change to the ajax_callback function:

function ajax_type_callback($form, $form_state) {
  return $form['field_version'];
}


How to install certain modules only for specific site using Acquia Desktop

do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.?

Yes, you need to create a specific modules folder for the specific site(s) you wish that module to be available for. If you want it available on, say, 10 out of 20 sites, you'll need a copy in each site's modules folder. You can remove the need for this by making it available in sites/default/modules, but obviously it will be available to all sites in the multisite.

  are going to find it difficult to export sites to FTP for making the site go online.?

Completely depends on your deployment process. You'll probably want to review that process before implementing this on your live servers, but whether or not it's 'difficult' depends on what you need to do.


How do I show 2 images on row 1 and 3 images underneath on row 2 with Views?

You can define attachment display of view, in which u can display only 2 images with offset 0 under Pager section. and in page you can define image to show as 3, with offset as 2.

As attachment loads above the page, so it will show the structure accordingly.


Conditionally display a field based on another field's content by field.tpl.php

I don't think that you need a custom field.tpl.php or custom module. You can just copy the field.tpl.php from a field module and modify it. Look at comments above the field.tpl.php:

$items: An array of field values. Use render() to output them.
...
$element['#object']
$element['#field_name']
you can get user info from global $user object;

i think these are key variables which you can use.
E.g. (poorly modified version of field.tpl.php. But logic is like this):

<?php
  global $user;
?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>

      <?php
        if($element['#field_name'] == 'field_NAME') {
          if($item == 'MY_VALUE (e.g. free)') {
            $output = render($item);
          }
          elseif($item != 'MY_VALUE (e.g. free)' && isset($user->roles[MY_ROLE_KEY]) {
            $output = render($item);
          }
          else {
            $output = ''; // or whatever you want
          }
        }
      else {
        $output = render($item);
      }
      ?>

      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print $output; ?>

    <?php endforeach; ?>

//P.S. Putting your logic into .tpl is not good..


How to prevent taxonomy terms being duplicated on node form?

Though there is a module for help with taxonomy term being duplicate here, but like module page says, it doesn't work apart from taxonomy term and vocabulary forms.

So a solution I can think of in your scenario is to use hook_node_presave and compare value of both fields. If it match, you can think of some logic such as, create single term & set newly created tag for both fields.

Other hook can also help you such as hook_node_insert with your own logic to tackle this. Happy Coding !!


Drupal 8 Blog Autoposting To Facebook, Twitter, LinkedIn etc

There's a framework of modules under development as part of a 'Social initiative'. See https://www.drupal.org/project/social_post


Do exposed filters work in Views 7.x-3.3?

Okay I figured out the problem.

There is, as of today, incompatibility between Views and Theme Developer. If I disable Theme Developer views acts normally.

FYI for everybody else having this problem!


Unless you're changing the $node inside a node_save() or something, your changes won't make it into the database unless you add a node_save() after the change to $node.


TL;DR
Public file path is used for file uploads that happen in Drupal. Usually you want to use Drupal to manage content, that means article, users and files. This requires you to upload files inside Drupal application and this is where the public file setting comes into play.
Longer version
When you create a Drupal site, you can decide where all file uploads (which are public) should be located. The only rule is, that it have to be inside the webroot, so that they are accessible for download.
By default this is sites/default/files, but it could be /uploads or whatever you like.
This is used for when you actually use Drupal as a CMS and upload files on content like on articles, user profile pictures etc. When you upload files through Drupal and they are public, Drupal will save info about the file, know it's location and can do things with it.
Having the public path configurable is pretty smart, it means to change move or rename the upload folder and you only need you change one setting for it to work.
If you have FTP access you can upload any file to the webserver, it will be accessible to users etc. You should note that uploading files this way, means that Drupal wont know that they exist and can't actually use them in any way. It might be a good solution for your use case, but you are effectively bypassing Drupal as a CMS and if you plan on manually uploading all files through FTP, you will loose a lot of the file management features and the public file setting wont matter one bit.
Hope this clear things up for you a bit.


These are the tokens, more specific a custom/dynamic tokens implemented by Drupal core (token.inc) and managed by Token module.

See: List of tokens page for more details:

  Custom format [node:changed:custom:?]   "?" is a single, unquoted PHP date formatting character. Use this token multiple times to build a full custom format.


Term pages that list all the content that has been tagged with that term are built with "Taxonomy term" Views. You can edit that View to change what those pages show (/admin/structure/views/view/taxonomy_term).

Filter
The easiest change for you would be to add the Content type Filter (from the "Content" Category) to your Views so your visitors can choose manually which types to see listed.
Expose it to your visitors (this option is in the Filter Settings). This will show a filter at the top of each Taxonomy term page that will allow visitors to limit the content to only the chosen content types.
I recommend cloning (duplicating) the Taxonomy term Views, disabling the original and working on the duplicate so you can always refer back to it.

Contextual Filter
For a more automatic solution you can add a Contextual filter instead of a regular one (Contextuals are under Advanced View settings) to filter the results, and build a new Views Display to list the new taxonomy term links that are sensitive to the types of content.
There is already the "Has taxonomy term" contextual filter present there, you need to keep it.
Add another Contextual filter, named Content type, configure it with these options:
When the filter value is NOT in the URL
Hide view
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator Content type
Case in path Lower case
More
Transform spaces to dashes in URL
Rearrange the Contextuals so the type one comes up first, and the "Has taxonomy term ID" comes second.
Edit the "Has taxonomy term ID" Contextual filter and change its option under When the filter value is NOT in the URL from "Hide view" to "Display all results for the specified field".
This will enable you to add the content type into your path to have it automatically filtered by the type: /taxonomy/term/[ContentType]/[TID], for example: /taxonomy/term/article/5.
There is also an option to override the Title if you need to correct it to name only the content types filtered out.
To test that your Contextual filter is working you can enter the argument for it in the Preview with contextual filters: field and hit the Update preview button if you don't have it set automatically. To view all the results without filtering simply delete the argument or enter all at the Preview or at the end of your path. In this case Views takes 2 arguments so you need to include both of them, separated by /, e.g.: article/5, article/all.

List all links
You can now use Views to build a list of all links to your terms for each content type. It can be a Block Display where you override the "Has taxonomy term ID" to display a Summary, and adjust the Content type Contextual to provide a Fixed Default value, add another Display for your second content type (it doesn't have to be automatic since you only have two types).
There is more than one way of doing this, it's out of scope of this question, but it gives you enough to know which direction to take and learn more.


Redirect rule doesn't contain all the query parameters

That's the way drupal_parse_url() parses your URL. If you think this is wrong, you can escape your & characters and file an issue in the core Drupal issue queue.

$ drush php-eval 'print_r(drupal_parse_url("user/login?destination=node/4?cid1=[entity-fetched-household:0:contact-id]&cs1=[entity-fetched-household:0:hash]&cid2=[account:civicrm-contact:contact-id]&cs2=[account:civicrm-contact:hash]"));'
Array
(
    [path] => user/login
    [query] => Array
        (
            [destination] => node/4?cid1=[entity-fetched-household:0:contact-id]
            [cs1] => [entity-fetched-household:0:hash]
            [cid2] => [account:civicrm-contact:contact-id]
            [cs2] => [account:civicrm-contact:hash]
        )

    [fragment] =>
)


Check if you have activated these modules.
Views translation and  Block languages (i18n_block).

Then You need to change those blocks language settings in configuration. follow this: https://www.drupal.org/taxonomy/term/39286

tick "make this block translatable" and select the languages.
it will allow you to translate a block in to a language you want. you might need to create separate blocks for each language.

In a View check if "Field Language" selected as "Current user's language" in Advanced area.

also use a filter for the view "Content: Language (= Current user's language)"

This will populate the content by detecting the users selected language.
"


Creating a module does not automatically enable it.

I tried your code in a clean Drupal 8 installation and /hello show the page as expected.

Try running drush en hello_world to enable you module and you should be ok.

If that is not the case, then you can use drupal route:debug to see a complete list of your site routes, so you can know if your route is registered.


I found the answer through a patch in the menu block module.


Unable to upgrade from version 5.10.0 to version 8

The following code works for me in Linux Machine:
    cd /usr/local/bin
    mkdir drush-8
    cd drush-8
    composer require drush/drush:8.x
    ln -s /usr/local/bin/drush-8/vendor/bin/drush /usr/local/bin/drush8

Let me explain a little bit:

Go to folder /usr/local/bin
Create a new folder drush-8  * go
to the folder above
Install drush (here more info:
https://docs.drush.org/en/master/install/ )
Finally, create a Symbolic Links that point to new drush version


How can I schedule adding a new field collection item for all users?

I'm not sure about rules but you could do that in a custom module with a little code:

$uids = db_query("SELECT uid FROM {users} WHERE status=1")->fetchCol();
$accounts = user_load_multiple($uids);
foreach($accounts as $account) {
    $edit['my_field'][LANGUAGE_NONE]['0']['value'] = 'my new value';
    user_save($account, $edit);
}


How do I Print/Display Site information Form

<?php print drupal_get_form('system_site_information_settings'); ?>

You can output any form in Drupal using drupal_get_form once you know it's form_id (which is the function name that returns the form array)


Do not hack the core (change any of the files in the initial Drupal download) unless you are using a patch in the issues queue or making one for a registered issue, /includes is part of that core.

The reason for this is that you will not be able to reliably upgrade your Drupal site as new versions are released and it is very important to keep it updated for security reasons.

Do always test new things on a development copy of your site, never on your production site (at least not after launch).

That being said, the best part of the answer you referenced is:

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

To elaborate:

MySQL allows various different encodings in its storage engine.  Latin1 (often the default) stores all of the data in one way and allows a limited set of characters.  UTF8 is a much larger library of characters.  Characters that exist in UTF8 that don't exist in Latin1 (for example) will make your database cry because it doesn't know how to read them.

The solution is to tell your database to use UTF8 instead of Latin1.

There are instructions online for doing this in-place but I personally prefer to do a mysqldump and import the database into a fresh database that has been specifically set to use UTF8, then tell Drupal where to find the new database.

As Molot said in his answer, you need MySQL 5.5.3 or higher to use UTF8, so you may need to upgrade your version of MySQL.  If you're on shared hosting this could be difficult, you should be able to see your MySQL version in CPanel or Plesk, otherwise ask your hosting provider for support.


form_submit() and form_validate() doesn't work for tableselect

You either need to change the name of the submit handler so it matches Drupal's naming convention of FORM_FUNCTION_submit, e.g.

function deckslider_admin_settings_submit(&$form, &$form_state, $form_id) {
  dsm("Hello");
}

Or add the handler manually in your form function:

function deckslider_admin_settings($form, &$form_state) {
    global $theme;
    $blocks = _block_rehash($theme);
    $header = array(
        'title' => t('Block'),
    );

    $options = array();
    for ($i = 0 ; $i < count($blocks) ; $i++){
        $options[] = array('title' => t($blocks[$i]['info']));
    }

    $form['select_blocks'] = array(
        '#type' => "tableselect",
        '#header' => $header,
        '#options' => $options,
        '#multiple' => TRUE,
    );

    $form['#submit'][] = 'select_blocks_submit';

    return system_settings_form($form);
}


Views: two filters on one term reference (=wrong join)

Notice that filters are by default added in AND logic. You probably want OR logic so the one filter does not affect the other.

Of course if the two fields are not relevant at all you should have used different vocabularies (e.g. terms and someothercategory)and not only terms


How to avoid clearing of the form state?

This:

function module_form($form_state) {

needs to be changed to this:

function module_form($form, &$form_state) {

The function sig for forms changed in Drupal 7 to the second example above.


Using a view to attach fields from a content type to another one

What I would do:

Enable the query preview under Views settings.

Create a new View.
Make sure "Title" is a selected field, and that the titles of both "Scheduled classes" and "Class type" is available in the list.
Add a new relationship, pick the one representing your node-reference. Make it required.
Change the title-fields configuration to select the newly added the relationship.
You should now only have titles from "Class type".

From there on, you likely want to add a contextual filter on a nid so you can pick out "Class type" from a specific "Scheduled class".

I haven't used references in a while. If you get stuck already here, give the same thing a try with entity reference instead, just to see if it plays better together with Views.

Also see Learn Views with NodeOne, episode 11 is specifically about relationships.


How to display article from category and show it in block

Not sure of your exact need, between articles, your content type... Try something like that :

Go to admin/structure/views/add.
Fill in the form : Show Content of type article (or Your content type). If  sport news is a taxonomy category, tagged with sport news.

Uncheck create page, check create a block, display format table of fields, five items, then continue and edit.

Now in the left side of the form, click on add fields, choose the fields you'd like to display and settings for each field. Give a admin name to your block in Block settings, at the top of the middle column. You now have a block view with 5 items of content type article and the fields you selected.

Go to admin/structure/block, look for the block you've just created, and set the region where you'd like to display it, or click on configure to be more specific, displaying it on specific pages, for specific roles or whatever.


alternative to storing api keys in migration yaml files?

In Drupal 8, If the migration is one that is a config entity (shows up in /config rather than in migrations/) values can be overridden in settings.php or environment specific settings.

// Set migration settings from environment variables.
$config['migrate_plus.migration.node_article']['source']['urls'] = [getenv('CMS_ARTICLE_API_URL') . '/services/articles/facilities/all'];
$config['migrate_plus.migration.node_article']['source']['headers']['apikey'] = getenv('CMS_ARTICLE_API_KEY');


How to get the untranslate original string?

If there are multiple submit buttons on the form, I always prefer to have different submit functions for them. In your case I'd go for something like :

  $form['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Modify'),
    '#submit' => array('_my_function_to_go_to_previous_function'),
  );

and implement the logic inside the submit:

function _my_function_to_go_to_previous_function($form, &$form_state) {
  // Logic to go to previous step.
}

In this way you'll have more control over whatever you do. Works well with multistep forms.
You can also implement separate #validate function per button too.
Note that the $form_state parameter is passed by reference, which would mean you don't have to return anything from the submit function. Just manipulate the values inside the variable as per requirement, and then call

$form_state['rebuild'] = TRUE;

inside the submit function, so that the form rebuilds itself with the new values.


If you want to remove twig debug comments you can use striptags filter

Like the following:

{{ fields.view_node.content|striptags}}


Ajax enabled form stopped working - Ajax callback never called

Ok, this was just a stupid mistake in a another javascript. There the jQuery method .off() was used to remove event listeners which had the effect to remove the Ajax event listener.


You can create an RSS feed of your own using the Views module. It may seem a bit overkill to redefine the entire feed for just an extra parameter, but you may need more customization in the future, and having your feed served using Views allows all kinds of customizations in the future.


Entity reference field changes not shown in diff?

Problem was that the fields were set to hidden in Mange Display default display setting. Set to Label and it works.


Ajaxify certian content on the front page

You might be interested in Ajax Blocks, which allows you to load a block on a given page via AJAX, after the page has loaded.

See also: Calling a block by AJAX


This post discusses the very same issue. Also, as mentioned in this comment,

  1) You have to go to this page admin/config/regional/i18n/strings And
  set the language to english..than the translation strings can be made
  to your language.

  2) You need to go to admin/config/regional/translate/i18n_string and
  enable

  Select text groups  Fields 3) Then the fields are between the normal
  translation page to be able to translate:
  admin/config/regional/translate/translate

  4) After adding translation and nothing showing, back to
  admin/config/regional/translate/i18n_string Enable Fields and click
  REFRESH.

Hope this helps.


.module files are not required if you are not adding any procedural code. If you need to use any hooks, like hook_theme or hook_form_alter, yes, you need to do that in the .module file, because it cannot be done anywhere else. A lot of modules that extend base classes or provide services don't have any need to also include a .module file unless they provide something via hook_help, for example.

Some developers provide empty .module files, like:

<?php

// empty

I simply omit them if they have no code.

  And as a test I added a .module file but it seems it is not being read.

You'd have to elaborate on this, because any module that is enabled that has a .module file is definitely read. You may have to clear cache to pick up on changes.


how do I open a custom module form in colorbox popup?

I am suggesting you to use chaos tools for modal popup form. Its easy to implement and integrate into Drupal 7. I already used in my several sits.

You can find a great example of Ctools modal form at here


Yes, this is a very broad question, so I can only offer a broad answer.

Typed Data is only really interesting for you if you are a module like Rules, a context/token system or something like that, that wants to work with any possible data structure on any level, with generic code. Like displaying that famous rules data selector based on getting an arbitrary object (or actually a definition object about that object that you will get at runtime) and all you know about it is that it is typed data.

For most other cases, like when you know that you are working with an entity, or a specific field, you want to work with more context-specific API's, if available.

You specifically mention entity forms, note that work there is still going on, but the idea is that editing fields should work the same for base fields as it does already with configurable fields, with widgets, whose configuration you will set in your baseFieldDefinitions() method. Support for that very recently landed, see the node title definition in Node::baseFieldDefinitions(). There is no change notice yet but the relevant issue is #2144919 Allow widgets and formatters for base fields to be configured in Field UI.


How can I tell that my hook_nodeapi function is being called by cron and not a user?

How is cron being executed?  If done via crontab like

0 1 * * *   /usr/bin/wget -O - -q -t 1 http://my.site.com/cron.php

then I suspect that

function hook_whatever () {
  global $user;

  if (strpos(request_uri(), "/cron.php") === 0 && $user->uid == 0) {
    // from crontab
  } else {
    // from somewhere else
  }
}

would work.

Manually running from one of the admin pages may be trickier, but taking out the $user->uid check may suffice in that case.


Copy and paste it in the textarea, make sure you have full HTML filter selected, if y do not have that option, go to Text format and create a filter


How to add back button for specific content?

Duplicate your node.tpl.php file (in your theme's folder) and rename it to node--[content type].tpl.php. Use machine name of the content type, which can be found in Administer > Structure > Content Types
Replace content type with name of your content type. (i.e for page content type, node--page.tpl.php)

Don't forget to flush all caches when you have placed the new code in this new template.

Drupal will now use this custom template file for this node type, and the node.tpl.php base template for other types.


Multiple forms on the same page are causing conflicts?

I recently had the same issue and found a workaround in the corresponding Drupal core issue: The same form twice on one page with different arguments may process the wrong form when submitted.

The third comment suggests to enable FormState caching, and that worked great for me.

$form_state->setRequestMethod('POST');
$form_state->setCached(TRUE);


Is it possible to determine what attachments (JS libraries, CSS, etc.) are required by a node form?

The most elegant way to do that is define attachments in hook_form_FORM_ID_alter. You can specify css files, js files or libraries:

$form['#attached']['library'][] = array('system', 'jquery.cookie');
$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';
$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';


Drupal doesn't provide third level local tasks by own. You have to implement it, something like this:

/**
 *  @see: menu_local_tabs()
 */
function my_module_menu_local_tabs() {
  return array(
    '#theme' => 'menu_local_tasks',
    '#primary' => menu_primary_local_tasks(),
    '#secondary' => menu_secondary_local_tasks(),
    '#tertiary' => my_module_tertiary_local_tasks(),
  );
}

/**
 * @see: menu_secondary_local_tasks()
 */
function my_module_tertiary_local_tasks() {
  // The index of local task starts from 0, so you need the 2 level of local tasks.
  $links = menu_local_tasks(2);
  // Do not display single tabs.
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
}

function my_module_preprocess_page(&$vars) {
  $variables['tabs'] = my_module_menu_local_tabs();
}

All of this code based on core's localtask generation function, it's normally alterable, translation-ready, access checked:

menu_local_tabs()

menu_secondary_local_tasks()


Drupal 8 is great, and has a lot of improvements related to multi language sites. But Drupal 8 isn't ready yet, and it "will be ready when it's ready" (that's what some experienced Drupal-ers say, and I do fully understand that).

Also, after Drupal 8 is released (I've heard dates like somewhere in 2016 only, and it wouldn't surprise me), there are still all the contributed modules that will not be upgraded yet to Drupal 8. Today there are still Drupal 6 modules waiting for their Drupal 7 upgrade) ...

For all these reasons, I will continue to go for Drupal 7 for quite a while (probably at least the rest of 2015). Because of its maturity, and because I would not want to depend on a Drupal 8 release of either core, or any of the contributed modules that I "must have".

There is also that great presentation from David Reid about all those amazing contributed modules in Drupal 7, which are like backports of new Drupal 8 features.


Drupal 7: can't get SQL query to work that works outside of Drupal

Instead of the above one try the following query,

$date = date_create();
date_modify($date, '-4 week');
$interval =  $date->format('U');

$result = db_query("
SELECT timestamp
FROM accesslog
WHERE uid = :uid
AND path = :path
AND timestamp > :interval",
array(':uid'=>$uid,
      ':path'=>$path,
      ':interval'=>$interval))->fetchAll();


Uninstalled modules still in system table?

Drupal adds an entry in system table for each module present in the filesystem, even if it has never been enabled. This is the same for Drupal 6 and 7. In Drupal 8 the system table has been removed.

So, if you want to get rid of entries in system table for uninstalled modules, remove them from the filesystem once they're uninstalled.

See _system_rebuild_module_data() for details in Drupal7. In drupal 6 this function was called module_rebuild_cache().


how to enable access to a webform only from a link sent to user

You can do this by help of Deeplink module. Module page explains -

  Sometimes you want to be able to give simple URL access to content
  that would not normally be available to a particular user (or perhaps
  someone not even registered with the site).

  Deep link module allows the direct access to a specific item of
  content under certain circumstances and limitations. Such as one-off
  or time-limited deeplinks.


Select organic group on the user registration form

I managed to get this working. These very short instructions are indeed correct. But the first few times I tried to follow them I did not have any success. Therefore I thought it would be useful to explain the steps and potential pitfall in more detail.

I have broken this answer up into two parts. You may have already done the work in Part A of these instructions. I have included them so that if you are really struggling you can go back on a new Drupal installation and ensure that you have followed exactly the same steps as me. You may find this unnecessary, if so skim read Part A and check you are at the right stage before skipping to Part B.

Part A: Steps to install OG and Create an Organic Group (Can be skipped if already completed)

Install Organic Groups and enable it and its submodules (Organic groups register, organic groups UI etc.) as normal (You will need the Entity reference and Views_bulk_operations modules installed to enable these modules). You may need to rebuild the permissions after doing this – you should get a warning if required.
Install Organic groups register which is a submodule of Organic groups - You will need to in order to complete the steps
Create the content type that will be your group (Administration > Structure > Content types). I am calling my example content type ‘Special Group’. Important: in the Organic groups section at the bottom of the create content type select the ‘Group’ checkbox to allow this content type to be a group. Save the content type, you can add the other fields you need once you have everything working.
Create a piece of content using your group content type. (Content > Add Content > Special Group) I called mine My test Group.
In a new browser where you are not signed in, view the new piece of content e.g. ‘My test Group’. You should be able to see the ‘Group: request group membership link’.
Clicking on the request group membership asks you to sign in or register, and then you have to go back to the group to be able to join it. It is this step that we want to improve, by allowing a user to join a group from the registration form.

Part B: Steps to enable group sign up during registration

First we need to add the 'Group register' field to your group content type. To do this go to Configuration > Organic groups > OG field settings.

1.a. From the Bundles drop down, in the node section, select your group content type (mine is called Special Group).

1.b. From the Fields drop down select ‘group register

1.c. Click the ‘Add field’ button at the bottom of the page. After this has been done you should be able to see that the field ‘Group Register’ has been added to the list at the bottom of the page.

Next we need to add field to the user registration form.

2.a. Go to Configuration > People > Account settings > Manage fields

2.b. Edit the 'Group membership' field.

2.c. Select the 'Display on user registration form' checkbox and then save.

2.d. You can now see the ‘Group membership’ field in the Account settings field list with a machine name of ‘og_user_node’ and a field type of Entity Reference.

2.e. Warning: Because you have checked ‘Display on user registration form’ there is a temptation to believe that you have completed the task. If you go to register a new account you will be able to see the ‘Group membership’ field, however there will be no groups in the list. Obviously we do want the groups to be listed here. This is where a lot of users were getting stuck. Don’t worry about this. Simply continue to the next step.

Next we need to select which groups appear on the registration page (solving the problem discussed in 2.e.) The default behaviour of the 'Group membership' field that we created in step 2 is set to 'Do not show on registration page' in our group content type that we created in Part A step 2. We need to do two things – change the default so that new groups that are created have the right setting automatically and then update any groups that have already been created.

3.a. First we will change the default so that new groups that are created have the right setting automatically.

3.a.i. Go to Administration > Structure > Content Types and edit the group content type you created in Part A step 2 (mine is called Special Group).

3.a.ii. You can see the Group register field in the list of fields with a Boolean field type (see screenshot 6). Click edit to edit this field.

3.a.iii. In ‘Default value’ change the radio button to ‘Show on registration page’ and click save settings. Doing this means that all new groups that are created will be listed in the drop down on the registration page by default

3.b. Second we need to update any groups that have already been created.

3.b.i. Go to Content and filter the content by the group content type that you created in Part A step 2 (mine is called Special Group).

3.b.ii. You now need to edit each of the groups that have already been created. For each find the ‘Group register’ radio button group and change it to show on registration page.

4.Now you can test that this has worked.

4.a. First we will test our existing groups. In a browser where you are not logged in create a new account. You should be able to see the group that you created in Part A step 3 (mine is called ‘My test group’) in the Group membership list.

4.b. Second we will test that new groups that are created have the group register setting correct by default. Create a piece of content using your group content type. (Content > Add Content > Special Group) I called mine My second test Group. You should see that the ‘Group register’ radio button is already set to ‘Show on registration page’ as you are creating the content. In a browser where you are not logged in create a new account. You should be able to see the group that you just created in the Group membership list.

I have also added these instructions to the Drupal Community Documentation.


Webservices to create (Register) a new user

Try using the example reference below which displays the php code using OAUTH library with Services module.

Email verification needs to be done using the rules by adding condition to block user since using oauth it will be activated by default.

You can use the Facebook/Twitter end-point, consumer credentials(key & secret) replaced to Drupal services.

Reference:
http://www.covenantdesign.com/blog/drupal-services-rest-server-and-3-legged-oauth


Add another field, select Math Expression from Global group, then in there put something like [field_1_total] 2 [field_2_total]

there is not need any addition module


You should use the field_view_field() function. Have a look at Rendering Drupal 7 fields (the right way).


Set value for date field in hook_form_alter

The date field's a funny one, normally the field column name is the last in the array (like the first example you tried), and the default value is set on that.

For a date field though, the default value is an array, and it's one level further up, e.g.:

$form["field_price_date"]["und"][0]['#default_value']['value'] = $curDate;

For future reference, install the Devel module and use the dpm() function to print a breakdown of the form array to the screen (dpm($form);). It makes debugging this kind of thing so much easier.


How to make a link between Drupal and my ownCloud server?

As a first step you would need to share users between owncloud and drupal.

I found this github project that appears to allow your owncloud installation to use the users from the drupal database.

Anything beyond this point requires some coding.

Assuming that the above worked and you have the user shared between the two platforms, then I expect you would need to write a drupal module with that used the owncloud API to submit a file from a drupal form. You would also need to use the owncloud api to return a list of files associated with a user.

This would be a very crude implementation, which bypassed all of drupal's file handling functionality, and relied on your own code for every interaction with owncloud (I can't find an existing module). A more advanced module would aim to use owncloud as a backend for the file system, in which case you might want to look at the patterns used in the Droogle or dropbox modules and adapt them to the owncloud api.

Whilst writing this answer I found what looks to be an interesting discussion from drupalcon Austin entitled Collaborative Spaces: Integrating Drupal with Google Drive, Dropbox, and more. Maybe that would be of help.


How to change rendering of div order in a field?

You can use $form['#after_build'] to modify a form. Put below element at the end of your hook_form function.

$form['#after_build'][] = 'FORM_NAME_after_build'; //Calls function

After build function to change the position of DIV

function FORM_NAME_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("#edit-field-geboortedatum-und-0-value").insertAfter($(".description"));
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}


hmmmm . When i try it today i get an error message in the browser. I thought I had turned on error reporting in php.ini yesterday.

OS ubuntu 14. all the webdirectory is chown www-data: www-data .
ive tried chmodding the themes directory to 777 but I still get the error.

ive just got one user, I assume admin privileges havent changed with the upgrade

Warning: move_uploaded_file(/tmp/marinelli-7.x-3.0-beta11.tar.gz): failed to open stream: Permission denied in drupal_move_uploaded_file() (line 1639 of /var/www/devsite.org/includes/file.inc).
Warning: move_uploaded_file(): Unable to move '/tmp/phpgdOHHS' to '/tmp/marinelli-7.x-3.0-beta11.tar.gz' in drupal_move_uploaded_file() (line 1639 of /var/www/devsite.org/includes/file.inc).
File upload error. Could not move uploaded file.


How to add a book page: material types empty

Node/add works for me, but try admin/content/add.  Also check that you are logged on as the administrator.


An illegal choice typically means that the Form API received something it didn't expect when the form was processed. As Stan Ascher says, make sure you don't have modules enabled which modify the login process. You can tell if there are functions which end in _user or _form_alter in those modules.


Remove child elements from Taxonomy List Exposed Filters

Here is my solution which I think is quite a bit simpler. Simply remove the entries from the form if they start with a '-'. Note that you must have the 'Show hierarchy in dropdown' option selected for the children to begin with a '-' hyphen.

/**
* Implements hook_form_alter().
*/
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  if($form['#id'] == 'views-exposed-form-[your-view-here]') {

    foreach ($form['tid']['#options'] as $term_key => $term) {

      // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == '-') {
          unset($form['tid']['#options'][$term_key]);
        }
      }

    }

  }

}


How can I export the raw body of a node?

Under FORMAT, click on Settings, check mark "Keep HTML Tags"


How to implement something like OG which the groups can manage on their own?

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?". And for more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Cannot export theme settings to the .info file

The "omega" theme is the base theme for my theme. It needed to be Enabled, but not set as the default. After enabling the theme, the drush omega-export command worked successfully.


get user id from username or email without logging in

You can load the user with loadByProperties():

$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['mail' => $mail]);
$user = reset($users);
if ($user) {
  $uid = $user->id();
  $rids = $user->getRoles();
}


Need to know the most essential JS and CSS files for a Drupal 7 page

You can achieve this by making your module load your own html.tpl.php and in that version of the html template, you simply remove references to styles and scripts.

<?php print $styles; ?>
<?php print $scripts; ?>

For a viewer, you can probably do without the reams of CSS cruft that is loaded by default and add your own bare bones css & js either through a hook or by including it in your custom html template.

<?php print $path_to_your_reader_styles; ?>
<?php print $path_to_your_reader_scripts; ?>


How to see if there is a hidden admin role with an account that has no admin access?

... For a person who is just now learning Drupal, what would be the easiest way to see if their is a hidden admin role?

Talk to your friend, and perform these steps:

Step 1: ask for a screenprint (created by your friend, while your friend is logged in) of the list of roles shown via relative path admin/people/permissions/roles ... That will show you all "roles" defined in your site. Typically you'll have at least these 3 hardcoded (= delivered with Drupal) roles:

anonymous user (in the Drupal database this corresponds to role id = 1).
authenticated  user (in the Drupal database this corresponds to role id = 2).
administrator (in the Drupal database this corresponds to role id = 3).

Step 2: find out what the "user id" is for the user that you received, which you'll typically see (as part of the relative path) when you try to edit your own profile.
Step 3: ask for a screenprint (created by your friend, while your friend is logged in) of the granted roles shown via relative path user/uid/edit (whereas uid in it corresponds to your own user id) ... That will show you all "roles" you have been granted. Probably the role "administrator" will not have been granted.


You also need to grant permissions for the text format that the body field is using, e.g.


How to add a translation to an existing node/entity using REST?

You have to load the node first and than addTranslation. You can check if exists or not. This way I was able to do it.
    $transNode = Node::load($nid);
    $transNode = $transNode->addTranslation("en");
    $transNode->title = $title_EN;
    $transNode->body= $body_EN;
    $transNode->field_1 = $field_1_EN;
    $transNode->save();


You can implement hook_field_attach_view_alter to hide the field you've mentioned.

my_module_field_attach_view_alter(&$output, $context) {
  global $user;

  // check if the content is what you want to alter
  if ($context['entity_type'] != 'node'] || $content['view_mode']=='my_display') return;

  // only user with 'administrator' role can see
  $output['my_field']['#access'] = in_array('administrator', $user->roles));
}

enter link description here


Feeds Setup to Automatically Update and Delete Nodes

What version of Feeds are you using? Deletion of existing items is not currently in the latest stable release, but it is in the latest dev release of the Feeds module, 7.x-2.x-dev (2014-Sep-17).


You might get into the sub menu element with the ['#below'] object. not tested.

<?php

   /**
    * Implements theme_menu_link__[MENU NAME].
    */
   function YOURTHEME_menu_link__main_menu(&$variables) {

        $element = $variables['element'];
        $sub_menu = '';

        $element['#attributes']['class'][] = 'dropdown mm-menu-fw';
        $element['#localized_options']['attributes']['class'][] = 'url-link';

        if ($element['#below'])
        {
         $sub_menu = $element['#below']['#attributes']['class'][]= 'NEED-TO-ADD-CLASS';
         drupal_render($sub_menu);
        }

       $output = l($element['#title'], $element['#href'], $element['#localized_options']);

       return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

 }
?>


How to add 3 text boxes for a phone number field?

You can use Masked Input to format a field. It won't give you three text boxes. But it can solve your problem by formatting the text box like below,


Product reference field (autocomplete) length limitation

This limitation takes affect only when the product reference field widget ist set to "autocomplete". Set up the "product reference field" to checkboxes, list or turn of the widget when you use "bulk add" product


Resizing image from one field and save result in another field

have you seen Imagefield Focus?

This would give your users a much nicer UI to edit and crop images, and more importantly choose the correct regions to crop.


Views node count Taxonomy term as a field

https://www.youtube.com/watch?v=w22Utjm-chs

This video explains the process.

I found my old fields didn't work anymore once i added aggregation so, you might want to remember and fields and styling you have made because you might have to rebuild the fields once aggregation is turned on.

add a relationship (under advanced tab) 'Taxonomy term: Content with term'.
turn on aggregation (advanced tab at the bottom).
create a field 'Taxonomy Term: Name'.
add any other fields associated with the taxonomy such as image or any others you created.

Style everything and done!


Drupal 7: how to display the content of the field without the label in node--type.tpl.php?

You can do this by editing the Content Type and managing the display of your fields - click the Manage Display tab.

Once in there, you can change the label to hidden.

See screenshot:


The closest thing you come by is the maintenance-page.tpl.php, It doesn't cover all cases, but if things go wrong but not that wrong that Drupal can't post a page, it uses maintenance-page.tpl.php to display the error(s).

The error itself is displayed using drupal_set_message


Theming custom block type have multiple paragraph field

I Agree with Kevin's comment. Focus on theming the block.
Activate your theme's debug mode and view the template suggestions for your block. Add a new template and name it as one of the template suggestions, e.g. block--views-block--more-by-this-author-block-1.html.

It may help to duplicate the original block's code and paste into your new twig file, then find a good place to add your for loop.
Now you can loop through the paragraphs:

{% for item in content.field_home_page_carousel %}
    <p>{{ item.field_home_slide_image }}</p>
{% endfor %}


Expose the required fields in listing view

Use hook_form_alter() on the views_exposed_form. You can then change the type from select to radios or checkboxes.


You can test login form in this way:

When I visit 'user/login'
And I fill in "username" for "name"
And I fill in "userpass" for "pass"
And I press the "Log in" button
Then I should see the text "some text"


Panels + Recaptcha : how to add a (re)Captcha in my panels view?

You don't usually add a recaptcha directly to Panels; you'll want to add it to the appropriate form(s) (comment, registration, etc.)  When you do so, adding the appropriate form in Panels should automatically pull in the recaptcha as well.


how to convert node_uri (array) to url string

The path string is contained inside the path element of that array, so

$node = node_load(1);
$uri_array = node_uri($node);

$url = url($uri_array['path']);

should get you what you're looking for


How do I access the values of my results from a view

You need the method getValue() from each field to get the field data from row:

$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

If you want the rendered field use $field->render($row)


Using taxonomies with Field Collection in Drupal 7

Ultimately, I'd build a view that looks at the taxonomy term and then uses a node reference for other information supplied. The Second post in your issue points to another issue that contains a lot info about views integration and node references. If you can't find a solution there, I'd add your needs into the mix and follow that discussion.


How to add a new join table by using a hook view?

Here is a solution to add a join table to an SQL query in views.

Let's consider a view for a Person entity. We want to add a join to a PersonTag entity. Person has an id field (the primary key);
PersonTag has a person_id field that contains the PersonTag ID.

In your module_name.module, you would add this hook_views_query_alter() implementation.

function module_name_views_query_alter($view, $query) {
  if ($view->id() == 'views_id') {
    $definition = [
      'table' => 'person_tag_field_data',
      'field' => 'person_id',
      'left_table' => 'person_field_data',
      'left_field' => 'id',
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('person_tag_field_data', $join, 'person');
  }
}

After clearing the cache, you could check the SQL query used by the view and notice INNER JOIN is added to the query.

module_name is the name of your module, views_id is the ID of your view, person_tag_field_data is the table name for the PersonTag entity, and person_field_data is the table name for the Person entity.


Entity Registration: Override built-in registration list with custom view

In case someone is interested, I came up with a very nice and simple solution. I'm implementing hook_menu_alter() and overriding tab's "page callback" so that my custom view is called instead built-in registration list. (Note that solution below covers only tab for NODE entity!)

function MYMODULE_menu_alter(&$items){
    $items['node/%entity_object/registrations']['page callback'] = 'regstrations_view';
}

function regstrations_view(){
    $node = node_load(arg(1));
    return views_embed_view('my_registration_list_view','page', $node->nid);
}


How to add Checkbox Fields to User Accounts?

You can add checkbox list from Account Settings

Go to  Configuration >> People >> Account settings - http://example.com/admin/config/people/accounts/fields

Add Field >> Add a new field of List(text)

Add options and select options as unlimited (for multiple select)

Save and go to Manage Form display (/admin/config/people/accounts/form-display) change the checkbox widget to checkboxes/radio buttons.

That's it you can see the check boxes in user account form like this


How can I use user fields in panels title

Click on the gear icon on the grey bar for your field you have added, and click set as panel title.


How to apply an image style to an image field within a node template

I found this code somewhere as well and it seems to work within the template file.

 print theme('image_style', array( 'path' =>  $field_my_image[0]['uri'], 'style_name' => 'square_550'));

where the field_my_image is the name of your field  ....  I suppose it does the same as the above code.


Drush crashes after "command dispatch complete"

Drush is running out of memory.

In the case of re/indexing search data via Search API, the item in that issue queue for this is Better memory usage on indexing.

To work around these sorts of issues, you can increase the amount of memory used by Drush, without touching the memory limit used by your Web server.  See Configuring php.ini for details.

In my case, in my drush.ini, I increased it from:

memory_limit = 256M

to:

memory_limit = 512M

...and it solved my Search API (re)indexing problem.


Separate statistics on sites from Domain Access

I haven't actually tested this but you could maybe use separate database tables with different prefixes for the tables that the statistics module provides (accesslog, node_counter).

So your tables might be something like:

site1_accesslog
site1_node_counter
site2_accesslog
site2_node_counter

The domain_prefix module handles that. This module was a sub-module included in the main domain access module for Drupal 6 but was separated in Drupal 7.

There is also an issue here which seems to indicate you can use a small snippet of code in a custom module for this instead of using this drupal.org module, which is seemingly not well supported currently.

Keep in mind this is a fairly advanced usage of Drupal so I advise caution and lots of testing. Having said that though the tables you want to split are low risk compared to say the node or users tables.


WYSIWYG editor not displaying buttons and plugins

Please look at your browser javascript console (native, Firebug, etc.), when the page with TinyMCE is loaded and post any error here (if there is no error, please reload the page). It will make possible to determine the cause of issue.


Get current node's count (rank/order?) from node.tpl in a View which renders a list of nodes

Ok it looks like there's a similar thread but worded differently.

How to add classes to every X number of node in a array


Copying the template file from the bootstrap theme to your subtheme, and making the changes in the subtheme should work just fine.
Just note to clear the caches.


I just wrote a quick test of this hook and got what I think you're looking for...

Here is your chance to write your first module. If you're up on PHP, creating a module and enabling it is a 10 minute task.

Once you have a module that your drupal installation recognizes as enabled, you're well on the way. I tested hook_cart_item and found the entire content of the cart...

Note that there are several invocations of this hook, you'll want to inject your changes at the appropriate stage.
In the example code below, I simply made a folder in sites/all/module/modcart
Then, created a module called modcard.module, (as wall as a modcard.info file).

/**
  * Implementation of hook_cart_item()
 */
 function modcard_cart_item($op, &$item) {
  global $user;
  $test = $op;
 }

Reference: http://www.ubercart.org/docs/api/hook_cart_item

Hope this helps.


Are you using a module to handle the multisite configuration? A place where you can associate each site to a domain, theme and other configuration settings. Also you should be able to add https protocol to the desired domain.

If you don't use any module, check settings.php of each site looking for $base_url where you can change it from http to https.


got a Parse error webform.install in drupal 7

It's a bug in eAccelerator, which has been (apparently) been fixed. Webform requires PHP 5.3. The affected version of eAccelerator doesn't support all of PHP 5.3 -- specifically anonymous functions.

eAccelerator is not a "default setting" of a server. It is add-on software (presumably added by a host company, and not kept up-to-date).

you can follow this link on drupal website which touch the same issue


How to prepopulate a node reference field (checkbox)

Take a look here:

Prepopulate checkbox [#checked]

I have also been searching for a solution on how to do this.


Content Id is the node id in Contextual filters for Drupal 8 views.


Fatal error: Cannot redeclare THEMENAME_preprocess_page()

Function names in template.php have to be prefixed with themename_function. At the same time, you cannot have a function declared twice.

bootstrap_agency_preprocess_page() should exist once in bootstrap_agency/template.php, and the other should be bootstrap_agency_minimal_preprocess_page() in bootstrap_agency_minimal/template.php.

If you do not need to do any override, and the one theme is a subtheme, you can simply omit it from template.php. Otherwise, you would need to copy the function code in and amend what you need to amend.


How to place a specific comment on top of list

Found Best Reply module.

  Best reply module allows node authors to mark a particular comment as the best reply. It aims to encourage quality comments and to give some recognition to people posting quality responses.


Best practices when choosing a method of displaying content?

You want to display a single, featured product on the homepage. I would try using Views to create a Block which you can then include in the Content region on the homepage.

In Views, set the criteria, so you're pulling the appropriate content type. Perhaps you have some kind of "featured" or "sticky" flag. Add that to your criteria as well. Then if you want to restrict it further by taxonomy or sort it by most recently added and restrict the view to a single item, you can do that (see Pager settings; click "Display all items" and adjust settings).

Typically, Views is used to create a Page or a Block. Have yours output a block, then at sitedomain.com/admin/structure/block, locate the new Block and add it to the page wherever you want it.


First problem see: https://drupal.org/node/1909078#comment-8718835

"While I could be mistaken, I'm pretty sure that the error regarding "Unable to get the data property format..." (note the emphasis on format) when inserting a comment is due to code in:

message_notify/plugins/notifier/abstract.inc

Specifically these lines:

// Get the format from the field. We assume the first delta is the
// same as the rest.
if (empty($wrapper->{$field_name}->format)) {
  $wrapper->{$field_name}->set($output[$view_mode]);
}
else {
  $format = $wrapper->type->{MESSAGE_FIELD_MESSAGE_TEXT}->get(0)->format->value();
  $wrapper->{$field_name}->set(array('value' => $output[$view_mode], 'format' => $format));

}

The error occurs in the "comment insert" message type for the field_message_rendered_body field (and not the field_message_rendered_subject field) since it's a textarea that by default allows filtered text types to be selected (i.e. in Managed Fields, select the rendered body field and you'll see "Filtered text (user selects text format)" checked under "Text processing"). I haven't investigated fully yet but the bug can be avoided by selecting "Plain text" under "text processing" in the meantime (which will bypass the empty $wrapper->type->{MESSAGE_FIELD_MESSAGE_TEXT}->get(0)->format->value() in the ELSE statement)."


How to implement "Add another item" for custom forms?

One way to do this is by setting the form fields/field sets within a for function. Create a seperate function to increment the value via a submit button callback for instance and rebuild the form after you increment.

for($x=1; $x<=$variabletoincrement; $x++){
(insert form fields/field sets )
}

Here is code from form_example_tutorial_9 which shows information on how to create dynamic fields. This information is much more thorough than my explanation:

http://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/function/form_example_tutorial_9_add_name/7

http://api.drupal.org/api/examples/form_example%21form_example_tutorial.inc/function/form_example_tutorial_9/7


Each node has a score (percentage) which is updated weekly & want to show latest and the past scores in below/in a chart

You could implement them with a field_collection (currently not stable for either D7 or D8) or with the paragraphs module (currently stable for D8 only) if you need to keep track of old scores of each node and when they've been set.

I've also implemented similar things (paired values) by simply having two multivalue fields, one after the other, and letting editors keep them in sync manually, then rendering them together in a table or the alike with a custom template.

Using two simple multivalue fields (and they could be both numeric fields, if the time is something simple as the number of the week) may eventually simplify accessing such data in a view.


How to programmatically create new file/folder in Drupal 7 files directory?

To create folders you can use file_prepare_directory and pass FILE_CREATE_DIRECTORY as second parameter like so:

$new_folder = 'public://newfolder/';
file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);


"post_update" hooks that have been run are stored in the database, in the key_value table, post_update collection, but the data is serialized and awkward to update directly.

I used some of the details from @kiamlaluno's answer to create a drush script which you can use to reset a single hook. Here's a basic version (longer version is here):

#!/usr/bin/env drush

$key_value = \Drupal::keyValue('post_update');
$update_list = $key_value->get('existing_updates');

$choice = drush_choice($update_list, dt('Which post_update hook do you want to reset?'));

if ($choice) {
  $removed_el = $update_list[$choice];
  unset($update_list[$choice]);
  $key_value->set('existing_updates', $update_list);
  drush_print("$removed_el was reset");
} else {
  drush_print("Reset was cancelled");
}

And here's an example of what it looks like when you run it from the command line:

./scripts/reset_hook_post_update_NAME.drush

Which post_update hook do you want to reset?
 [0]   :  Cancel
 [1]   :  system_post_update_add_region_to_entity_displays
 [2]   :  system_post_update_hashes_clear_cache
 [3]   :  system_post_update_recalculate_configuration_entity_dependencies
 [4]   :  system_post_update_timestamp_plugins
 [5]   :  my_module_post_update_example_hook

# The script pauses for user input.
5

my_module_post_update_example_hook was reset


How to integrate a custom header and footer?

Use the Block system in Drupal. For example, create a custom block with the footer content, and place it in the footer area using the UI in Structure > Blocks.


D8 default front page is a view page admin/structure/views/view/frontpage/edit/page_1. Views in 7 and 8/9 is quite similar from a end user perspective meaning you should feel right at home. D7 and 8 default front page is /node as you see and normal access permission.


the menu is not being displayed when the first parameter is user

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7:

"page callback": The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

So page callback has to be omitted to fallback on the parents callback or has to be a function.


Getting two errors when trying to click Extend and Config tabs

I found this Gist about Fixing a Drupal 8 site with an empty install profile related to your problem (which I also have). The guide solved the problems, but created another.

  Drupal\Core\Extension\Exception\UnknownExtensionException: The module minimal does not exist or is not installed. in Drupal\Core\Extension\ExtensionList->getExtensionInfo() (linea 346 di /var/www/html/web/core/lib/Drupal/Core/Extension/ExtensionList.php).

Looking for the second problem, I found this issue and patch #112 should solve all your problems without using the first guide I mentioned.

If instead you want to follow the guide, which I think is the best way to go, to solve the new problem do what comment #110 says.
By adding the line minimal: 1000 to the core.extension.yml file


In my case I utilized hook_link_alter() to accomplish this.
Situation: in my menu links, I only need Contact Us to open in a new tab.

<?php
function MYMODULE_link_alter(&$variables) {
  if (!$variables['url']->isRouted()) {
    $uri = $variables['url']->getUri();
    // Only want the Contact Us to open in new tab.
    if ($uri == 'base:contact-us') {
      $variables['options']['attributes'] = ['target' => '_blank'];
    }
  }
}


How to send an email using Rules to everyone in an Organic Group based upon a date field?

To do what you're asking for, I would only use the Rules module, and the Rules Scheduler (a submodule of it), as further explained below.

Step 1 - Create a Rules Component

Create a Rules Component which looks like so (in Rules export format):

{ "rules_send_notification_to_og_members" : {
    "LABEL" : "Send notification to OG members",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules", "og" ],
    "USES VARIABLES" : { "current_node" : { "label" : "Current node", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "current-node" ],
          "type" : { "value" : { "book" : "book" } }
        }
      }
    ],
    "DO" : [
      { "og_get_members" : {
          "USING" : { "group_content" : [ "current-node" ] },
          "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "group_member" : "Current group member" },
          "DO" : [
            { "mail" : {
                "to" : [ "group-member:mail" ],
                "subject" : "Friendly reminder about some post in group",
                "message" : "Hello [group-member:name],\r\n\r\nThere is a reminder about a post with title [current-node:title] (located at [current-node:url]) which belongs to one of the groups you are subscribed to.\r\n\r\nSome more details about this node:\r\n\r\n- Price: [current-node:field-book-price]\r\n- Release Date: [current-node:field-book-release-date]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some details about the above Rules Component:

Component Variables: only a "node" (of type "node"), of type "parameter", labeled "Current node", and machine name current_node.
Rules Condition: use whatever extra condition you need/want, but actually you may not need any at all. As a sample, I just used "Content is of type" (with actual type = book).
Rules Actions:

Get group members from group audience, for current_node, and store the result in a list with machine name group_members.
Perform a Rules Loop, for each item in the group_members list, whereas the item is named group_member. And for each iteration of this loop, send an eMail to the group member being processed, with all sorts of data about the node included in the eMail title and/or eMail body (use your own imagination to make it fit your needs).

Step 2 - Create a Rules which schedules the Rules Component

Create a Rule which looks like so (in Rules export format):

{ "rules_remind_og_members_about_node_content" : {
    "LABEL" : "Remind OG members about node content",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "og", "rules", "rules_scheduler" ],
    "ON" : [ "node_insert", "node_update" ],
    "IF" : [
      { "og_entity_is_group_content" : { "entity" : [ "node" ] } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_book_release_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_notification_to_og_members",
          "task" : "Notify-OG-members-for-node-[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_notification_to_og_members",
          "date" : {
            "select" : "node:field-book-release-date",
            "date_offset" : { "value" : -259200 }
          },
          "identifier" : "Notify-OG-members-for-node-[node:nid]",
          "param_current_node" : [ "node" ]
        }
      }
    ]
  }
}

Some details about the above Rule:

Rules Events (either of both):

After saving new content.
After updating existing content.

Rules Conditions (all conditions must be true):

Entity group content, for entity = node.
Entity has field for field field_book_release_date, which is defined as a date field, and which you could consider as something like the release data of a book. Note: for nodes which don't have that field, or for which it is empty, this Rules Condition is false (so no Rules Actions will be performed).

Rules Actions:

Delete scheduled task, with Notify-OG-members-for-node-[node:nid] as the "Task identifier", whereas the task refers to the Rules Component created in Step 1.
Schedule component evaluation, with Notify-OG-members-for-node-[node:nid] as the "Task identifier", whereas the task refers to the Rules Component created in Step 1. And the actual date to schedule the execution of this Rules Component, is the date indicated in the node's field field_book_release_date, but with an offset of -3 days (pick whatever value for this offset the fits your needs), so 3 days before the date indicated in that field, the Rules Component is executed.

To be complete: the first Rules Action (to delete the previously scheduled task with the very same Task identifier), is to ensure that the Rules Component is only executed once. The typical scenario is that first the node gets created (and the Rules Component is  scheduled accordingly). But later on the node is updated. In that case, the request to execute the previously scheduled Rules Component is deleted, and a new request is scheduled again. And if the date itself was not updated, it will be scheduled for execution at the very same moment. But if the date was updated also, only the date of the most recent update will be taken into account. For this mechanism to work, it's important to use a unique Task Identifier, to be used in both Rules Actions. That's why I added the token [node:nid] to it (with a prefix like Notify-OG-members-for-node- so that it can be recognized by somebody looking at the currently scheduled Rules Components also).

Bonus tip - Resolving potential access issues

By using the Rules Scheduler, in the end the Rules Component will be executed when cron is running (the very first time after the date/time the Rules Component was asked to be scheduled). But cron jobs always run with user Anonymous.

So the question that remains is: "How will the eMail content look like if you're processing a node for which an anonymous user has no access?". If you run in any such access issues, the easiest workaround I can think of is that you improve the Rules Component by adding additional variables (used as "Parameter"), and so that these variables contain the values of the relevant node's fields that you want to be able to refer to in the eMail to be created. Since the user who triggers the Rule from Step 2 (due to a create or update of a node) should have (read) access, for sure these values will be passed to the Rules Component at the time of scheduling the Rules Component.

PS: I'm assuming this question is about D7.


Well, actually yes - overlay might be used too if needed. I have just done a quick write-up on this: http://zgadzaj.com/how-to-open-standard-content-pages-in-drupal-7s-administrative-overlay


How to hide a field of a Views row if comments are closed?

in admin panel of that view.. add Filter criteria and select "Content: Comment status"

and then click on apply and then choose closed option in options box

let me know if need any clarification...

Thanks
Ashish Raj


Additional field data stored outside of the field storage (in a separate table) doesn't load with the rest of the field

hook_field_load is being called, but only once after a cache clear. Either the loaded field or the whole node is cached somewhere. Remember to clear your caches!

I missed the initial load because I had yet to instrument the function with the typical bevy of dpm() and ddebug_backtrace() calls. Also the function itself isn't loading the data back properly, but that's outside the scope of the original question.