How do I use PathMatcher::matchPath() for a wildcard path?

In your sample you were comparing the internal path (/node/123) with a path alias pattern (/topic/*). This won't work. You need to do the matching with the path alias instead.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  if (\Drupal::service('path.matcher')->matchPath($current_alias, '/topic/*')) {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

You could achieve the same by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}


I think you're getting confused about how Drupal hooks work. You don't overwrite the existing function you instead create your own function that is called when the relevant part of the site is loaded. (So in this case node links)

So there is no THEME_comment_node_links_alter hook. There is HOOK_node_links_alter. So I'm guessing you looked in the comment module and saw comment_node_links_alter which is actually the comment module implementing HOOK_node_links_alter

In your theme/module you'd want to replicate what the comment module is doing so something like

THEME_node_links_alter(

With THEME being your theme machine name. THen that will mean your function is called and you can amend the variables

https://api.drupal.org/api/drupal/core%21modules%21node%21node.api.php/function/hook_node_links_alter/8.4.x


Minimizing cache clearing during development

Define all caches disabled, how do you do that?

The recommended approach is to only disable the render cache (as per the example local settings.php), but if you have a complex site and a slow, especially virtualized environmment, that can still take some seconds on every request.

Make sure you don't have xdebug or so constantly enabled. Use PHP7 if possible, that's basically 50% faster. It doesn't make mysql faster obviously, but unless you have very slow/bad queries, that is likely a smaller part of the whole response than you think. And if you have slow queries, then you need to find ways to optimize them, since it will get much morse when you have more parallel page requests.

If you clear cache manually, make sure you use drush cc render and not drush cr unless you actually change something that requires a full cache clear.

Cache tag invalidation doesn't really help that much, you could of course find out the cache tag of your specific block/view and invalidate just that, but there is no drush command for that yet). You could write your own cache backend that extends from the default and allows to ignore cache writes of cache IDs that match a certain pattern. But invalidation will require you to figure out the cache id of the thing, unless you work on the same thing for quite some time, that won't be worth the effort.

For more specific things, you'd need to profile the site to find out what is actually slow.


you can add a "global text area" field to the "header" of the view. Then add the link HTML in there:

add

The %1 will take the the first argument from the URL


name of last person who modified node - Display suite

The easiest way to see who did the last revision is to, well, enable revisions for that content type and require them. This won't help you with past edits, but going forward, every edit will create a new revision, which will have a user associated with it, so you can see who made the last edits.


Drupal 6: CCK Images broken (because of path) on multisite after copying/moving site

Changing site URL with a multi-site setup in Drupal 6 is problematic as the paths in the file table will be incorrect.  (See Migration failed)

In Drupal 7, you set up multi-site aliasing via the sites.php file (copy and edit the existing examples.sites.php),  which should be stored in the /sites directory.

For Drupal 6 you can try applying the multi-site aliasing patch.

As a last ditch effort (not best practice) you can also try editing the database (e.g. system and files tables) to change the file paths to reflect the new path.


Can I create a custom interface to power views search?

Write a custom views_handler_filter. See Views' API for a step by step introduction to implementing handler classes for Views.


file_delete deletes a file where it is located and its database record also.

First check file_load whether it is rendering an object file.

// load the file
$file = file_load('YOUR_FILE_ID');

// delete file from disk and from database
file_delete($file);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.

use drupal_unlink($fullpath) if files are not recorded in the file_managed table and file_usage table.

See this


How to group drush command sets together in sequence?

There are quite a few, I tend to use a shell script, but you can create your own drush command:
http://www.sitepoint.com/drupal-create-drush-command/

Here is an example of how I would do this with a shell script (mac / linux).

#!/bin/sh

# Default parameters to use.
version="7"
profile="standard"
user="admin"
pass="admin"
mysql_user="YourMySQLUser"
mysql_pass="RandomPassword"
mysql_host="localhost"
mysql_db="YourMySQLDatabase"
makefile="example.make"

# Collect parameters from the command line to override defaults.
for args in "$@"
do
  # Get the drupal install version.
  if [[ ${args:0:10} == '--version=' ]]
  then
    version=${args:10}
  fi

  # Get the installation profile
  if [[ ${args:0:10} == '--profile=' ]]
  then
    profile=${args:10}
  fi

  # User name to give the drupal admin user account.
  if [[ ${args:0:7} == '--user=' ]]
  then
    user=${args:7}
  fi

  # Password to give the drupal admin user account.
  if [[ ${args:0:7} == '--pass=' ]]
  then
    pass=${args:7}
  fi

  # Mysql username
  if [[ ${args:0:13} == '--mysql-user=' ]]
  then
    mysql_user=${args:13}
  fi

  # Mysql password
  if [[ ${args:0:13} == '--mysql-pass=' ]]
  then
    mysql_pass=${args:13}
  fi

  # Mysql host
  if [[ ${args:0:13} == '--mysql-host=' ]]
  then
    mysql_host=${args:13}
  fi

  # Mysql db
  if [[ ${args:0:11} == '--mysql-db=' ]]
  then
    mysql_db=${args:11}
  fi

  # Drush make file to use.§
  if [[ ${args:0:11} == '--makefile=' ]]
  then
    makefile=${args:11}
  fi

done

`drush dl drupal-$version.x`
`drush site-install $profile --account-name=$user --account-pass=$pass --db-url=mysql://$mysql_user:$mysql_pass@$mysql_host/$mysql_db`
`drush make $makefile`

Example usage:

~/path/to/script --profile=minimal --user=adminuser --makefile=meh.make


You can try the Field Conditional State module: With field conditional state module you can set #state form field attribute based on value selected in other form fields.

Module splits fields into two types:

Control field - field which set #state attribute based on the value from that field
controled field - field for which #state attribute is set based on the value from the control field.

Module supports AND/OR functionality for control fields which means:

AND - all choices must be selected to control the filed (example: field A will be visible when in field B option 1 and option 2 is selected)
OR - any choice will control field (example: field A will be visible when in field B option 1 or option 2 is selected).


How to output form element values as text?

Changing a form field to a markup element creates problems if the form field is checked by a form validation handler or a form submission handler: #markup elements are not passed in the $form_state['values'] array, which contains the current values associated with the form fields (and which is the array used by the form handlers—both the validation and the submission handers). This method works for form fields that use #element_validate, as #element_validate is also used from the #markup form fields.
If you are sure there aren't form validation handlers that check the value of the form fields you want only to show, then you can adopt this method. As third-party modules could add form validation handlers for those fields, I would not suggest to adopt it, if not in the case the form fields are created by a custom module you created, and no other developers will alter the form fields added by your code (or alter the form created by your code).

Using #attributes to make a field read-only is not a secure method (as Berdir pointed out); to be sure the form field values are not altered, you should compare them with the value contained in the form before it shows (which means to check the values contained in the $form array).
This method has still problems with the form validation handlers (and form submission handlers) because other modules will act as those values are not read-only; only your code will act like as those values are read-only.
The other reason to not adopt this method is that is "easier" to add the #disable attribute to a form field.

Another method is to change the form field type to #hidden. If you choose this method, then you need also to render the form field value using #prefix, and #suffix.

$form['field']['#type'] = 'hidden';
$form['field']['#prefix'] = '<strong>' . t("Field title: ") . '</strong>' .
  check_plain($form['field']['#default_value']);

As side note, if those form fields don't need to be visible to users, but they must be present in the $form_state array because other modules (including the one that created the form) implement form handlers, then you can change the form field type to #value.


remove all active sessions for given uid

Why not just delete the corresonding entries from the sessions table? e.g.
in sql, delete from sessions where uid = <uid>

This won't work if you're using memcache for your sessions table, but I imagine there's an equivalent if you are.


As @googletorp commented, the argument in the url have to keep a certain order if not Views won't know which kind it is. The recommended method for this is allowing a "wildcard" by providing an exception, in views you can configure this in the contextual filter options:

Then you simply put all instead of the year when not it's not available:
2- the category id alone : http://mydomain.com/events/all/4


I can't to expose the option sort Post Date in a view in Drupal 7

It seems to be an issue with having the devel module enabled.  If you are using it try disabling it and it should work.


Way to display View block only when a specific option is selected in Facet

In common situation, when facet is active - you have GET params in your url. You can use it as condition for programmatically display view. For example

if (!empty($_GET['my_facet'])) {
  print views_embed_view('view_name', 'display_name');
}


If the whole point of this is to be able to add wrappers around fields, an alternate option would be to use the field group module. Here is a video tutorial on it.


The clue was seeing the Drupal's modal just uses jquery widgets. So a simple Google for "jquery widget close event" lead me to this SO answer.
So the solution is:
$('#drupal-modal').on('dialogclose', function(event) {
    alert('closed');
});


Module with multiple Blocks in multiple files

* Method 1 - all blocks in separate file *

You can implement hook_hook_info() in your .modules file like this:

function hook_hook_info()
{
  $hooks['block_info']['group'] = 'block';
  $hooks['block_view']['group'] = 'block';

  return $hooks;
}

This tells the system that when hook_block_info() and/or hook_block_view() are invoked, any [MODULE].block.inc files should be loaded. So you can then put these two hooks into [MODULE].block.inc, keeping your block code in a separate file altogether.

* Method 2 - different file for each block *

You can add module_load_include() to include files for each block. To do this, in hook_block_view() you can do the following:

function hook_block_view($delta = '')
{
  if($delta == 'block1')
  {
    module_load_include('inc', 'MODULENAME', 'MODULENAME.block1');
  }
  elseif($delta == 'block2')
  {
    module_load_include('inc', 'MODULENAME', 'MODULENAME.block2');
  }
}

With this code, you can now put block1 in MODULENAME.block1.inc and block2 in MODULENAME.block2.inc. Note that MODULNAME should be the actual name of your module, though technically the module name isn't required, it's just a good practice.


How can I make a gallery of "boxes" of content consisting of an image and some text?

Module Image Field Caption

The Image Field Caption module adds an extra text area for captions on image fields. Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

The Readme.txt of this module details how you can tune/customize the image caption display, e.g. via theme templates (.tpl files), or via CSS.

Module Textimage

The Textimage module may be a good fit for what you're looking for. Excerpt from itsproject page:

  ... adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.

The project page of this module also includes some links about HOWTO manuals.

Other modules to consider

If the above modules are not what you're looking for, then I suggest you consider these alternatives:

Drupal 7 - How to Create an Image Gallery in Drupal contains some great docu about this topic also.
Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it. Just to mention a few of them (mentioned on the linked page):

Gallery formatter

  ... provides a CCK formatter for image fields, which will turn any image field into a jQuery Gallery.

Views Slideshow

  ... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Flexslider

  ... integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Node Gallery

  ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).

Multiupload Filefield Widget

  The File module of Drupal 7 enables you to select only one file at a time which can be very time consuming in case of many files. This module uses the 'multiple' attribute of html5 to overcome this problem and presents a widget called 'Multiple' that can be used with fields of type File.

  Using this Multiple widget in case of File fields it is possible to select more files at a time, which can be a big time saver.

Multiupload Imagefield Widget

  As an extension to Multiupload Filefield Widget this module presents the same widget to Image fields.

Field Focus

  If you are using ImageField and ImageCache, you might have had hard times trying to get Scale And Crop to show what you actually want of your images.
  That is what ImageField Focus was made for.

  It allows you to tell ImageCache what portion of the image you want to focus to, and what portion you want to be cut out.

Plupload integration

  Provides integration between for the Plupload widget to upload multiple files and Drupal. Plupload is a GPL licensed multiple file uploading tool that can present widgets in Flash, Gears, HTML 5, Silverlight, BrowserPlus, and HTML4 depending on the capabilities of the client computer.


Building a search View that respects access control

For the Search Views module there's an option that enables further access checks on indexed entities that will enable your Taxonomy Access Control permission check.

You'll find in the Views UI under Advanced > Query settings on via the Settings link. It is enabled via the Additional access checks on result entities checkbox. As a caveat, this option will make result counts, pagination, and other search result details behave oddly since  permission checks can't be made at index time.


Changing Pagination based on screen size

Short answer: No.

Long answer: The server doesn't know the screen size before it generates the HTML. The only way to do what you are suggesting would be to detect the screen size first, then redirect to one of two different views based on that.


How do I stop automatic double break tags in ckeditor?

The answer in this post helped me out:
CKeditor adding an extra
 tag when a
 tag is encountered

basically go into
administration > configuration > content authoring > text formats.

then select the text format that's causing problems and unselect "convert line breaks into html" and save configuration.

Then clear all caches on Drupal and browser. The content should go back to normal just by visiting the page while you are signed in otherwise saving over it should fix the problem.


File Transfer failed, reason: Cannot create directory /var/www/html/modules

The chmod a+x isn't enough, the directory should have write permission for HTTP server user, so try:

chmod 755 /var/www/html

Prefix with sudo if it's necessary.

or if you've already some files in it, try:

chmod -R u+rwX,go+rX,go-w /var/www/html

and if you're using Apache, you should change the ownership by:

chown -R www-data:www-data /var/www/html

If www-data is not correct, you can find the Apache user by the following command:

ps axho user,comm|grep -E "httpd|apache"|uniq|grep -v "root"|awk 'END {if ($1) print $1}


What is causing this error message when using search module?

You are declaring my_form function in two places somewhere in your block / view / Node where you are using php as filter. That is causing above issue.

Since you see above issue only in search page it should be an issue with blocks that are enabled in search page or search content...

Search in your database with keywords my_form using phpmyadmin or some other tool on all tables that will give you an idea from where the php code is getting executed !


You can do it via drupal's form API, First create your content type

1.Create a module (http://drupal.org/node/361112)

2.Create menu callback

function form_example_menu() {
  $items = array();
  $items['examples/form_example/tutorial'] = array(
    'title' => 'Form Tutorial',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_example_tutorial_1'),
    'access callback' => TRUE,
    'description' => 'A set of ten tutorials',
    'type' => MENU_NORMAL_ITEM,
  );
}

3.Use form api create form with necessary fields

function form_example_tutorial_1($form, &$form_state) {
  //your fields goes here
   $form['name']['first'] = array(
     '#type' => 'textfield',
     '#title' => t('First name'),
     '#required' => TRUE,
     '#default_value' => "First name",
     '#description' => "Please enter your first name.",
     '#size' => 20,
     '#maxlength' => 20,
   );

 }

4.Add necessary validation

function form_example_tutorial_1_validate($form, &$form_state) {
  //your validation goes here
}

5.Add form submission codes

function form_example_tutorial_1_submit($form, &$form_state) {
  //here you can process your data, in your case you want save it to a content type. so you can use node_save here
  $node = new stdClass();
  $node->title = $new_node['title'];
  $node->body['und'][0]['value'] = $new_node['body'];
  $node->type = 'article';
  //include all necessary fields
  node_save($node);

  //after success full save you can  write code for confirmation e-mail and redirection page
 }

6.As you have saved data to a content type, You can create a view with all required details, with edit delete functionality

If you have any doubt in module development and implementing form api you can get examples on this page http://drupal.org/project/examples

hope this may helps you


Drupal 7 - how to use jw player using videos located on a CDN

I did something similar for flowplayer. I had nodes created for legacy videos stored in Amazon S3 and added this code to the node--video.tpl.php:

 $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));

        print '

';
        print $video2;

There are other player options available as well, video.js seems to be more modern.


Exposed filter render as autocomplete but I need a select field

This is an advance solution.  Checkout how this guy did it for a similar problem by creating his own view filter. Creating custom filters in views 2


Block plugin's render array values ending up in $variables['content'] instead of $variables

This is how block templates work, they render the variable content.
{{ content }}

Your code though is using a block template inside of a block, which doesn't make sense, because the block template is wrapped around the block by Drupal automatically. You probably want to build the inside of the block like a controller output by using a custom template not derived from a block template, which you do when you don't start the template name with block__.
See https://www.drupal.org/docs/theming-drupal/twig-in-drupal/create-custom-twig-templates-for-custom-module


How to Add\Edit ECK entitys from front-end?

ECK create CRUD permissions for all entity type/bundles that has been created with it, so all you need to do is to give the users the permissions needed.

Since the path is located in admin/ you might need to create a link for users to use to create some of your custom entities.


Drupal 7, GPS lat, lng closes value, is it possible?

Have a look at this article: Creating a Store Locator with PHP, MySQL & Google Maps. Especially the section about "Finding locations nearby with MySQL" is hinting towards your solution.

As you can read in the mentioned  article, calculating the distance between 2 points given their lat/lon requires quite some math (Haversine formula). So, I guess that the performance optimization in the article you are referring to won't be possible. This because it will be hard to use an index to retrieve probable points.


Check out Simplenews module.

Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.


drupal 8.1 blocks config choices different from D8

This is not a difference between 8.0 and 8.1, it happens in both versions.

It is a core bug, triggered by ctools. See https://www.drupal.org/node/2632434


Javascript file attached via Drupal behaviours does not work occasionally

You are firing your event on document context, which happens only once (basically same as old school $(document).ready()). But a major point Drupal behaviors is that they are fired every time when somehing is added to the DOM, even when added with Ajax. (core's  BigPipe might add blocks with Ajax, this module is enabled by default)
So instead of the one-shot
  Drupal.behaviors.basics = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }
      ...do stuff

target the specific DOM nodes, e.g. if your carousel has a container

...

attach the behavior to its class:
  Drupal.behaviors.my_fancy_carousel  {
    attach: function (context, settings) {
      $('.my_fancy_carousel', context).once('init_my_fancy_carousel').each( function() {
        ...do stuff...

Also notice the .once('my_unique_identifier') part which makes sure your functions don't trigger repeatly on the same DOM node


How to lock a node from a certain role after changing state in workflow?

For this you should have to implement hook_node_grants and hook_node_access_records. It look something like that -

 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission_Content'][]=array($account->uid);
  $grants['Node_Edit_Permission_OtherRole'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id_content = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id_content ) {
      foreach ($user_id_content as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_Content',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }

    $user_id_other_role = /* list of user id which you want to block */;

     // Grant Permissions from these Users
    if (!empty($user_id_other_role ) {
      foreach ($user_id_other_role as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_OtherRole',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 1,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}


It's rendering as a list because you have set #size to 6, which means 6 rows will be visible. Either remove the #size property completely, or set it to 1 to display a normal dropdown.

From the documentation:

  #size: The number of rows in the list that should be visible at one time.


I recommend you to write the function as follow:

function ahml_form_alter(&$form, $form_state, $form_id) {
  //for register page
  if ($form_id == 'user_register') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Login page', 'user/login'),
    );
  }
  //for login page
  if ($form_id == 'user_login') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Register link', 'user/register'),
    );
  }
}

For additional details, check Drupal 6 Form API Reference


How to disable Ctools modal form from running on mobile devices?

You can hack wonders with a little "@mediaquery" and "!important".
I used this little bit with "modal_forms", not sure if the #id is the same.

@media (max-width: 580px) {
    #modalContent {
      position: fixed !important;
      top: 12% !important;
      bottom: 12% !important;
      right: 4% !important;
      left: 4% !important;
    }
    div.ctools-modal-content {
      width: 100% !important;
      margin: 0 auto;
    }
    div.ctools-modal-content .modal-content {
      width: 100% !important;
    }
}


How to prevent users editing their profile, but allow password change?

You might be able to use the module: Password Hustle

  Adds the password set form as an optional fields on the one click
  login. In other words, we encourage (hustle) the user into setting
  their password as they log into the site via a one click login.


Difficulty running tests, --group option not being respected

edit: This might be my issue.

Yes.

The error happens during test discovery, first it has to find all tests and then limit it based on the group.

The easiest workaround is simply to specifiy your module, then you don't even need the group. phpunit will only discover test in that folder, which will not just avoid this problem it will also be much faster.

$ ../vendor/bin/phpunit -c core/phpunit.xml modules/custom/mymodule


You need to use CSS last-child selector to theme last entry as a box ! You need to write css in you active theme style.css.

  I would also like a page with squares side by side, sorted by date.

For above you need to use views module and display nodes in grid format sorted by sort filter date.


How can I install composer packages with drush make?

You should use yoursite.make to download the Drupal module and composer.json for composer.

There is the Composer module that integrates Composer with Drush.

I hope that soon .make is going to disappear, replaced by composer.json; for that to come true, some issues need to be resolved, such as version number.

Composer packages are stored in the git repository; you can't use a composer package, but you can download the code. For example, for https://packagist.org/packages/symfony/symfony you can use the following.

libraries[symfony][download][type] = "git"
libraries[symfony][download][url] = " https://github.com/symfony/symfony.git"
libraries[symfony][destination] = "lib/symfony/"

Composer can build stuff recursively; of course, this will not work here.

See: http://cgit.drupalcode.org/drush/plain/docs/make.txt

Their is also https://github.com/composer/installers than can do the invert (install drupal module with composer).


It turned out to be fairly easy to do through custom module:

MYMODULE.module

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'poll_view_voting':
      $form['vote']['#submit'][] = 'MYMODULE_poll_view_voting_submit';
      break;
  }
}

/**
 * Submit handler for poll_view_voting form.
 */
function MYMODULE_poll_view_voting_submit($form, &$form_state) {
  // Invoke our custom rule and pass the loaded node object as an argument.
  rules_invoke_event('MYMODULE_poll_vote', node_load($form['#node']->nid));
}

MYMODULE.rules.inc

/**
 * Implements hook_rules_event_info().
 */
function MYMODULE_rules_event_info() {
  return array(
    'MYMODULE_poll_vote' => array(
      'label' => t('User casts a poll vote'),
      'help' => t('Triggers when users are casting votes on polls.'),
      'group' => t('MYMODULE HUMAN NAME'),
      'variables' => array(
        'poll' => array(
          'type' => 'node',
          'label' => t('Poll node'),
          'description' => t('Voted poll node.'),
        ),
      ),
    ),
  );
}


How to link taxonomy and views in a succinct way?

Forget views here and write a few lines of own code here. I had this problem also recently. Views is much to unflexible. You must do the following:

Create a route to your controller method
Get all relevant nodes in the method
Create a template via hook_theme() for the output.
Realize all your details! ;)

I needed around ~1 hour for this.


How to format multi value field as a grid?

We had a similar type of requirement to display in a grid/table layout multiple "Related" nodes rendered with a particular view mode (added with Display Suite), referenced through an Entity Reference field.
We came up with the following module: Grid Field Formatter, which is now available with a stable release.

If you look at the screenshots on the project page or the description in the content you should be able to find that it would seem to correspond to the initial requirements you described.

Feel free to let us know if I missed something, this doesn't work, or if you would have any more questions, comments or issues related with this requirement or module, I would be glad to provide more information or explain in more details.

Any more feedback, reporting, testing, comments or questions would be highly appreciated.
Thanks in advance!


How to see changes inside Paragraphs or Field Collections with Diff

You have to install and enable the Diff module.

  This module adds a tab for sufficiently permissioned users. The tab
  shows all revisions like standard Drupal but it also allows pretty
  viewing of all added/changed/deleted words between revisions.

Nothing else is needed.

Given a simple paragraph with a boolean field and a text field, if oyu change the textfield uou will get someting like this:


How to NOT turn element read only when waiting for '#ajax' callback in Drupal 7 forms?

I'm not sure I agree with your premise (interesting question, nonetheless). If performing a second operation while the first is already running would cause a problem client/server side, then that operation should definitely be blocked in my opinion.

If the only issue you have is that the blocking is done by way of disabling the text field, consider that it's just a matter of good UX. If the field wasn't disabled, but the functionality was, then there's no feedback to the user, who is left wondering why nothing's happening even though they're typing into a text field that has some rich functionality a few seconds earlier.

That said, if you want to override the behaviour of Drupal's AJAX have a look in the /misc/ajax.js file. You'll need to re-implement at least:

Drupal.ajax.prototype.beforeSend
Drupal.ajax.prototype.success
Drupal.ajax.prototype.error

Those functions set/remove the disabled attribute on the element. It should be reasonably straight forward to re-assign those functions in a custom JS file, and you can just remove lines like this:

$(this.element).addClass('progress-disabled').attr('disabled', true);

Or tweak it to something more palatable for your use case.


Search for content by title or add edit link to node

Yes, there's the Administration Views module, which replaces a bunch of the default admin pages with configurable views:

  Replaces administrative overview/listing pages with actual views for superior usability.

Features:

  Filter all administrative views via AJAX.
  Perform any kind of bulk/mass operations on items in administrative views.
  Filter content by title, node type, author, published status, and/or vocabulary.
  Filter comments by title, author, node title, or published status.
  Filter users by name, ban/blocked status, or user roles.

You'll also need the Views module for this


Is there an Authcache load event for fragments?

If you register your JavaScript as a behavior, then it is executed whenever the DOM changes, also when a fragment was loaded by authcache (see Managing JavaScript in Drupal 7). For example, the proper way to process any view - regardless of whether it is loaded via Authcache or not works something like this:

(function ($, Drupal) {
  "use strict";
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.view', context).once(function () {
        var view = $(this);
        // do something with view.
      });
    }
  };
}(jQuery, Drupal));


HTML E-Mails are being sent out as plaintext

Did you check the message setting of swiftmailer module? You can change the message format to HTML.


how to implement substring() in db_select statement

A couple quick greps suggest something like this...

$query->where('SUBSTRING(counter_date,1,10) = :arg', array(':arg' => $arg));

...should do it.


You're probably looking for entity_save().

If you want to use a metadata wrapper for a custom entity properties you need to implement hook_entity_property_info() to describe them to the entity module, especially setter callbacks which are used to set the value of the property.


Warning: Invalid argument supplied for foreach() in form_select_options() (line 2837 of includes/form.inc)

Looking on the code i suspect  that error lies in these lines-
$selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
 $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);

And according to my understanding adding these lines will fix this warning-

 $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
$selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);
if(!is_array($ort_options)){
    $ort_options=array();
}

Assuming that _ajax_city_dropdown_options($selected); returns options for second select list/ Check Boxes there can be some options in first Select List or there is none selected in first list for which there is no values available for second list. So returning an empty array will address this situation and prevent this error form appearing.


Searching by sku number but some products and new product are not showing using search api drupal 7

This is probably due to indexing by the search module. You need to run cron in order to build the search index.


Adding a new variable to account menu for twig rendering

In your THEMENAME.theme

function THEMENAME_preprocess_menu__account(&$variables) {
  $variables['account_name'] = Drupal::currentUser()->getAccountName();
}

And in your menu--account.html.twig

<div class="welcome-message">
  Welcome, {{ account_name }}!
</div>

Just tested and it works, so basically what you posted should work but probably you mistyped the twig file name which needs two dashes (--)


Handling uploaded resources for local development

Yes your database and files need to be kept in sync to avoid 404s as you describe.
With our setup all developers have access to a backed up copy of the database and files. The backups of both database and files are synchronised so together they're essentially a snapshot of the production site. I personally use a collection of Drush commands wrapped up in a shell script in order to restore this snapshot to my local machine.


Comment form is not working with ctools popup

I have found the issue. There is #action property in comment form which was redirecting to same form when we submit comment form. So, it seems that comment form is not working properly.

I have set up a global variable to remove #action property of the comment form if comment form is displaying in ctools popup.

/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  global $comment_popup;
  $comment_popup = 1;

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
    're_render' => FALSE,
    'no_redirect' => TRUE,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed']) || !empty($form_state['ajax_commands'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands[] = ctools_ajax_command_reload();
  }

  //If form is submittedd
  return ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));

}

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

  if ($form_id == 'comment_node_article_form') {

    global $comment_popup;

    if ($comment_popup == 1) {

      $comment = $form_state['comment'];

      // If not replying to a comment, use our dedicated page callback for new
      // comments on nodes.
      if (empty($comment->cid) && empty($comment->pid)) {
        // Change the action to call our function.
        $form['#action'] = url('modal/nojs/comment-popup/' . $comment->nid);
      }

      $comment_popup = 0;
    }
  }

}


The Webform (node) References tab should still be working as expected in rc27.


Solution:

function billetsalget_form_system_theme_settings_alter(&$form, &$form_state)
{
    /**
     * The group fieldset
     */
    $form['static_nodes'] = array(
        '#type'          => 'fieldset',
        '#title'         => t('Static Pages'),
        '#weight'        => -2,
    );

    /**
     * Get pages from db as options
     */
    $node_type = "page";
    $result = db_query(
        'SELECT n.nid, n.title FROM {node} n WHERE n.type = :type',
        array(':type' => $node_type)
    );
    $options = array();
    foreach ($result as $record) {
        $options[$record->nid] = $record->title;
    }

    /**
     * Select dropdown for Frontpage
     */
    $form['static_nodes']['front_page_id'] = array(
        '#type'        => 'select',
        '#title'       => t('Frontpage'),
        '#options'     => $options,
        '#description' => t('Set the page used as the frontpage.'),
        '#default_value' => theme_get_setting('front_page_id'),
    );

    /**
     * Run function when form is submittet
     */
    $form['#submit'][] = 'billetsalget_form_system_theme_settings_submit';
}

function billetsalget_form_system_theme_settings_submit(&$form, &$form_state)
{
    /**
     * Set frontpage to 'node/' + node_id selected in the form
     */
    variable_set('site_frontpage', 'node/' . $form_state['values']['front_page_id']);
}


Firstly it depends on your local environment. 700 Taxonomy terms are not a lot but calculation might be affected if your local environment is not powerfull enough. To mitigate your performance drawbacks take two steps.

Make sure you are using php 7 because it actually has a significant performance increase.
Increase your php memory limit to 128MB. Find the memory_limit variable in php.ini file and add 128MB next to it.

Now in the case of your calculation of depth after re-enabling the module issue I guess the correct path to take is the issue queue of the module itself. Issue Queue


You do not need to define any calculation rules. The problem is that you are checking out when the rule doesn't apply to you. For example, if you do NOT have the role B and you are checking out, when you are checking if the user has the role B, you will get this message.


Add properties to an entity hook_schema_alter

Using the third-party Entity API module, you can:

Implement hook_schema_alter().
Use something like db_add_field() to actually make the change to the DB in YOURMODULE_install() or updateN(). hook_schema_alter() does not actually create the field in the database. It just tells other modules at the code level that the field exists in the schema.
Implement hook_entity_property_info_alter(). This tells the Entity API module that this field exists as a property of some entity, where it lives in the database table, and how to access it.

Clear the cache to have the new properties showing up.

An example property in the $info array is basically the following one:

  $properties['survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make business logic easier.',
    // This is the schema field you made.
    'schema field' => 'survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );


How to use pager_default_initialize with entity field query?

If your motive is to create a pager for those results, I suggest you to use ->pager() on your EntityFieldQuery.

See this question EntityFieldQuery display pager

if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}

If you necessarily want to use pager_default_initialize(), see this post Creating pager in Drupal (without db_select() and PagerDefault)

$per_page = 10;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));

Hope these examples will help you.


Used this hook

function fee_management_views_pre_render(&$view) {
  if($view->name == 'payment_schedules' && ($view->current_display == 'receive_payments')) {
        $total_payable_amount = 0;
        foreach($view->result as $key => $payment) {
            $total_payable_amount += $payment->fee_schedule_instalments_amount;
        }
        $view->attachment_after = "<div> Total Payable Amount: $total_payable_amount</div>"; // does not work with fee_management_views_post_render

    }
}


Install the String Overrides module, search for the string, and replace it with your custom one.


"Explanation or submission guidelines" missing

That information is displayed in the help block. Make sure the theme you are using on those pages has a help block.

The Seven theme does have that by default, but either you've configured the node add/edit pages to use the front page theme, or you removed the help block.


How do I delete a Panopoly landing page?

Thank you @Patrick Kenny for the information. I prefer not to "hack" as it does cause difficulty updating.
My Solution
On admin/structure/pages/edit/mypagenameI clicked the Delete tab that appeared after disabling it.


How does drupal 7 know its version? which file does it check?

The VERSION constant is defined on line 11 of bootstrap.inc:

/**
 * The current system version.
 */
define('VERSION', '7.41');


See https://www.drupal.org/node/2253257, wich would do this by default.

It's pretty easy to do it for your own link, note that the patch there is out of date. Instead of the accepts thing, you simply put data-dialog-type and data-dialog-options on your link attributes. See also https://www.drupal.org/node/2488192 that describes this change and contains lots of examples.


Loop through multiple values from an array to create multiple arrays

Try this to loop the $build variable :)
// define variables
$organisers[] = "";
$organiser_email = "";
$organiser_name = "";
$email_delimiter = "; ";

// recreate the array from your example
$organisers['und'][0]['target_id'] = 20;
$organisers['und'][1]['target_id'] = 345;
$organisers['und'][2]['target_id'] = 678;

// populate $build variable
$build['field_eventorganizer'] = array(
      '#theme' => 'registration_property_field',
      '#label' => 'Event Organiser(s)2',
      '#classes' => 'field field-label-inline clearfix',
    );

// because the numbers are nested in the array, I've chosen to use `for` instead of
// `foreach` to use $i as the iterator then rebuild what I'm looking for in the loop. I've
// used count($organisers['und']) because the next piece of the array is the number we are
// using to load user data.

for ($i = 0; $i < count($organisers['und']); $i++) {
    // load the user object based on $i
    $organisers = user_load($host_entity->field_eventorganizer['und'][$i]['target_id']);
    // fetch loaded users email
    $organiser_email = $organisers->mail;
    // fetch loaded users name
    $organiser_name = $organisers->name;
    // populate $build variable
    $build['field_eventorganizer'][] = array(
      '#items' => array(
        array('#markup' => l($organiser_name, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
      ),
    );
}

Side note: Not sure if it was intentional or not, but be careful of your plurals. You are using $organisers and $organiser_email which can sometimes be missed and cause a headache.


How can I create a new field with a line break in it?

Maybe the "p" tag doesn't work, because has been escaped and the Text format chosen is "Filtered HTML", see the "Allowed HTML tags" below to be sure that the "p" tag is allow.

Choose "Full HTML" for not escape.

Greetings.


The problem is you're trying to use the same system_main content type variable that's not always defined. Try this instead:

$node = menu_get_object();
$type = isset($node->type) ? $node->type : 'none';
$type = ($type == 'none' && arg(0) == 'node' && arg(1) == 'add') ? arg(2) : $type;
$content_type_class = 'content-type-'.$type;
$variables['classes_array'][] = $content_type_class;

That should give you a $classes_array var with either "content-type-TYPE" or "content-type-none" for pages that aren't associated with nodes.


Add type='tel' attribute to webform field

Drupal 7 core field doesn't support HTML 5 form elements.

You should try the Elements module to do that.

  This module intends to become a repository for advanced form elements. Supports HTML 5 standards like: (url, email, search, tel, number, range)


There are some examples on drupal.org of adding a pager to the page, if you want to use the one that core uses:

https://api.drupal.org/api/drupal/core%21includes%21pager.inc/function/pager_default_initialize/8.2.x

The second example should work for you:

  $page = pager_find_page();
  $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
  $offset = $num_per_page * $page;
  $result = mymodule_remote_search($keywords, $offset, $num_per_page);

  // Now that we have the total number of results, initialize the pager.
  pager_default_initialize($result->total, $num_per_page);

  // Create a render array with the search results.
  $render = [];
  $render[] = [
    '#theme' => 'search_results',
    '#results' => $result->data,
    '#type' => 'remote',
  ];

  // Finally, add the pager to the render array, and return.
  $render[] = ['#type' => 'pager'];
  return $render;

I have done this before in my own wired up search pages, it should solve your issue.

You can replace $num_per_page above with 10, if you do not have a custom module to store the setting.

You could go further, and in your code create a service that handles just attaching the pager. I was doing some sandboxing exploring the search API, and came up with this. First, you need to define your service and inject it to your controller (I refer to mine as pager_service).

  /**
   * @var \Drupal\velirsearch\Service\PagerService
   */
  private $pager_service;

  /**
   * SearchResults constructor.
   * @param \Drupal\velirsearch\Service\PagerService $pager_service
   */
  public function __construct(PagerService $pager_service) {
    $this->pager_service = $pager_service;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    $pager_service = $container->get('velirsearch.pager_service');
    return new static($pager_service);
  }

Then, a method that attaches a pager:

     /**
       * Convenient method to obtain a pager to attach from the pager service.
       * @param $totalRows
       * @param $limit
       * @return array
       */
      protected function attachPager($totalRows, $limit) {
        return $this->pager_service->getPager($totalRows, $limit);
      }

Then, the service:

namespace Drupal\velirsearch\Service;

use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class PagerService implements ContainerAwareInterface {

  use ContainerAwareTrait;

  /**
   * @var \Symfony\Component\HttpFoundation\Request
   */
  private $requestStack;

  /**
   * PagerService constructor.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $requestStack = $container->get('request_stack');
    return new static($requestStack);
  }

  /**
   * @param $totalRows
   * @param $limit
   * @return array
   */
  public function getPager($totalRows, $limit = 10) {
    pager_default_initialize($totalRows, $limit);
    return ['#type' => 'pager'];
  }
}

Then, when you need it...

  $render[] = $this->attachPager($results->getResultCount(), 10);

  return $render;

You don't necessarily have to go that far, I was just looking for ways to reduce the code needed to attach a pager to different instances of search result controllers. YMMV.

Note that I did not use the third argument to pager_default_initialize, $element, which you will need if your page will have multiple pagers on it.

getResultCount(), by the way, is a method provided from Search API ResultSet class.

edit: now looking at my answer, your pager service does not need to inject the RequestStack at all. I was probably thinking of another idea and never finished it or figured I did not need it.


How to create a block that shows recently viewed products/nodes for users?

recently_read seems to have evolved
or do it with flag module (although not described in the linked tutorial, flag can also handle anonymous users)


If you want to create a voting module you should look into Voting API, it's an API module that offers common functions and database storage for voting modules to use.

However, since this is a learning excercise, you might want to do it all yourself, in this case:

Use hook_schema() to define your database schema (the example on the documentation page is pretty self-explanatory!)
In Drupal 6 you need to manually specify which schema to install so implement hook_install() and hook_uninstall():

function mymodule_install() {
  drupal_install_schema('mymodule');
}

function mymodule_uninstall() {
  drupal_uninstall_schema('mymodule');
}

An example of a hook_schema might look like this:

/**
 * Implementation of hook_schema()
 */
  function mymodule_schema() {
    $schema['mymodule_votes'] = array(
      'description' => 'Your schema',
      'fields' => array(
        'vid' => array(
          'description' => 'vote id',
          'type'        => 'serial',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'nid' => array(
          'description' => 'node id',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'vote_up' => array(
          'description' => 'number of votes up',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
        'vote_down' => array(
          'description' => 'number of votes down',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
      ),
      'primary key'     => array('vid'),
      'indexes'         => array('node id' => array('nid'))
    );
    return $schema;
  }


Multi step form with click and state logging in Drupal 7?

I can't say that this is the best way, but you can achieve that using the Webform module.

You can create multi step form using Webform module. Add Page break type to form components to split the form.

In Advanced Form Settings you can manage the multi step form actions like 'Automatically save as draft between pages and when there are validation errors' options.

In you want to provide advanced navigation bar for multi step web from you can try the Webform steps module

  This module provides a navigation bar for multi-page webforms. The navigation bar is a set of buttons placed at the top of each webform page. The buttons allow free navigation between steps that have already been visited.


Following example unsets the filter average when user is NOT administrator, you can modify it to your specific case.

use Drupal\Core\Form\FormStateInterface;
function my_modulename_form_alter(&$form, FormStateInterface $form_state, $form_id){

  $roles = \Drupal::currentUser()->getRoles();
  $is_user_admin = in_array("administrator", $roles);
  $is_exposed = $form_id == 'views_exposed_form';
  $is_filter_set = isset($form['average']);

  if ( $is_exposed && $is_filter_set && !$is_user_admin ) {
    unset($form['average']);
  }
}

If you want to unset only on a specific view exposed form use this condition

$is_our_view = $form["#id"] == "views-exposed-form-article-page-1";


I'm not sure there is an easy answer to this right now. Product IDs are updated on licenses when a line item is created or updated. This happens in commerce_license_commerce_line_item_presave().

This gets complicated if you're using Commerce License Billing because your order renews according to your billing arrangement. If you are using that, then you'll need to review the code in there and figure out a way to save a new order that will be the one that gets renewed.

Otherwise, you could just create a new order, set the correct product, revoke the old license, and then complete the new order and then a user will have a new license and the old one will be gone.

If you have more questions, the issue queue is probably the best place to get help and provide feedback.


How to programmatically create a title for a new node?

Here's how to do it with an entity builder callback.

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

//Implements hook_form_FORM_ID_alter()
function agenda_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $form['title']['#access'] = FALSE;
    $form['#entity_builders'][] = 'agenda_node_builder';

}

function agenda_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state)
{

    $date_of_meeting = $node->field_date_of_meeting->date->format('Y-m-d');
    $node->setTitle('Agenda for meeting on '.$date_of_meeting);

}

Notes:

I found that the callback had to be set up in hook_form_BASE_FORM_ID_alter() rather than hook_form_FORM_ID_alter in which case it didn't get called.
Didn't get to the bottom of this but it's probably something to do with the fact that alter hooks are called in the following order: hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter().
Nodes #entity_builders offer a Node entity object for modification before being stored when the form is eventually submitted.

Thanks to @Berdir for the pointers.


Set (add) group role using Rules when organic group membership is updated?

You should note that group role is not a field or property in the og_membership entity. The og_membership entity contains the properties etid, entity_type, group_type, and gid. There are other properties, but those are the ones you are interested in. When a user is added to a group, the entity_type is user and the etid is the user id. When node content is added to a group, the entity_type is node and the etid is the node id. The og_membership entries are not updated very often, so I'm not sure why using the event "User has become a group member" isn't sufficient. Assuming you really do want to change a users group role when the og_membership is updated, then you need to verify via rule conditions that the og_membership group type is node and the og_membership entity_type is user. Then you can use the Grant OG Role action. The rule export would look something like this:

{ "rules_205092" : {
    "LABEL" : "205092",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "og_membership_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "og-membership:group" ], "type" : "node" } },
      { "entity_is_of_type" : { "entity" : [ "og-membership:entity" ], "type" : "user" } }
    ],
    "DO" : [
      { "og_grant_og_role" : {
          "account" : [ "og-membership:entity" ],
          "group" : [ "og-membership:group" ],
          "roles" : { "value" : { "licensee" : "licensee" } }
        }
      }
    ]
  }
}


how to grant a user to only access the performance area of the configuration screen drupal 7

you can write a simple custom module to do this for you.
as you can see.with hook_menu_alter you can alter all menu in drupal. And by overriding it's access callback you can have your custom function to grant access to your users. Here is a sample code that check if user has an 'editor' role.then it return true and user can access performance.

function MYMODULE_menu_alter(&$items) {
  $items['admin/config/development/performance']['access callback'] = '_accesscheck';
}

function _accesscheck(){
  global $user;
  if(in_array('editor', $user->roles)){
     return TRUE;
  }
  return FALSE;
}


register.json does not login the user or return the user's session/token/password

Not sure if you need an answer at this point (or if this is even one), but it looks like you have "Require e-mail verification when a visitor creates an account" turned on?

In your image, in the second window (where you see the message from drupal_set_message()), it says that an email was sent and you will need to follow instructions to gain full message.

To turn this off, navigate to /admin/config/people/accounts and uncheck Require e-mail verification when a visitor creates an account.

If you look at the user table in the database, the status column should show a 1 for enabled, 0 for disabled (meaning he hasn't clicked on the link in the email).

Hope it helps!


Calculate field value based on another field value with Rules

Try Computed Field

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of CCK fields. So start cooking up your PHP based values!

Check Conditional Fields too

  Define dependencies between fields based on their states and values.


I am getting a PDO error which seems related to the Media module

it seems you have not done the update completely. one part of Drupal updating is Database updating.

there are some solutions to update it.

solution go to YOUR_WEBSITE_ADDRESS/update.php  the go through the steps.
solution if you have drush, run drush updb


How to update/change anonymous author to authenticated current user upon logging in?

Try using the trigger 'after saving a new user account'.  You don't want to check for content every time they log in, just when they create an account that matches email addresses with those node.

For security purposes you should probably prevent people from being able to change their email address too or they might somehow steal someone else's content.

As for people who create content when they already have an account but are not logged in: create a rule that checks for accounts when a new node is saved.  So in summary:

New users should claim existing content when the 'after saving a new user account' is triggered.
New content by existing users (that are not logged in) should be automatically claimed by the user account upon saving the node.

Neither of these events require you to check when a user logs in.


Static page on main domain and Drupal on subdomain

You can solve this one using a RewriteRule in your .htaccess file. What you basically will do is check if the request is destined for your main domain (both with and without the www), and if so, tell Apache to go fetch the files from somewhere else. All this is done on the server-side, so the browser doesn't see a thing about this.

For the example below, I assume that Drupal is installed in /var/www. If it's installed somewhere else, update all occurrences of /var/www below.

Create a new directory /var/www/static_main_domain. This directory will contain the static content of your main domain.
Add the following lines of code to your .htaccess file (preferably immediately behind   the RewriteEngine On):

      # Check if the request is destined for www.yourdomain.com OR
      RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC,OR]
      # Check if the request is destined for yourdomain.com
      RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
      # If so, go get the requested files from the static_main_domain subdirectory.
      RewriteRule ^(.*)$ static_main_domain/$1 [L,QSA]

For more info, check this: http://httpd.apache.org/docs/current/mod/mod_rewrite.html


Restricting Video upload to mp4 format alone - in media module

Go to admin/config/media/browser to change settings.


OG groups: How to check if user is a member or not?

For the 7.x-2.x branch of Organic Groups you need to use the following code.

og_is_member('node', $gid, 'user', $user)

'node' is the entity type. The function og_is_member requires 4 parameters to return the correct value.


There are two main ways of doing this: You can create a second content type which is the same as the Basic Page content type except with the additional fields that you require, or you can just add those fields to the Basic Page content type and only fill them out on the single node you want them to appear on.

As for how to show a list of nodes on another node, I would highly recommend the Entity Reference module. This allows you to add a field that is just stored as a reference to another node.

Original answer (I am leaving this in because it is another way to accomplish a similar outcome):

Using Views you can create the list of nodes that you would like to display on the page. The new version of views makes it super easy to do that. From there you have a couple options, depending your level of skill with theming and how much control you need to have over where the list of nodes displays:

A Block - Create a block display for your view. Place the block in the same region as the main content block.
node--NODEID.tpl.php - You could add a template suggestion to your theme to override the specific node that you want to add the list to. To do that you would need to:

Create a node--NODEID.tpl.php file, replacing the NODEID with the nid of the node you want your list of nodes to show up on.
Embed your view in the node template using the following code:

<?php print views_embed_view('MY_VIEW', 'MY_DISPLAY', $node->nid); ?>

Where MY_VIEW is the machine name of the view you created and MY_DISPLAY is either "default" or the machine name of a specific display in your view.

Here is an example: http://api.drupal.org/api/views/views.module/function/views_embed_view/7#comment-32858


Generating pages with multiple views based on url parameter

Create 7 different views, one for each content type. Create a block display for each view, and use block layout to put them all on one page.

Use contextual filters for the block view to get an argument from the URL. I believe it's a bit odd to configure:
"in the section 'What to do if the URL is not available' select ' Provide default value' and select 'Raw value from URL from the dropdown box. From the 'Path Component' box select the position in the URL that your contextual filter gets its value."

This is a straightforward Drupal approach, should be performant.

Alternatively, you could use Views aggregation to use only 1 view, divided into 7 different groups, and use CSS wizardry to adjust the layout.

Which approach you prefer depends on whether you want to be able to customise each view, and whether you want to use UI rather than CSS to control layout.


Creating an "unzip" module that can interface with Content created through the GUI and through node.create by was of Services module (Drupal 7)

I think the best place for your code is in a custom module, in hook_node_insert() and hook_node_update(); they're fired when a node is created and updated respectively. As the services module uses the standard node save/submission functionality these hooks will be fired even when using services.

It would make sense to keep your un-zip code in that same module.

This is a brief example just to show what I mean:

function MYMODULE_node_insert($node) {
  // Get the file ID from the node field
  $fid = $node->field_file[$node->language][0]['fid'];

  // Load the file
  $file = file_load($fid);

  // Pass the file path off to the unzip function
  $result = _my_unzip_function($file->uri);

  // Do the rest of your processing...
}


You should be able to get the account of the current page via

$account = menu_get_object('user');

and then check

if ($account->uid == $user->uid)

menu_get_object will grab the loaded object based on the url


How can I create block for my custom form?

The code in MymoduleBlock::build() is correct, and it is what Drupal core does in UserLoginBlock::build().

  $form = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');
  unset($form['name']['#attributes']['autofocus']);
  // When unsetting field descriptions, also unset aria-describedby attributes
  // to avoid introducing an accessibility bug.
  // @todo Do this automatically in https://www.drupal.org/node/2547063.
  unset($form['name']['#description']);
  unset($form['name']['#attributes']['aria-describedby']);
  unset($form['pass']['#description']);
  unset($form['pass']['#attributes']['aria-describedby']);
  $form['name']['#size'] = 15;
  $form['pass']['#size'] = 15;

What the block definition is missing is the annotation (the comment before the class) which allows Drupal to identify that class as plugin. See what Block API says. (Emphasis is mine.)

  Blocks are a combination of a configuration entity and a plugin. The configuration entity stores placement information (theme, region, weight) and any other configuration that is specific to the block. The block plugin does the work of rendering the block's content for display.

  Block plugins use the annotations defined by \Drupal\Core\Block\Annotation\Block. See the Annotations topic for more information about annotations.

In the block class I used as example, the annotation is the following one.

/*
 * @Block(
 *   id = "user_login_block",
 *   admin_label = @Translation("User login"),
 *   category = @Translation("Forms")
 * )
 */

Also, the machine name of module should not contain hyphens, which aren't allowed in PHP functions. That creates problems when you implement hooks, since the hook name is derived from the machine name of the module. For example, the implementation of hook_page_attachments() for your module would be my-module_page_attachments(), which is not an acceptable PHP function name.
If you think your module is not going to implement hooks, keep in mind that the majority of modules implements at least hook_update_N(), for which is also preferable not using capital letters in the module machine name.


How can I find webform e-mail submission values keys?

Here is the answer.

Lets say I've 4 fields in Webform

 Label    -   Field Key

First Name - first_name

Last Name - last_name

Phone Number - phone_number

Message - message

Here is the way to access them in template field

For example if you want to display name as the combination of First Name and Last Name

Name:  %value[first_name] %value[last_name]

Then this appears in mail like

Name: Krishna Mohan

If you want to access a individual field value with Label

For example Phone number

%email[phone_number]

This appears in mail like

Phone Number - 555-555-5225

I've tested this and works great! Hope this helps


MailSystemInterface::mail has a particular return value:

  TRUE if the mail was successfully accepted for delivery, otherwise FALSE.

The caller uses that to determine whether or not the mail was sent successfully, so just return TRUE when the mail succeeds and the error will stop.


First you should avoid captcha, their are not user friendly. But good new, in this case you don't need it :).

Print module generate the pdf once and cache it https://drupal.org/node/516466#comment-6390678. So DOS are not possible on pdf generation.

You can still have DOS by requesting a pdf thousand of time, saturating your bandwidth. If you are really worried about that you can for example configure Apache with mod_evasive http://systembash.com/content/how-to-stop-an-apache-ddos-attack-with-mod_evasive/

By robot I suppose you mean search engine robot. You can add that in your robot.txt (But I think is not necessary):

User Agent: *
Disallow: /*.pdf$


Adding translations to installation profile upon installation

You must include locale.inc before:

include_once DRUPAL_ROOT . '/includes/locale.inc';
locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', true, true);


How to hide the label of a entity referenced image field

Starting in Lightning 2.2.4, you can manage the label in the Media Entity's Manage Display tab.

See this issue for more information: https://www.drupal.org/node/2922289

  Include patch to omit media name

  Until this is fixed in core, it would be good to have the patch from [#2912298: Make media name available on manage display] included so that media name can be removed from display. This is especially crucial for lightning upgrades with existing media embeds.


Take messages generated by module and print them inside the node teaser?

My suggestion is:

Change this line in hook_node_view()
if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
and add $view_mode == 'teaser' to it. Then you can create a patch and submit to community, if you think that this feature may be needed by other users.
You can create a template file for this content type, store the messages in a theme variable and display them in template file, just use <?php print $VARIBALE_NAME ?> You also have to write a template preprocess function where you will write code to get message body.

I think second option is the best. The requirement is not generic and changing the module is not right in this case. However, you can search the module's issue queue for this.

References

function template_preprocess_node
Drupal 7 Template (Theme Hook) Suggestions


I'm running into this problem, though I'm not sure we're using Path Redirect. For me, Migrate is bringing in URLs that are non-canonical, and I need to override the query to get the URLs that D6 has decided are canonical.

In D6 the code that does this is drupal_lookup_path('alias', $path);

By examining this I determined that if you don't care about language, the bare query is (for node/121):

SELECT dst FROM url_alias WHERE src = 'node/121'  ORDER BY pid DESC;

The ORDER BY pid DESC is the key part here.


Two concatenated links throwing an error upon attempted logout

The issue is you have href="users/logout" not href="/users/logout", eg, it's a relative url, and thus building upon where you are in your site.


Merge two drupal views with different base types ('user' and 'node')

Why not simply use a content type only?

You can for example add an optional user reference field to a content type, which points to the user to whom the contact belongs. Then you can embed the content type into the user profile, if you want that. For example by using the Panels project.

For normal users, you could write a few lines of custom code to automatically populate the user reference to the current user and hide the field from them. You could also add a check that they can only create a single contact, if you want that.


access denied error on user registration module

You will get a 403 on user/register if you are already logged in.


Print custom field in user edit form in block

I've just run your code and it works fine. Maybe it is permission related problem.

<?php
function user_profile_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function user_profile_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

Output/result:
Here Birth Date is custom field, created form admin/config/people/accounts/fields.


Submit a custom form as a webform submission

Without really knowing much else about the custom requirements of your form it's difficult to give a complete answer however your on the right track by using Webform.

You should recreate as much of the form as you can using webform as a base rather than FAPI. Then you can use FAPI to alter (hook_form_alter) the existing form that webform outputs.

Your custom FAPI code can then be worked into the way webform works, you may have to massage some of the data based on your requirements though.


Enabling a module leads to memory exhaution. Where to look for?

A short answer for the question is to check the function names defined in the module.  If there is any conflict with the existing function names, that can give a trouble when enabling the module.  Also, it may be advisable to disable and enable the module, whenever you add a function to the module, maybe, to detect a potential trouble at the earliest opportunity.
--The following appended--
Another preventive ways: (1) Keep only hook_ functions in a *.module file, (2) for D7, name always your private functions with a little convention, for example, add the prefix of _: e.g., function _myfunction_theme().
--Appended up to here--

It turned out the function name My_Module_Name_theme() conflicts with hook_theme() in Drupal.  I was not using it as my intention, but the code of the function was left for the future development - that caused a trouble, as it was regarded as a valid hook by Drupal, whatever the programmer's intention was.  The arguments given to a call of another Drupal function in that function were not compatible with the Drupal function.  That may have lead to the memory exhaustion.

My guess is, since it is the name of the function (or maybe because it is a hook?), that caused a memory exhaustion while enabling the module rather than during run-time.  I added the function in the module when the module had been already enabled.  At that time (I mean, after I added the function), the module caused no trouble and kept functioning as I intended.  It is possibly because the function names were not registered to Drupal?  I don't know, but whichever, it would make (and indeed did make in my case) a programmer's job to track down the cause of the memory exhaustion difficult, as the error message might not help much to pin down which module, let alone which function, is causing a trouble.

Note even after I had added the "hook" function, I have once successfully disabled and enabled the module (after Drupal experienced a memory exhaustion), and the module worked fine for some time, before it eventually started to cause a memory exhaustion and then it became impossible to re-enable it.  I do not know why it was enabled successfully once and worked OK for some time.

The moral of this case is summarised at the beginning.  Added to that, to chop off all the unnecessary parts like debugging may help (as @rooby suggested in the comment of the question), because something in those unnecessary parts, or those that you think are unused, may be causing a trouble.  Frequent disabling/enabling cycles, as well as clearing the cache, can also help to identify the problem at the earliest opportunity.


Search API / Facets: How can I define a range / manipulate the search query in D8?

Afterwards here my solution: I've solved it with condition groups in the hook_search_api_query_alter() function:

function MYMODULE_search_api_query_alter($query) {
    //...

    $conditionGroup = $query->createConditionGroup('AND');
    $conditionGroup->addCondition('created', $firstDayOfYear, '>=');
    $conditionGroup->addCondition('created', $lastDayOfYear, '<=');
    $query->addConditionGroup($conditionGroup);

    //...
}


This happened to me with a couple of modules last week; the solution was simply to run cron, allowing the fields marked for deletion to actually be deleted. After that I could uninstall the module in question without issue.


Perhaps it is a NGINX config problem? Running Drupal in a subdirectory under Apache normally requires you to alter .htaccess and RewriteBase. I am not a NGINX admin but I would start by getting a copy of the running config. It might need stuff along

location ~ \.php$ {
        fastcgi_split_path_info ^(/abc)(/.*)$;
}

To avoid loosing in base directory.


From time to time, the system does not find a file that exists

The problem was traced back to a call to drupal_add_js with relative URLs. I have added a prefix of drupal_get_path and the problem has disappeared for ever; it seems sometimes Drupal did not find the file because it thought it was in another location, but later it found it. This is why clearing the cache reproduced the problem. With the absolute path, problem is vanished.


As your running the drupal from sub directory so modify the line containing "RewriteBase" (may be line no. 102) of .htaccess, change "# RewriteBase /drupal" to "RewriteBase /drupal_test".

And if the above thing doesn't works for you than please try the following:
Search for "<directory /var/www/>" in the "/etc/apache2/sites-available/default" file and change it as below:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>


Drupal 7: Find which user created a given user

Drupal, by default, does not keep any authoring information of users.

However, there is a module for that! Try Sub User module. It uses Relation module to maintain the relationship with parent user.


You might be able to create a rule based on this:

event: After content has been saved...
condition:  content is new
condition:  content is type (select type)
action: page redirect:  fill in page here with tokens based up content above

In the page direct you can create a query variable after the ?, eg foo=[TOKEN], and then in your page, you can access that variable via $_GET['foo'] or $_REQUEST['foo'].


How can I fix this error and upload files?

I figure out what the problem was. I'm posting the solution for my case just in case someone has the same problem.
My problem was that I had change the submit button ID in the input.html.twig file. I replaced it to the original and it works fine.


My if statements are working everywhere except in my hook_block_view function

$form_state['values']['searchInput'] is undefined in that function so this will never work. You could remove the if in this function and let search_engine_form return HTML if it is submitted. You can add it inside the if you're using for the message display.

You maybe have to use the #rebuild option on that form, so it gets rebuild.


By default, Shipping information fields should be shown

1) Go to Store Settings -> Checkout settings
2) Click the configure link for "Shipping information"
3) On the configure page,  uncheck the "Make copying information from this profile the default action, requiring users to uncheck a box on the checkout pane to enter a different address." checkbox.


Put your old theme back into the old location.
Enable and set Bartik theme as default theme.
Uninstall the old theme.
Move your old theme to the new location.
Enable the old theme and set as default again.
Uninstall Bartik.

Voilà


Linking to a homepage when Drupal is located in a Directory

You should use url() function to generate a page URL. For the frontpage it is:

<a href="<?php print url('<front>'); ?>">YOUR LINK

If the generated links using the url() function are not correct, you can change the $base_url variable in the settings.php

$base_url = 'http://www.yourwebsite.com/drupal7/drupal-7.23';


In general, the reason this block isn't working is that a block does not have an assigned path and the contextual filter does not have a path to work on.  To connect the block to a path return to the contextual filter settings and in the section What to do if the URL is not available select Provide default value and select Raw value from URL from the dropdown box. From the Path Component box select the position in the URL that your contextual filter gets its value.

In your specific case you have told the view to interpret the URL as a taxonomy term and that is probably not the format of your URL (taxonomy/term/tid). The Views UI is a bit misleading in that it suggests that the alias can be used in the contextual filter when it does not.  Drupal converts the alias to the base URL value when it calls the view and that is what is directly available in the contextual filter.  To use the alias you must specifically inform it as described above.  Views is powerful, but a bit tricky to use.  One tool you can use if you have some experience with SQL queries, is to turn on the display of the queries in the View preview display in the Settings tab.  This will tell you what views is trying to do when the view is called.

More can be found on this issue at this question


Views Data Export print feed icon in template file

Solution from: https://www.drupal.org/node/2117433#comment-9422881

Copy the views-view.tpl.php file from views into your theme (or its
templates directory if it has one). Note that you can rename the
file in certain ways to make it specific to an individual view or
display. The "Theme: Information" section of the views UI will give
you more information. Also see the blog post for more information on
that.
Clear the cache so the site starts using your new template file
instead of the default views one. The "Theme: Information" part of
the views UI should now indicate that your file is being used.
In your theme's version of the template file move the feed icon
section wherever you want it. Potentially you would put it under the
exposed filters or something. Currently the the feed icon part of
the template looks like this (move this whole section):

    <?php if ($feed_icon): ?>
      <div class="feed-icon">
        <?php print $feed_icon; ?>
      </div>
    <?php endif; ?>


In your Quick Tabs settings (admin/structure/quicktabs/manage/...) there's a checkbox to hide the title of your content and use the custom Tab-Title instead.

If you want to hide the block title (of the quicktabs block) itself, you can insert <none> in the block settings...


How does a Rule access a variable defined in the event info?

I was looking in the wrong place and thought about how Rules work the wrong way.  The event for when an Order entity is part of the Rule is triggered by the Commerce module on checkout.

rules_invoke_all('commerce_checkout_complete', $order);

And for the other entities, Rules already takes care of most by invoking events from its events.inc.


AJAX error: node form + list field with multiple options + image field

After additional testing, this seems to be a bug in Drupal core that affects only the select form elements.

Workaround is to change the field type to checkboxes. Everything else can stay the same. Values are then passed properly and everything works OK even with multiple file upload fields added to the same form.

Also the validation and submit handlers work as expected in this case.

I created a ticket for Drupal core here.


How to add a background image wallpaper to a drupal site from within the drupal admin?

For simple Drupal themes we use Artisteer. You can change most properties of a theme with just a mouse click. Please note that the tool is not free (and I'm just a happy user).


How come I cannot fetch the name of the taxonomy term from term id?

Currently your problem is that you're trying to call entity class methods on a stdClass object - directly querying the database means you're not using the API any more, the results you get aren't entities.

Unless there's a particular reason to do so, though, you shouldn't have to do it that way.

For example, the same query can be executed like this through the API:

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadByProperties(['vid' => 'term_category']);

foreach ($terms as $term) {
  $name = $term->getName();
}

It's quicker (loading in one go, not single loads in a loop), fewer lines of code, and when you bring caching into it, probably more performant.


overriding template file of display suite layout applies on other pages

You can use hook theme suggestion in your template file. It gives you the right way of naming you tpl file.

function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);

}

function THEME_preprocess_page(&$variables, $hook) {
  print_r($variables['theme_hook_suggestions']);

}


The third solution would be:

1- Install drush : https://www.drupal.org/node/1791676

2- Move to the local home directory of your drupal website inside the Command Prompt / Terminal (according to your OS type)

3- Type this command in the Command Prompt / Terminal (according to your OS type):

drush en panels -y


I would either implement a block or if you are using panels create a content pane.


Is there a better way to control user's login sessions? Yes.
There's a great module (beta since 2012, 1,000+ active sites used it as of October 1, 2014): https://www.drupal.org/project/persistent_login
From the module page:

The Persistent Login module provides the familiar "Remember Me" option in the user login
form. Additional security is provided by using two tokens (one long-running, one per
access) that allow the detection of unauthorized token use.
Persistent Login is independent of the PHP session settings and is more secure (and
user-friendly) than simply setting a long PHP session lifetime. For a detailed
discussion of the design and security of Persistent Login, see Improved Persistent Login
Cookie Best Practice.

What is causing the users to be disconnected? Depends.
As Mołot pointed out, there are literally dozens of things that could be happening. For example, we could be talking about multiple browsers, multiple devices, or someone who regularly clears out their cookies and internet history. Most of these situations are out of your control. The standard Drupal session cookie usually keeps me logged in over the course of a day or two without having to re-login. If someone is getting logged off in the same 24 hours span, something is happening.


This approach should work. I've tried it in the past and it did exactly what I needed.

Quoted from the above-linked comment:

Put views-view-row-rss.tpl.php in your theme directory

and replace print $item_elements;

with

$item_elements = preg_replace('<pubDate>.*</pubDate>', '', $item_elements);  // removes pubdate
$item_elements = preg_replace('<dc:creator>.*</dc:creator>', '', $item_elements);  // removes author
$item_elements = preg_replace('<category .*</category>', '', $item_elements);  // removes terms

$item_elements = preg_replace("!^\s+(\D)!m", "\\1", $item_elements);  // removes some blank lines

print $item_elements;


How do I update the section component configuration?

I have done it like this.
$node = \Drupal\node\Entity\Node::load($nid);
$layout = $node->get('layout_builder__layout')->getValue();
$sections = $layout->getSections();

foreach ($sections as $key => $section) {
  $components = $section->getComponents();
  foreach ($components as $component) {
    if ($component instanceof SectionComponent && $component->getPluginId() === 'myplugin_id') {
       $configurations = $component->get('configuration');
       $configurations['label_display'] = "0";
       $component->setConfiguration($configurations);
    }
  }
}

$node->set('layout_builder__layout', $layout);
$node->save();


My suspicion is that Drupal's .htaccess URL rewrite directives have been disallowed in your Ubuntu installation of Apache. If it were a bootstrap or database connection problem, you would not be able to see the front page either.

Ordinarily, Drupal prevents Clean URLs from being activated if not supported by the server. In this scenario, of course, that test was done in the Windows installation. Ensuring rewriting support in the target server is at the top of the migration checklist.

The quickest way to see if Clean URLs is the culprit is to try browsing to localhost/sitename/index.php?q=user/login ; if that page does come up, you will need to enable rewriting in your web server.

See http://drupal.org/node/1186762#comment-5424052 for some instructions on checking your Apache configuration to make sure it allows Drupal to rewrite URLs in its .htaccess file.

If you can confirm that the .htaccess file is being read, rewrite directives have been allowed in Drupal's installation directory, and that mod_rewrite is active, and still see problems, I would check next for a corrupted menu table.


How to fire multiple Rules Actions in a single rule?

I see "data set" which I'm 99% sure means your field is either set to one value.. Or in taxonomy, it could mean  that setting data overwrites previous values. So your rules might simply overwriting each other.

I can't remember much about taxonomy but change your field to infinite values if not already and use the rules action, " Add an item to list" if possible.

On a separate note, you should avail of the action "fetch entity by property" and only have maybe one rule for everything. So you'd add an integer field to your taxonomy terms and use the rules action to fetch it using the integer provided. Let me know if you want to try it.


Zen is all right but after using it a while I ran into problems since it's not built on the grid system. I found Omega pretty amazing as a grid-based starter theme for Drupal 7 with a responsive option. The steep learning curve was worth it, and it provides great tools and help.


Display block if content type has entity reference (tags) that contains specific term

The easiest solution is probably term_condition

Install/enable the module and then on the block layout of a certain block you will be presented with a term visibility setting where you can search for term that will be used as the visibility condition.

NOTE: Currently the module is incompatible with rules as rules has its numerous conditions on its own.  This issue has been reported here


Display custom form mode in twig with drupal_entity_form

You need to create a custom module
Let say you call it module_name
In your module_name.module file you'll have to use the hook_entity_type_build()
/**
 * Implements hook_entity_type_build().
 */
function module_name_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('applicant', 'Drupal\node\NodeForm');
}

Then enable your module_name module and flush the cache.


Using custom CSS3/HTML on generated pages?

You can override the views template and create your own template/markup to achieve what you want.  You can read more on how to achieve that here: http://drupal.org/node/1089656


Restrict User Roles in viewing a Node Content Type without installing a module

You can control node access using hook_node_access

e.g:

/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  if ($type == 'type_of_interest') {
    // Require administer nodes permission to view
    if (($op == 'view') && (!user_access('administer nodes', $account))) {
      return NODE_ACCESS_DENY;
    }
  }

}


How can I provide a filter with context/nid of node invoking?

Filters are not context-aware and AFAIK, there is no way at the moment to do what you want. This has been a feature request since 2008, but the proposed patch didn't make it into Drupal 7.

If this is very important to the site you're building, you can consider patching Drupal core. However, once Drupal core is patched, you will need to take extra care (and time) when updating your site.


getting rid of Media Module Message "Media Folder: Media Root"

A similar problem came up for me when upgrading a Drupal site to Drupal 7.53. I found that the "media folder" field suddenly started appearing on all images on the site.

What fixed it for me was hiding the media folder field from the file type generated by the file entity module (which makes files fieldable). Here are the steps to do that on your Drupal site:

Go to Home » Administration » Structure (admin/structure/file-types).
Click "Manage display" for the affected file type.
Change the label and format to "hidden" for the "Media folder" field and click save.
While you are at it, repeat steps 1 and 2 for all the file types on your site.
Clear your caches.


Suggestions for storing private user content lists

You could use ECK and link it to the user using Entity Reference. You'll need to some small custom coding to auto fill the entity reference field with the logged in user's id. Better yet, you can use Rules for a no code solution to autofill the entity reference with the logged in user ID.

Here is a video on ECK and for entity reference.


Modal with content depending on opening hours

if you run your site under an url like example.com/dat/fresh/site/, remove the first slash in the href, like:

Test link

or change to full path, like:

Test link


Show 3 different Views displays for same exposed filter block or link Views displays?

You can use only one exposed form of one of the displays. The other exposed forms should be set "as block", so they are not shown (as you will not set them active in the block configuration). As exposed forms work via GET-params, you simply can use the same "Filter identifier" for filters that shall share the same value.

An exposed filter in display2 with identifier type will use the same value as the exposed filter in display1 with the same identifier type.

This way you can control all three displays by only using one exposed form.


Add a prefix to a views field pre_render

I would do it by creating a template file, like views-view-field--fieldname.tpl.php, for the field and add the currency prefix to it.


Rendering nodes of a same content type in different templates

It seems you are looking for Template Picker module:

  Template picker gives content creators a list of templates to choose from as they create nodes.