Judging from your question you seem very confused about line items and what they are used for.

Line items are used to link products to an order. The whole idea is that some data you want to fetch from the product directly, like it's title, media etc, while some data you need to copy, like the price and sometimes you need to add data, like the address for a subscription and quantity.

The reason you need to copy the price, is that if you ever change the price of the product you want to preserve the old orders which is why you need to store the price for each purchase.

There is nothing technical that will hinder you to create a relationship from products to line items or from line items to line items, but it won't make much sense to do so, and will most likely result in some strange bugs, as line items are used for orders to store info about products, and commerce expects this.


How to have a content type that displays a title, a description and a list of feeds imported from an external URL such as blogspot?

Drupal creates 25 node of "blogger" type, that are my feed items, but I don't want this.

There is a difference between attaching an importer to a content type and selecting a content type on the node processor. The first one is meant as a sort of "container" - you'll need to create nodes of this type in order to import content. The content type select on the node processor is the type of nodes that Feeds will create when you import content. Make sure that these two settings are always different.

So you need to make sure that you have two content types:

One content type - called "blogger" for example - is the content type that you attach the importer to. This setting can be found under "Basic settings". This means you need to create a node of this type in order to import content.
The second content type - called "blog item" for example - is the type of content that you want Feeds to create. Select this content type on the node processor.

When you now create a "blogger" node and provide a source - in your case an URL since you selected the HTTP fetcher for your importer - Feeds will create nodes of type "blog item".

In order to show the blog items on your blogger node, you'll need to create a View and find a way to display that View on your blogger node. One way of doing that would be using a block that is only shown on your blogger content type.

If you want to have a head start with this, I recommend to install the Feeds News module (this module is included with Feeds). This demonstrates how to use the attach to content type feature. It also includes a View for displaying the imported items (though on a separate page).


How to set the default for checkboxes element

Simplistically, the issue is that the default value uses the array key, not the array value.  So, there are two ways you can change this to make it work.

One:

$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a' => 'a','b' => 'b', 'c' => 'c'),
  '#default_value' => array('a'),
  '#title' => t('The average vote is more than'),
);

or

$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a','b','c'),
  '#default_value' => array(0),
  '#title' => t('The average vote is more than'),
);


I would recommend using the field collection module instead. Create a field collection with a file upload field, description field and file owner field (can be a text field or user reference field. Set the field collection to unlimited. Then add the field collection to your page content type. It will allow you to do more custom things moving forward.

https://www.drupal.org/project/field_collection
https://www.drupal.org/project/references


Is it okay to use drupal_goto() from within a node?

It is a bad idea and I wouldn't recommend doing it.  The cron error you see is most likely due to the Search module. During cron while the Search module is trying to index content, if it reaches a node containing a drupal_goto() it will hang and cron will error which could lead to more problems


Best way to migrate text field to taxonomy reference field

I would:

Go thorough all values, grouping them by their Levenshtein distance from each other.
For all set of similar names, I would choose canonical one, and put them in taxonomy as a term.
Using Computed Field or VBO I would choose the Levenshtein closest term for each node.

Details of implementation would need a bit of polishing, but that's my general approach. Apparently you can use Views Bulk Operations both to create taxonomy terms and to set field's value on node.


"one more" ajax call for multiple node add forms on one page

I worked on similar case. I wanted to add few nodes at one time without reloading page.

Instead I did multi value field in my content type (mysomething), but I needed to have more elements than one field. So I found field collection module, made collection and put it as multi value field of type collection. Now when I do node/add/mysomething I have collection and [Add more] button below.

Creating collection allows You to add all core field types, so in your case I would add text field working as title and body field to collection.

The other thing is, that if someone add 3 collection at once it will be consider as one mysomething node by D7 core - You should make some views to see whats inside. Another approach is to catch node creation action of type mysomething and try to split it into nodes by rules, but I didn't do that so I'm not sure if it is possible. And finally someone probably can write custom module with ajax form, where submit button will save node for each element...

I think it's nice trick with no coding (UI visual puzzle). I can write step by step config for You, if needed, but it's pretty easy.


You have a slight error in your page callback property for the menu item. You've got a string resembling a path in there instead of the name of the callback function.

Just change

'page callback' => '_dsregion/autocomplete'

to

'page callback' => '_dsregion_autocomplete'

Then clear Drupal's caches and you should be good to go.


Periodically set the userpoints for every user

you could extend the userpoints module to have some actions exposed to VBO then execute that periodically with Rules. Depends how much time you have, but it would be a nice addition to that module..


How can I know that node is created or updated?

Modules that need to execute code during cron tasks, and for nodes that have been created/updated/delete already implement code to do that. If you need something similar for your own module, you could use the following code.

function mymodule_node_insert($node) {
  $queue = DrupalQueue::get('mymodule_cron_queue');
  $queue->createQueue();
  $queue->createItem($node);
}

function mymodule_cron_queue_info() {
  $queues['mymodule_cron_queue'] = array(
    'worker callback' => 'mymodule_cron_worker',
    'time' => 10,
  );

  return $queues;
}

function mymodule_cron_worker($node) {
  // Code that uses $node.
}

With this code, mymodule_cron_worker() is called during cron tasks for every node that has been created; if you need to execute code during cron tasks for updated nodes, or deleted nodes, then you need to implement hook_node_update(), or hook_node_delete(). The code I shown for hook_node_insert() is the same code you would use for the other node hooks.

References

Queue operations
Example: Cron


moving of a database [drupal-commons 6x25]: Which tables can be emptied safely?

I used to empty all "cache" prefixed tables, "watchdog" table and session table.


How to prevent users from being registered when their username contains a space?

@Jeroen,
Then I would suggest to do just one custom form alter to the user registration form and add a validation function that will validate each case for you.

/**
 * Implements hook_form_FORM_ID_alter().
 */
// Alter the registration form
function CUSTOM_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Add your own function to the array of validation callbacks
  $form['#validate'][] = 'CUSTOM_MODULE_user_validation';
}

/**
 * Custom function to validate the user creations.
 */
function CUSTOM_MODULE_user_validation(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  if (preg_match('/\s/',$name)) {
     form_set_error('name', t('Name should not contain white spaces.'));
  }
}

Its easier to use and doesn't invoke rules API every time. I also think this is much effective for performance.


Zoom and center a GMap according to its markers is not working?

Instead of a delay, wait for a map loaded event. I could not find a direct one so used a mutation event.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
  var target_id = mutations[0].target.id;
  var map = Drupal.gmap.getMap(target_id).map;
  if (typeof map != 'undefined') {
    var initialLocation = new google.maps.LatLng(old_lat, old_lon);
    map.setCenter(initialLocation);
    // map.vars.zoom
    map.setZoom(12);
  }
});

jQuery(".gmap").each(function() {
  var gmapID = jQuery(this).attr("id");

  observer.observe($("#" + gmapID)[0], {
    subtree: false,
    attributes: true
  });
});

Subtree = false should mean that once the map is loaded this doesn't get triggered again. Add another test if needed.


This appears to be about primarily about the CSS, and the right answer depends on how the html is structured.

Have you tried any resources like Learn CSS Positioning in Ten Steps?

If there are already some containers, you can float both the containers left and give them specific widths (probably).  Or you could use absolute positioning.  Do you have to account for the picture potentially NOT being there?

My best suggestion is to use Firebug or Inspector or similar to try out a couple things based on your DOM


Uploaded images in theme settings is going to be lost

My solution is to ensure to make permanent the image when drupal load page theme settings. You don't need to create a custom submit handler because after the new settings are saved the settings page is reloaded, and the fix executed.

Plus, you cannot use "active theme" because sometimes the current active theme is the admin theme, and not the default or maybe the user is changing the settings theme in a theme that it's not set as default.

function YOUR_THEME_form_system_theme_settings_alter(&$form, &$form_state)  {

  $default_file_dir = 'public://template/logos';
  $folder = file_prepare_directory($default_file_dir, FILE_CREATE_DIRECTORY);
  $settings_theme = $form_state['build_info']['args'][0];

  if ($folder) {
    $my_logo = theme_get_setting('my_logo');
    // BUG: Force file to be permanent.
    if (!empty($my_logo)) {
      _fix_permanent_image('my_logo', $settings_theme);
    }
    $form['my_logo'] = array(
      '#type'               => 'managed_file',
      '#title'              => l('My logo'),
      '#default_value'      => $my_logo,
      '#progress_message'   => t('Please wait...'),
      '#progress_indicator' => 'bar',
      '#upload_location'    => $default_file_dir,
      '#upload_validators'  => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_image_resolution' => array('375x50', '30x50'),
      ),
    );
  }

}

function _fix_permanent_image($image, $theme) {
  $fid = theme_get_setting($image, $theme);
  if ($fid > 0) {
    $file = file_load($fid);
    if (is_object($file) && $file->status == 0) {
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      file_usage_add($file, $theme, 'theme', 1);
      drupal_set_message($image . ' saved permanently.', 'status');
    }
  }
}


Or add a php script step to your form and simply use the Field API to extract the highest value of the delta as a variable to be used later in Rules execution.


How to add a width attribute to a responsive image with srcset?

This is not going to be easy due to Drupal's way of rendering images, you should not touch this unless you know how to write code. The code below is untested, but should give you a direction.

function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  //this is the hook where you do get access to the image file entity
  //don't use 'width' as attribute name, it might get unset by Drupal in the following hook
  $variables['responsive_image']['#attributes']['data-original-image-width'] = $variables['item']->width;
}

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //this is the preparing the rendering, here you can set the width attribute again
  $variables['#attributes']['width'] = $variables['img_element']['#attributes']['data-original-image-width'];
}

This is code just an outline, and most likely will only work if responsive images module is configured for an single img[srcset] and will not work with <picture> tags.

The hooks are quite good documented though, check the API docs for more information

hook_preprocess_responsive_image_formatter

hook_preprocess_responsive_image


Adding comments to a node via drush or commandline

Expanding on Shawn Conn's answer, below is a Drush command that adds a comment to a Drupal 7 node.

Usage:

drush add-comment --uid=1 --subject='A comment' 'This is my awesome comment.'

Save the script below as add_comment.drush.inc, and place it in your $HOME/.drush directory.

<?php

/**
 * Implements hook_drush_command().
 */
function add_comment_drush_command() {
  $items = array();

  $items['add-comment'] = array(
    'description' => "Add a comment to a node.",
    // Describe the arguments for this command.  Delete
    // this seciton if command takes no arguments.
    'arguments' => array(
      'comment' => 'The comment to add.',
    ),
    // List all options used for this command. Only options that
    // are listed here (or that are global Drush options) may
    // be specified on the commnadline; all others raise an error.
    'options' => array(
      'nid' => array(
        'description' => 'The node id to add the comment to.',
        'example-value' => '3',
      ),
      'subject' => 'The comment subject. Defaults to empty.',
      'uid' => 'The user id of the user to post the comment as. Defaults to anonymous.',
    ),
    // Give one or more example commandline usages for this command
    'examples' => array(
      'drush add-comment --nid=123 "This is my great comment."' => 'Do something.',
    ),
    'aliases' => array('addc'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 *
 * @param
 *   A string with the help section (prepend with 'drush:')
 *
 * @return
 *   A string with the help text for your command.
 */
function add_comment_drush_help($section) {
  switch ($section) {
    case 'drush:add-comment':
      return dt("Brief help for Drush command add-comment.");
    // The 'title' meta item is used to name a group of
    // commands in `drush help`.  If a title is not defined,
    // the default is "All commands in ___", with the
    // specific name of the commandfile (e.g. add-comment).
    // Command files with less than four commands will
    // be placed in the "Other commands" section, _unless_
    // they define a title.  It is therefore preferable
    // to not define a title unless the file defines a lot
    // of commands.
    case 'meta:add-comment:title':
      return dt("add-comment commands");
    // The 'summary' meta item is displayed in `drush help --filter`,
    // and is used to give a general idea what the commands in this
    // command file do, and what they have in common.
    case 'meta:add-comment:summary':
      return dt("Summary of all commands in this command group.");
  }
}

/**
 * Implementation of drush_hook_COMMAND().
 *
 * Add a comment to a node.
 */
function drush_add_comment($comment) {
  $nid = drush_get_option('nid');
  $uid = drush_get_option('uid', 0);
  $subject = drush_get_option('subject', '');

  $comment = (object) array(
    'nid' => $nid,
    'cid' => 0,
    'pid' => 0,
    'uid' => $uid,
    'mail' => '',
    'is_anonymous' => ($uid == 0),
    'homepage' => '',
    'status' => COMMENT_PUBLISHED,
    'subject' => $subject,
    'language' => LANGUAGE_NONE,
    'comment_body' => array(
      LANGUAGE_NONE => array(
        0 => array (
          'value' => $comment,
          'format' => 'filtered_html'
        )
      )
    ),
  );

  comment_submit($comment);
  comment_save($comment);
}


Getting content type data from twig view template

Blocks don't have the same variables as other entity types do. They will vary in their theme hook implementations. That is why there is no {{ node.field }} concept for blocks, the information does not exist. The same principle applies to Views, Media, Paragraphs and other entities. For example, to reference fields on the paragraph in its template, you wouldn't call {{ node.field_foo }} you would call {{ paragraph.field_foo }}.

Just because a view block is rendering on a node detail page doesn't mean that the same twig template automatically sees a node object.

If the View is building this block display, I would say add the field to the View that you want to output (Author).

If you want to blow your own mind, if the view you have is returning fields on a node, change the display to use the rendered content mode, and choose a display mode (start with Teaser). This approach will allow you to use node--node-type twig templates, as Views is rendering the entity instead of printing fields into the View. The View output is then driven by the display mode on the node type itself and is a much more manageable result in most cases.


How to allow for manual HTML & CSS changes?

go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or full html) You need to go to
/admin/config/content/formats/filtered_html
OR
/admin/config/content/formats/full_html
Uncheck the correct faulty and chopped off html box.


How to add a "continue shopping" button after emptying cart in Ubercart?

For this, you can override uc_empty_cart() function with theme_uc_empty_cart(); which returns your custom message on empty cart page.

You can get continuous shopping cart URL from Store > cart setting using variable_get('uc_continue_shopping_url', '').

Example:

  // Default function from uc_cart.module
  function theme_uc_empty_cart() {
    return '
'. t('There are no products in your shopping cart.') . '
continuous shopping';
  }


Content Types with field "clusters". Possible or is there a different solution?

Probably the easiest solution is to have a single content type, add all fields that you need in any possible situation, and use Conditional Fields to hide/show fields based on the chosen equipment type taxonomy term.


How can I install Drush without Composer?

This is the simplest solution I have found.

If you don't want to use composer, follow the instructions here...

https://sharpi.sh/blog/web-development/install-drush-on-ubuntu-quickly-without-composer/

Download a Drush release from Github to user folder

wget https://github.com/drush-ops/drush/releases/download/8.1.17/drush.phar

Rename drush.phar to drush

mv drush.phar drush

Find the bin directory

echo $PATH

which shows something like.... /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

I’ll go with /usr/local/bin

Move drush to the bin

mv drush /usr/local/bin/drush

Change permissions to

chmod +x /usr/local/bin/drush

Test with

drush version


How do I add a view mode to a simple custom entity?

You need a view builder class in the handler section:

 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",

and a field UI route:

 *   field_ui_base_route = "my_entity.settings",

pointing at the config form for the settings of your entity type. If you don't have settings return at least a #markup element:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['my_entity_settings']['#markup'] = 'Settings form for My Entity entities. Manage field settings here.';
    return $form;
  }


I disabled the Bakery module and am now able to clear the flood tables using the command without getting the deadlock.


How to show a block only if a specific user is logged in?

If only a block needs to be shown for each user, then what I would do is to implement the block in a module that changes the content of the block basing on the currently logged-in user. The visibility settings are also used for blocks implemented by third-party modules.


How to archive old orders in Drupal Commerce

Couldn't you just backup your database using phpmyadmin, doing a .mysql export of the whole database which would keep record of all orders in the commerce_order and commerce_customer_profile tables?

Then using phpmyadmin, just remove all rows from the commerce_order table, to wipe the slate clean.

In the future, if you wanted to add all orders back into the site, you could import the data from your backup.


Results table with form select for filtering

I don't see a render function anywhere after you create the form. If you didn't exclude it on purpose, after creating the form, it has to be rendered and printed.

in your function you call drupal_get_form()

  Return value

  The form array.

and later on you add to that with theme()

  Return value

  An HTML string representing the themed output.

it looks like you're trying to put together an array and string in the same variable. You need to either render the form first into a string and then add them together, or include the theme data into the form array and render it later on.


Hide Uploaded Files in File Field in Node Edit Form

Create a custom module and implements hooK_form_alter(). and set field access to false for other user except administrator.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id === 'CONTENTTYPE_node_form' && !in_array('administrator', $user->roles) && $form['field_image']['und'][0]['#default_value']['fid'] > 0) {
    $form['field_image']['#access'] = FALSE;
  }
}

MODULENAME = Your costom module machine name.
CONTENTTYPE = Your content type machine name.
field_image = Your custom file field machine name.


Adding a dependencies in theme info file

Nope, themes do not have such a directive in their info files.

Themes are supposed to be module independent. The "designed" way to do it is to move all module-dependent code to a custom module, and in relevant parts of your theme simply test for existence of data your custom module was supposed to provide.


How to render a node with different DS View modes depending on taxonomy term?

You can switch view modes using hook_entity_view_mode_alter. In pseudo code, something like:

function your_module_entity_view_mode_alter(&$view_mode, $context) {

    //check that this is a node of typex, and check current view mode
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'typex' && $view_mode == 'full') {

      //check current taxonomy terms
      [code]

      //code to set view mode
      if (condition based on taxonomy terms) {
        $view_mode = 'new_view_mode';
      }
    }
}


Drupal 8, get value of field user in proper way, not an array

The method getValue() is used to get an array:

$array = $user->get('field_value')->getValue();

If you want to get a skalar use:

$value = $user->get('field_value')->value;

Both methods look similar, but do different things:

The method getValue() is to get the complete array of a field, which is quite useful for multiple value fields or multiple properties.

The method ->value gets the property with the same name.  Most standard fields use value as the main property.


Both give me the vendor files. I have uploaded those files to the remote server's vendor directory, yet they are still not being loaded.

What files did you upload exactly? It's not enough to upload just the new files from your package, installing packages with composer also updates its own autoloading files to make sure it knows where to load that and you probably forgot to upload those, that's the only explanation I have at least.

Try uploading all the files in vendor/composer as well or to be sure, all the files in vendor.


How to build a dynamic user-page from LDAP (Active Directory) and show this page after logged in?

After login the user should come to it's own personal page.

Whatever page you want to send the user too (different from the default user profile page) can be achieved by using the Login Destination module:

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

Then you said:

  In which he can see his personal data and so on. But how to create a
  dynamic page like a template for this personal page??

You didn't mention if this page should be the user's profile or a different page simply showing all the account details from LDAP (and possibly other pieces of content). You can embed the user profile on any path you want, see similar question(s) and example solutions at:

How to show custom user profile fields in a view?

Or, you can create a View that uses an LDAP Query and simply show information from LDAP on a custom view page, which the ldap module supports. See the LDAP Query documentation.


How to restrict access to specific content types by role?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

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

Notes (to further address your comment below this answer):

  ... I want to give access to anonymous users, I guess they can't be part of a group?

True, an anonymous user, by design, cannot be part of a group. But as mentioned in my answer to "What are the various roles supported by the Group module?": the role "Anonymous" (related to a user that is not signed) is one of the Special Global Roles (apart from Outsider and Member). And it is via that Special Global Role "Anonymous" that you can make the magic happen for any anonymous user. Have a look at the video tutorial, around 10:53, where you can see that it is possible to grant access to anonymous users* to (eg) "View content" to a Group node (of content type "Article").

  ... I would then need to add every person to those groups instead of just assigning permissions to their roles?

If you'd grant appropriate permissions for Outsider (combined with the access you want for Anonymous), they do not have to be part of those groups.

  ... It seem like a little bit bad work-around for my need.

With the above details included in this note, I presume you agree that this part of your comment no longer applies.

Bonus tip:

A possible solution to "... make all 'article' nodes be content of an 'articles' group." (as in another comment added to this answer) is explained in comment nr 3 of the issue titled Bulk assign of content to groups. This is part of what it says:

  The steps to take are roughly:

  Make sure you have a GroupType
  Make sure the GroupType has the right plugins enabled (GroupType::installContentPlugin(); read deprecation notice)
  Create a Group of said GroupType
  Start adding the nodes using $group->addContent($node, 'group_node:NODE_TYPE_HERE');

For D7 one can use Views Bulk Operations (VBO) and Rules as detailed in my answer to "How to bulk assign existing content to a group created with the Group module?").


Constructor in a custom entity isn't prior to baseFieldDefinitions

Entity::create gets the storage for the entity type and calls  EntityStorage::create. What you are looking for is probably the method
Entity::preCreate, which is the first entity event invoked by EntityStorage::create.

Place it as public static function in the custom entity class to change the values before the entity is created:

class CustomEntity extends ContentEntityBase {

   /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
    // modify $values
  }

}


I search a lot too after 8.2x and this is how i got it working :

Example for a custom user ressource :

  myModule/config/install

  rest.resource.user.rest_ressource.yml

langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

  In myModule/src/Plugin/rest/resource

  UserRestRessource.php

<?php

namespace Drupal\myModule\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "user_rest_ressource",
 *   label = @Translation("User Rest"),
 *   uri_paths = {
 *     "canonical" = "/api/user/getInfo"
 *   }
 * )
 */
class UserRestRessource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('restimadiff'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   *
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {

      $responseResource=new ResourceResponse(
          array()

      );
    return $responseResource;
  }

}


How can a user join a group in Drupal Commons?

In your Drupal admin area, go to "Administration → Structure → Content types → Group → Manage Display → Default" (/admin/structure/types/manage/group/display).
Set column "Format" for field "Group" to "OG subscribe link".

Your groups will now display a "Subscribe to Group" link on the groups' pages. This only applies for users who have the privilege to request membership to a specific group (which can be set in both the global OG permissions, and can be overwritten per group).


Unable to add custom validation rules using client side validation module in Drupal 7

Finally found the solution. Actually the code that I was writing was not complete. The examples for adding custom rules in client side validation can found at https://drupal.org/node/1324772 . Hope this helps some one.

Cheers!!!


Consult this, you will see there is a variable node that is fully loaded node object. so try the following. one of them should work

{{ node.field_name.value }}
{{ node.field_name }}
{{ content.field_name }}


How to add an autocomplete field to a form

Well, that was pretty ugly, and a LOT of guesswork is going on here.  But:

When Drupal sets up an autocomplete field, it adds a hidden variable to the form, which (I'm guessing here) is used to track the status of the whole autocomplete thing.  If you inspect a rendered form, it will look something like:

<input type="hidden" id="edit-field-name-autocomplete"
      value="https://example.com/path/to/autocomplete/handler" disabled="disabled"
      class="autocomplete autocomplete-processed">

That autocomplete-processed field seems to be the key: I had blindly copied it into my code and made it part of the field I was added to the form.  Once I removed it -- autocomplete-processed, that is -- autocompletion ran properly on it and all other similar fields.

Whew.  Your mileage may DEFINITELY vary.


Views to show all child terms without showing parent

You can add a relationship with your parent term. After that you can set a filter with your parent term and filter all terms, which have a parent term id (parent taxonomy term: term id(not null)).


Overriding admin settings form from bootstrap sub theme

You need to create theme-settings.php in your theme directory & add following function in that to add new fields as shown in code below:

<?php
function <THEME_NAME>_form_system_theme_settings_alter(&$form, &$form_state) {
    $form['campaign_pages'] = array(
        '#title' => t('Campaign Pages'),
        '#type' => 'textarea',
        '#description' => t('Specify pages by using their paths. Enter one path per line.'),
        '#default_value' => theme_get_setting('campaign_pages'),
    );

}

Here theme_get_setting stores the value of your field.


Clearing cache, won't flush image styles: http://drupal.org/node/997332

You could:

delete them manually
use image_style_flush
use the command line: rm -rf sites/default/files/styles
use drush: drush image-flush


How do I create a 'page' that creates and downloads a file from within a module

Don't forget anything you can do with PHP you can do with Drupal, so headers work in exactly the same way.

Adding a page callback which sets headers and exits the script (with drupal_exit()) is definitely the right way to do this:

function MYMODULE_MENU() {
  $items['mypage'] = array(
    'title' => 'CSV',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_deliver_csv'
  );

  return $items;
}

function MYMODULE_deliver_csv() {
  // Full complement of headers so IE behaves
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"filename.csv\";" );
  header("Content-Transfer-Encoding: binary");

  // Print your CSV data here

  // Exit the script
  drupal_exit();
}


View result alter title link based on content type

You can do it via views itself with the little tweaking.

Since you said the custom URL will not be available in other content types,

Add the required fields including custom field and the content path to your views fields.

Open the custom URL field and go to No Results Behaviour. Add the Replacement pattern of default content path.

Created a custom text and assembled results. Make sure u refer to custom URL field to link and not the default content URL.

It should automatically work now. Whenever there is no third party URL link not available, it will fetch the default URL. This should have your issue resolved.

But in case if the third-party URL field was available in all content type with some data, Then you need to do this in preprocess function. This approach will have issues.


Add a text field to OG subscription form

I noticed it is possible to add this field (and others if needed) through the OG settings of the membership (cf. admin/config/group/group-membership/manage/NAME_OF_YOUR_OG_MEMBERSHIP/fields).


Trying to embed a video in a Views Header

The 'Full HTML' format in Drupal 7 by default still strips out some of your tags, check your format settings under Administer » Configuration » Content authoring » Text format, or /admin/config/content/formats/ and you'll see that for the Full HTML format, you're limited to the following tags:

<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>

You can either add an object, embed tag here to make these work for this input format or you can add a separate input format that has no restrictions. The choice will really depend on what kind of site you are running and who else might have access to this format. If I were letting users use the 'Full HTML' format for adding comments, content, I would definitely want to restrict the tags they use and allow only admins access to an unfiltered format.


how do I theme rounded corners in Panels 7.x-3.3

The functionality you refer to predates common browser support for rounded corners, when images was the only reasonable solution.

Today, I would most likely no use it, but instead implement it with the modern CSS approach.

If you really want to modify the existing functionality though, it's called a Style. You can see this question for details about implementing ctools plugins: What are Ctools plugin (content type, access, etc), and how does one create them?


I opened a drupal.org bug report on 20 december 2016 for this exact same request. The patch passes all tests and is now in the "Needs review" stage. Feel free to test the patch and mark the issue as RTBC.


Send e-mail when webform submission changes

If you look here : http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/group/webform_hooks/7 , you'll see that Webform provides some hooks on which you can act.

There's a hook called 'hook_webform_submission_update', which triggers on the update of a submission. Using that one, you can check if the boss approved/denied it, and send out an email.

The plain 'send email on submission' can be configured through Webform itself, so you won't need to use a Webform hook for that. Although you could if you want to.


How can I check if the cart has shippable products?

The function is now a part of the CartInterface and implemented in the Cart::isShippable() method. You can use the CartManager service to retrieve the Cart object and call the method:

\Drupal::service('uc_cart.manager')->get()->isShippable()


7 - How to create a view using ApacheSolr?

I add a full response.

If you want a full integration with Solr and Views you should use Search api with Search Api Solr (there several modules that work with Search Api, see the Search Api page).

You will be able to:

create search pages (like normal search pages), with Search Api Pages
create every type of view based on the Solr Index, using filters, relations, contextual filters
add facet, with http://drupal.org/project/facetapi, to search pages and views

There are many usefule modules that work with Search Api: autocompletation, indexing files, create index on file taxonomies and users, spellcheck, sorts, ranges, saved searches etc.

Every day I use Search Api at work, for views and for default search, I think is the best solution.


Display current node rank from votes (voting api) in view

Check the comments on this question: Problem visualizing the rating value inside a view

It sounds like you probably haven't set an aggregate function on the Node: Vote Results relationship. You cab definitely display the total votes in a View without writing any of your own code.


The CSS changes are applied through a subtheme, but if you don't have access to that or only need to make small adjustment you can use the CSS Editor module to add your CSS.

The HTML you supplied doesn't seem to have a unique attribute you can use to target it reliably. Is there are wrapper div with an ID attribute around that code?

With classes you will likely style more than one component, this selector targets elements with both these classes:

.field--name-body.field--type-text-with-summary {
 float: right;
}

BTW you need to test your code in different browsers and browser window sizes to make sure you're not breaking the layout in some cases.


Condition plugins: two on the same form?

You are responsible for only passing a sub-key of the form to each plugin configuration method.

Have a look at BlockBase::buildConfigurationForm() and the corresponding validate and submit methods. Note that this itself is already a partial form of BlockForm::form().

For a more flexible approach, have a look at https://drupal.org/project/page_manager, which has an UI that allows to add conditions and configure them in separate forms, but those forms also pass only a part of the form to those methods.

The main advantage of the page_manager approach is that BlockBase only works in a useful way with condition plugins that have a no-op mode, meaning, that you can configure them so they don't do anything (and that is the default configuration) because all condition configurations are saved and all plugins are invoked.

Yes, this is sometimes limiting and inconsistent, but that's how it works and I don't really have an idea to improve it...


Something like this should work:

/**
 * Implements template_preprocess_search_results.
 */
function YOUR_THEME_preprocess_search_results(&$variables){
  $results = $variables['results'];
  if(count($results) == 0){
    drupal_goto('<front>');
  }
}


Drush error — missing module Console_Table

Drush 5 is no longer supported.  Install Drush 8 using the standard installation instructions.


When you use render element, the element which you apply the theme to is passed into the theme function in the $vars array...the index in the array will be whatever you've set render element to in your theme function, which in this case is element; hence the element you've asked the theme API to pass in is available in $vars['element'], which is a carbon copy of the original render element.

To get the effect you're looking for you would normally use variables instead of render element:

function opengraph_theme() {
  return array(
    'opengraph_company' => array(
      'variables' => array(
        'id' => 0,
        'name' => '',
        'picture' => '',
        'link' => ''
      ),
    ),
  );
}

Then you'd build your render element like this:

$block['content'] = array(
  '#theme' => 'opengraph_company',
  '#id' => 123,
  '#name' => 'Name',
  '#picture' => 'Picture',
  '#link' => 'Link'
);

Or, if you want to use your current $data array, you can pass it directly to the theme function:

$block['content'] = array(
  '#markup' => theme('opengraph_company', $data)
);

Bear in mind with that second method any modules whose hooks might be run after yours will no longer get the chance to alter the theme output, as you're converting it down to a string.

Using either of those methods though, when your theme function is run you will have access to the variables like this:

function theme_opengraph_company(&$vars) {
  $id = $vars['id'];
  $name = $vars['name'];
  // etc...
}


How do I add a custom textarea into the checkout screen?

You will need to write a custom checkout pane plugin, I'm afraid.

Docs here: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane


How do I setup Drupal/Varnish caching so Content Editors don't see browser-cached pages after logging in?

See the answer to this question:
https://drupal.stackexchange.com/a/117984/3279

Example usage for the D6 varnish module can seen here:
https://www.drupal.org/node/738420

So, you could do a hook_form_alter in a custom php module for D7 that adds an additional submit handler to your nodes that basically calls the D7 equivalent code to clear the varnish caches for the 1 node path path/aliases in question.


Modify Reference on Taxonomy Field Output

I managed to load the fields of the taxonomy term with this code:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php $taxonomy_term = taxonomy_term_load(54); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print $taxonomy_term->field_icon['und'][0]['filename']; ?>">

But I want to load the terms dynamically from the tid stored in this field:

The field 'field_produkteigenschaften' is part of the content type and is stored in the node object.

How do I now address the tid stored in the field 'field_produkteigenschaften' in this template?


Applying CSS to sub theme created by Omega

Two solutions:

rename in the CSS
rename in ALL .tpl.php file's theme

There are no other solutions.


Flexslider with Link - using Flexslider Field Collection

Just found it:

my Slider-Field-Collection ("field_slide") has:

[Label] -[Field Type] - [Widget]
Title- Text - Text field
Body - Long text - Text area
Image - Image - Media file selector
link - Link - Link

Display settings:

[Field] - [Format]
Image - Image Link Formater - Settings: Link image to: link (field_link)

in my content type I use that "field_slide" (embedded) and on display settings: Flexslider

This makes it easy to create content and add unlimited images (as slides) without creating each slide as a node.


Problem with using a taxonomy and taxonomy term referece field to organize my site content

When you want to automatically generate paths for nodes/taxonomies, using a specific 'pattern', the module Pathauto is the way to go.

By using the token of the selected/entered taxonomy term on the node, you can create the requested URL.


Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"

Fixed it!

When you delete an order on the order page, the associated payment does NOT get deleted. And, once the order is deleted, there is no way to delete the payment in Drupal commerce, since you only have a view of the orders.

Then, when you create a new order, the order number you deleted can get 'reused'. So, the old payment is then associated with this new order. That is why we saw the errant payments on the new orders.

So, I fixed this issue by going into the database and manually deleting all of the errant example payments in the commerce_payment_transaction table. So far, so good….

Bottom line: NEVER delete an order once live. Or, minimally, always delete the order's payment FIRST, then the order.


Exposed filters on blocks will only work if you've enabled ajax on the view. Try enabling that and your filters should appear


Omega Theme, change content zone when sidebar had no content

Yes, it is possible to change the column count for a region if another region is empty.

Go to the layout configuration of the Omega 3 Subtheme
Go to the zone that's the parent of the specific region
Set "Primary Region" to the region you want to give a flexible column count


How can we show the difference between values in consecutive rows in views

Daniel Cothran, the developer of the Views Cumulative field prepared a field (in no time at all) that serves the purpose. The link to the file is available here Measure of Change Field in Views Cumulative Field Module


How to get entity id of newly created entity using entity_get_controller

Assuming id is the name of your ID entity key, use this after the save:

$id = $entity->id;

You also have the option of using entity_extract_keys if you want to do it more generically:

list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);


Imce file/image browser not showing any buttons tab

Try changing the "administrative" theme - I observed this behavior with a custom theme, but it rendered the buttons if I changed themes to one of the standard themes.


How to extract data from DB into fields?

If you just want the content, you can use Feeds as Patrick said but this will replicate the content of the other database as entities in your Drupal site.

If you really want views connecting to a remote database, this question looks like a duplicate of:

https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data

This will help you make Drupal "aware" of the external db:

http://drupal.org/node/18429


Finally the problem in my case had to do with the text that was sent with mail after user registration. When user was registered a mail was sent in his inbox with his username and a (system created) password. Then the text was providing a link to the login page, a second one linking to the auto log in page (where the user supposedly would not have to enter his password) and a third one that it is irrelevant.

So i realized that the second link was actually a link to reset your password if you forget the old one. So the user when first reading the mail he click on the second link to log in automatically but he doesn't know that the password given to him was reseted and now his log in was valid only for one day or for one use. Each time he has to reset his password.

Anyway if you have access to your database you can experiment to see if it is another issue for you. You can create a fake account in drupal. In the mail that is sent to you click the second link (something like http://mysite.com/foo/user/reset/1085/1349294892/7bc9baf9d42aa774be00a0f36090323f). Then go to table 'user' of the drupal database, find the fake user you created and modify the record of the column 'created'  and put a unix-timestamp older than a day (there are online unix-timestamp creator). This way you can experiment if the password is temporary or not.


this might have to do with behaviours

see jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module


Excluding edge cases (querystring, hash tags, etc), this seems to work for all my test cases:

/**
 * Determine whether a given url matches the current page.
 *
 * @param string $test_path     A file path (no domain, no querystring, etc)
 * @return boolean
 */
function _nwr1_is_current_url($test_path){
    $test_path = trim($test_path, '/');
    $test_norm_path = drupal_lookup_path('source', $test_path);
    $this_nid = (arg(0) == 'node' && is_numeric(arg(1))) ? arg(1) : FALSE;
    $this_norm_path = ($this_nid) ? "node/$this_nid" : FALSE;
    $success = FALSE;

    // test by source (eg node/XXXX - preferred)
    if($test_norm_path && $this_norm_path && ($test_norm_path==$this_norm_path) ){
        $success = TRUE;

    // test by path
    }else if($test_path && current_path() && ($test_path==current_path()) ){
        $success = TRUE;
    }
    return $success;
}


Show facet filter even if there is no result

Not really, the facets (both search api and solr) are made up from the results of the search, therefore if there are no results then it doesn't know what to populate the facets with.

Depending on your expected output you may be best creating a custom/views block to display some relevant content then re-write the urls to conform with the search query, acting like a search facet.


The best solution I can think of for Drupal 6, would be to add some custom JavaScript to that page that scans all the links and attach a click handler on the links that matches the desired URL. Something like this:

$("a").each(function(){
  if (this.match('/bookmarks$/')) {
    $(this).click(function(){
      $.get(this.href, function(result) {
        $(result).find('#some .element').dialog();
      });
      return false;
    });
  }
});

The above code is written from memory, so is untested and probably flawed, but is can give you an idea of how to do it. The code requires jQuery UI dialog plugin to be loaded.


Fetching(GET) image url with applied image styles using jsonapi module

I would do it

create file: test_api.info.yml

name: Test API
type: module
description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
author: Minnur Yunusov
core: 8.x

create file: test_api.routing.yml

test_api.getparameter:
  path: 'my-api/get/{nid}'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::getpara_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

create file: /src/Controller/TestAPIController.php

<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function getpara_example($nid, Request $request ) {

    //get node;
    $node=node_load($nid);

    //get image uri
    $image =$node->field_image->entity->getFileUri();

    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');

    $url = $style->buildUrl($image);

    $response['nid'] = $nid;
    $response['uri'] = file_create_url($image);
    $response['image_original'] = file_create_url($image);
    $response['image_style_thumbnail'] =file_create_url($url);

    return new JsonResponse( $response );
  }

}

test:
url: localhost/drupal8/my-api/get/30
method: get

note: 30 is nid.

result:

{
  "nid": "30",
  "uri": "public://2017-10/generateImage_1RwT72.png",
  "image_original": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/2017-10/generateImage_1RwT72.png",
  "image_style_thumbnail": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/styles/thumbnail/public/2017-10/generateImage_1RwT72.png?itok=Dzg02oew"
}


ShareThis in header rather than content type?

Please try the following:

Go to menu Structure>Blocks.
find the ShareThis block.
set the block region settings for the theme you are using
go to block configuration and make sure the block is visible for all required pages, content types, roles, users
go to menu Configuration>Web Services>ShareThis
go to 'Advanced' section
find 'Location' settings
select 'Block' to select the ShareThis widget should appear as a block and not in a node content.


Of course.

I would do it this way:

1) Install of module devel.
Drupal7

2) go to drupal/devel/php
Of course.

Drupal8

in the textarea add:

  //please, change the nid of your node

use Drupal\node\Entity\Node;

$nid = 1;
$node = Node::load($nid);
$node->get('langcode')->value = 'da';
$node->save();

In Drupal7

$nid=1;
$node=node_load($nid);
$node->language='da';
node_save($node);


Links in second language not working when logged out

After much searching, I have code in the site's theme folder, within template.php, that made a call to the drupal_goto function if the connected user was not logged in, for all page requests where the language is set to french.

A search for $base_url led me to find this. Although now seeing that the redirection function in drupal is drupal_goto, I could have found this a lot quicker with a search for that call.


How do I correct error: Contained fields field is required in Commerce Index Filters

I am not sure if you found the solution for this error, but here is what i did.

on the /admin/config/search/search_api/index/product_display/workflow, the aggragated field settings, remove the fields that you don't need or have "unchecked" on the fields tab.

Hope this helps

Karim


How to get the users who did not submit articles?

Part 1 - Create an appropriate list of users

You could use an approach similar to my answer to "How to create a list of users who did not submit some webform?", i.e.:

Use the Flag module to introduce an article submission flag (similar to Step 1 in the above answer).
Register article submissions, using a Rules Event like "After saving content (of type article)", probably you don't need any special Rules Conditions.
List the users who have yes or no flagged "an" article with the flag from Step 1, using Views (similar to Step 3 in the above answer).

The above steps will allow you to create a list that is close to what you're looking for.

Part 2 - Filtering the list

To also filter them on which date they have missed the submission of an article node (as in your question), you would need to further enhance the view created in step 3. For that, there are various ways to do so. One of the possibilities is to use the DataTables module, and use its on-the-fly-filtering facility. This facility becomes available after you enable the "search" widget (somewhere within the datatables settings for your view). Refer to my answer to "How to display the data of a View in table format?" for way more details about DataTables.

Part 3 - Producing a message

To produce a message "Your article is pending" to those users (as in your question), you could enhance the view by adding the Views Bulk Operations (VBO) module to it, so that for the selected users you trigger a Rules Component which actually sends an appropriate eMail to those users. For an example of such rules component, refer to my answer to How to send an email notification when a subcription renewal is due? (within Step 2 of it).

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO.


Add custom text field to field settings form

What you'd have to do is define your own field type in a module, then use hook_field_settings_form to set the global options for that field (or hook_instance_settings_form for a specific content type's implementation).

Here's a general guide to creating your own field in Drupal 7, but to get a handle specifics of creating a custom settings option take a look at other modules' implementations of it.

For example, Drupal Commerce makes a set of options from existing customer profiles:

function commerce_customer_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
$form = array();

if ($field['type'] == 'commerce_customer_profile_reference') {
  $options = array();

// Build an options array of the customer profile types.
foreach (commerce_customer_profile_type_get_name() as $type => $name) {
  $options[$type] = check_plain($name);
}

$form['profile_type'] = array(
  '#type' => 'radios',
  '#title' => t('Customer profile type that can be referenced'),
  '#options' => $options,
  '#default_value' => !empty($settings['profile_type']) ? $settings['profile_type'] : 'billing',
  '#disabled' => $has_data,
 );
}

return $form;
}

Yours sounds more simple - but the same general idea. Get the field and instance data, do something with it, make another mini form and return it so it gets rendered.


Try the following:

/**
 * Implements hook_preprocess_media().
 */
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  /**
   * @note: in case your field not multiple, otherwise loop through the field.
   */
  $link = $media_entity->get('field_link')->first();
  if ($link->isExternal()) {
    //- External.
    $link_value = $link->getValue()['uri'];
  }
  else {
    //- internal.
    $link_value = $link->getUrl()->toString();
  }
  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}


Child navigation sidebar or drop-down navigation displaying child items

Drop-down menu from the main navigation menu, or some close
  alternative

Use Superfish. It integrates the jQuery Superfish dropdown plugin with your Drupal menus.

  Display all the children for that page in a sidebar

Use Menu Block. It provides configurable blocks of menu trees starting with any level of any menu. And more!


Listen to AJAX complete event from a behavior

Yes, there is :

Drupal.behaviors.YourBehaviour = {
attach: function(context, settings) {
  $('#yourform').ajaxComplete(function(event, xhr, settings) {
    if ($(event.target.id) == 'the-id-of-your-item') {
      // Your code here
    }
  });
 }
}


Newbie: Using css to style fields in a content type

There is a much easier way, but is still complicated if you're a newbie. Install the Display Suite module and enable Display Suite & Display Suite UI

Go to Structure -> Display Suite -> CSS classes. Add as many CSS classes for fields as necessary. Go to Structure -> Content types -> [xxx] -> Manage Display and you should be able to put the classes you have defined against each of the fields.


How to give an 'editor' role rebuild/clear cache permission?

To access this, they would need the administer site configuration permission.

From system.routing.yml:

system.performance_settings:
  path: '/admin/config/development/performance'
  defaults:
    _form: 'Drupal\system\Form\PerformanceForm'
    _title: 'Performance'
  requirements:
    _permission: 'administer site configuration'


Change node title and node field content

I think the $node will be a object and not array. You are trying to access it like an array, hence you get php error.

function module_node_view($node, $view_mode, $langcode) {
  $node->title = 'TEST';
  $node->field_description[$node->language][0]['value'] = 'CONTENT';
}


Modal form - cant set error message, and no message for required field

I know i'm a bit late but the problem is that the email field is required.
Required fields may not be empty, otherwise it will throw an error.

If you wish to show an error message you need a form element to catch these messages.

 $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];


Is necessary any sanitization functions if I use the database layer correctly

The db abstraction layer, as you noted, should prevent SQL injection attacks.

Check_plain is actually used to make sure text is html safe. If your printing out user submitted data to the screen, it should (at some point) be run through check plain to guard against cross site scripting attacks.


Custom php to handle url based on taxanomy terms

In views use TID converted to Name filter then use TID in url as a parameter and when the url is hit check the tid is valid or not and write behavior accordingly.


Using sender name and removing HTML entity encoding in Swiftmailer

I had the same issue and did the following to solve the issue with the entities.

$text = $message['body'];
$message['body'] = array_map(function ($text) {
  return Markup::create($text);
}, $text);

This will convert the body and will not display any entites anymore.


Sending Email verification when registering programmatically

When you create a new account using "user_save()", What status you passed "0" or "1", If you required email verification then it should be 'status' => 0, in user_save().


Drush CC all returning "No Drupal site found, only 'drush' cache was cleared"

There are a few things you can do to help debug your drush. Here is what you can try:

Debug output

Use drush cc all -vvv

This will provide you with some valuable information in terms of what Drush is doing in the background and maybe show you the actual error message.

Check your settings.php

Depending on your setup you may be passing in environment variables to your settings.php file for a database configuration for instance. Or perhaps to provide memcache. Drush unfortunately does not pick these up as it's bypassing apache. Therefore I would give it a test run without environment variables to see if that eliminates the issue or help narrow it down. For debug purposes it may be worth just using a clean copy from the example.settings.php and just modifying the database array to test this.

Check the mysql client is available

This is one that tripped me up a while ago and the drush -vvv will point you in the right direction. If it can read the settings.php, which it appears it seems to be able to as it gets the db settings, then perhaps it can't connect to your mysql database. One of the issues I had was that mysql client command was not available. E.g. try calling 'mysql' and see if that works. After fixing that it worked. In my Mamp setup it was just a matter of ensuring the correct path to the executable was in my shell $PATH.

I hope this helps.


How do I display information about a node's author on the full node and not the teaser view?

Just pop an if ($page): condition around it:

<?php if ($page): ?>

  <?php if ($display_submitted): ?>
    <?php print $user_picture; ?><?php print $name; ?>
  <?php endif; ?>

<?php endif;?>

In the context of node.tpl.php $page is defined on the docs page as a:

  Flag for the full page state.


if you want apply specific display formatter to some field like taxonomy terms, the best way is to write a display formatter module, and apply it to your entity_type via display setting on specific view mode, so if you want do this completely programmatically you need:

write display formatter moule
define view mode if necessary (e.g. for node we have full, teaser and ...)
add configuration to field instance setting

if you need some sample code to write display formatter module, let me know...

EDIT: if you want pass field instance setting to field_view_field you have something like this:

$display = array(
    'label' => 'hidden',
    'type' => 'colorbox',
    'settings' => array(
        'colorbox_node_style' => 'simpledeal_company_medium',
    ),
);
field_view_field($entity_type, $entity, $field_name, $display, $langcode = NULL);

this example code is about colorbox display formatter, should be replaced by yours

to do above via admin you should go to vocabulary display setting admin/structure/taxonomy/VOCAB_NAME/display, in CUSTOM DISPLAY SETTINGS check Taxonomy term page and set your display formatter, in this way you may do not need to change taxonomy-term.tpl.php


The filenames are wrong - they need to be migrate_plus.migration.*, not custom_migration.migration.*. The first component of a configuration entity filename is the module that defines the entity type, not the module defining the entity instance.


how disable edit for a certain content type, and a certain role,

In /admin/people/permissions Under "Node" category you can uncheck the permission "Edit content X" for your desired role.

I would recommend using this module if your site has a lot of modules/permissions since due max upload vars limitation by PHP could led to not storing your chages when submitting the form.

Also by code you can implement hook_node_access and put there some logic. Take a look on how core does it.

/**
 * Implements hook_node_access().
 */
function node_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
      return NODE_ACCESS_ALLOW;
    }

    if ($op == 'update') {
      if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
        return NODE_ACCESS_ALLOW;
      }
    }

    if ($op == 'delete') {
      if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
        return NODE_ACCESS_ALLOW;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}


Best way to achieve the following layout

Try Single Page Website module. Its a good option for this kind of website. Just create menu and give proper link.

  This module provide the ability to display the content of all menu items of the menu that you indicate in settings on the Single Page Website module.
  On the page 'single_page' the links in the menu will be replaced to the links to the correspondent anchors.
  You can set URL 'single_page' as front page of your site, and your visitors will see the Single Page Website. But it will be the site managed by Drupal 7.


paragraphs_update_8018 takes very long time to finish

Disclaimer: act on your own risk!

After looking into what this update exactly does, I decided to execute it without maintenance mode. It worked without any problems. It depends on your situation though. You have to make sure that nothing interferes with the tables in question (no editors editing paragraphs, no automatic content imports/updates etc.).

Note that drush updb automatically enables maintenance mode, you have to disable it explicitly.

Of course generally speaking it's not a good idea to disable the maintenance mode during drush updb and problems may occur.


Create a new class in your module that extends \Drupal\node\Entity\Node.

use Drupal\node\Entity\Node as BaseNode;

class MyNode extends BaseNode {
}

Implement hook_entity_type_build().

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * @param EntityTypeInterface[] $entity_types
 */
function my_module_entity_type_build(&$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->setClass('Drupal\my_module\Entity\MyNode');
  }
}

Remember to rebuild the cache.

It works fine when loading nodes via the entity type manager service and the node storage. It even works when you just use Drupal\node\Entity\Node::load($nid) thanks to the fact that this load() function it is just a static wrapper for the entity type manager service call provided by the Entity class which is extended from the Node class.

// Part of Entity class for reference
abstract class Entity implements EntityInterface {
  /**
   * Loads an entity.
   *
   * @param mixed $id
   *   The id of the entity to load.
   *
   * @return static
   *   The entity object or NULL if there is no entity with the given ID.
   */
  public static function load($id) {
    $entity_manager = \Drupal::entityManager();
    return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
  }
}

This also works fine with the soon-to-be-removed entity_load_multiple() function, so I guess this covers all standard use cases for loading nodes.

Of course, if your module does this and another module does the same, you'll have a problem, but I guess it's not common scenario, and it makes sense only for very specific use cases.


Can we add third one here?

Yes, we can. Use hook_form_alter(), alter form_id menu_configure.

How do I know what form_id? Let's see menu_menu() at http://api.drupal.org/api/drupal/modules--menu--menu.module/function/menu_menu/7

  Is there any way to get the list of
  all menus created in backend?

Again, We can. Select menus in table {menu_links} where {menu_links}.menu_name = management.

    $result = db_select('menu_links', 'm')
    ->fields('m')
    ->condition('menu_name', 'management','=')
    ->execute()
    ->fetchAssoc();


Contextual views - show articles that the current user is interested in

1) Create users View

2) Add contextual filter of User ID

3) a) Add relationship of reference field

3) b) Checkmark require this relationship

4) a) Add relationship of Content with term

4) b) Checkmark require this relationship

5) Now in FIELDS it should allow you to add title field

6) Remove Name from fields.
7) Add FILTER CRITERIA of Published content

Overall, should look like this:


Images are hardlinked inside the body field.

One way to correct it is to do a search and replace inside the database.

Perhaps also pathologic can help correct the problem with broken images.

add pathologic support to your desired text formats (congig > content authoring > text formats)
make sure you check  Correct URLs with Pathologic

when visiting a page pathologic should correct those broken images


Drupal 7: Two submit buttons and custom field validation

I'd suggest using the #submit property

For example:

$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Sign Up')
);
$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey')
  '#submit' => array('custom_submit_for_this_button')
);

And then:

function your_form_name_submit($form, &$form_state) {
  // your logic for first button here; this is auto-called by Drupal
}
function custom_submit_for_this_button($form, &$form_state) {
  // your logic for second button here
}


How To Remove Menu Tabs From Custom User Dashboard

You can do that from your theme's template.php file by implementing the theme_menu_local_task().

Using this function you can also rename specific tabs.

Code for both actions is below.
It is taken from this file of our Ultima theme.

<?php

/**
 * @file
 * Theme local task function.
 *
 * Created by: Topsitemakers
 * http://www.topsitemakers.com/
 */

/**
 * Implements theme_menu_local_task().
 */
function YOURTHEME_menu_local_task(&$vars) {

  $link = $vars['element']['#link'];

  // List of tab names to be excluded; t() function will ensure that the
  // tab name will be matched and excluded on multilingual sites as well.
  // This is useful in case you have many modules installed on the site and
  // large number of tabs break the layout of the theme.
  $excluded_links = array(
    t('View'),
  );
  if (in_array($link['title'], $excluded_links)) {
    // Skip all further processing.
    return;
  }

  // Uncomment code below to rename the "View" tab for certain node types
  /*
  // Check if the link title is "View"
  if ($link['title'] == t('View')) {
    // Make sure we are on single node page
    if (arg(0) == 'node' && arg(1)) {
      $node = node_load(arg(1));
      // Do this for specific content types
      if ($node->type == 'page') {
        $link['title'] = t('View full page');
      }
    }
  }
  */

  // Continue building the local task link
  $link_text = $link['title'];

  if (!empty($vars['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";

}


Special non-utf-8 characters appearing in feed imported from a windows based system?

You can use the Feeds Tamper module to do this with a custom plugin.

In your module:

/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($owner, $plugin_type){
  if ($owner == 'feeds_tamper' && $plugin_type == 'plugins') {
    return 'plugins';
  }
}

and in your module/plugins/utf8_encode.inc

$plugin = array(
  'form' => 'MYMODULE_utf8_encode_form',
  'callback' => 'MYMODULE_utf8_encode_callback',
  'name' => 'Convert ISO-8859-1 to UTF-8',
  'multi' => 'loop',
  'category' => 'Text',
);

function MYMODULE_utf8_encode_form($importer, $element_key, $settings) {
  $form = array();
  $form['html'] = array(
    '#markup' => t('This will convert all ISO-8859-1 characters to their UTF-8 equivalents.'
),
  );
  return $form;
}

function MYMODULE_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $field = utf8_encode($field);
}

If that doesn't work, then you can use one of the strip-non-UTF8 regex functions to do it in the callback instead.  I use

$regex = '/((?:[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}[\xF0-\xF7][\x80-\xBF]{3}){1,100})|./x';

preg_replace($regex, '$1', $field);


How drupal.org found a website installed module

Drupal.org gets 'reported installs' from the Update manager module. So to do something like that you would need you custom module to report back to a server of yours, and preferrably have your users be notified for that.


Add a class to a div depending on which term was clicked

The taxonomy term that is click will already have the class "active" applied to it.

The selector .field-type-taxonomy-term-reference a.active is the one you are probably looking for.


Check if a module is enabled with JavaScript

I can think of two ways:

Send a JavaScript flag as settings, indicating the module is active:

drupal_add_js(array('my_module' => array('enabled' => TRUE)), 'setting');

If the module is enabled, modify the output in some way so the JavaScript code that makes the petition is included only when your module is enabled, or the contrary way, make sure that code is not included if your module is disabled: you will have to use another module or some kind of configuration. The exact way depends on the origin of the JavaScript code that makes the Ajax petitions.


You can add fields to be explicitly ignored by adding addUnmigratedDestinations to your class:

$this->addUnmigratedDestinations(array(
  'roles',
  'role_names',
));


Create / Edit node and continue editing on same page after submit

The Save & Edit module is a very basic module. It comprises of 6 total functions, so a port could be done less than a day.

Alternatively, if the your requirement is to just save editing progress while keeping the editor window up, the Autosave form module does that.

If you're looking to go the custom code route, some simple jQuery form manipulation can add a button which can trigger a form redirection & submit. For example:

// Set the form destination to the edit form and submit it.
jQuery('form.node-form').attr('action', '/node/<NID>/edit?destination=node/<NID>/edit');
jQuery('.node-form').submit();


How to tell Drupal to use tpl file from my module?

You need to use hook_theme:

/**
 * Implements hook_theme().
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {

  if($type != 'module') {
    return [];
  }

  // If you want to put your templates in a templates directory
  // in your module directory add .'/templates' to the end.
  $module_path = drupal_get_path('module', 'MY_MODULE');

  return [
    'comment' => [
      'template' => 'comment',
      'path'     => $module_path,
    ],
    'other_template' => [
      'template' => 'comment',
      'path'    => '/my/custom/path/here',
    ],
  ];
}

This has set up our custom theme, then when you want to use it you can:

$tpl_data = [
  'param1' => $foo,
  'param2' => $bar,
];

return theme('comment', $tpl_data);

Now $param1 and $param2 will be available in your template file too.

If you don't need any custom data in your template then $tpl_data can be omitted.

Happy days.


Node access depending on boolean field in user profile

I got it working, for the sake of anyone ever needing this functionality and stumbling upon this thread:

You'll need the Access Control and ACL modules. The combination of these allows you to set "per user" access for each individual node. For the checkboxes on a profile or page, you'll need to use the Entity Reference module and create a field on the profiles for that type of content. You can then set that field up as checkboxes.

For the final part, you'll need the Rules module and set up two rules: one to "Grant Access per user" and grant view access when a specific value of the checkboxes is true and one to "Revoke Access per user" when values have changed. You'll need to play around with the rule's conditions to make it suit your needs.


How to implement a transaction process between users using the Privatemsg module?

You may want to use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "Something is flagged" (created with the Flag module, and the "something" being a product), then a simple click could be used to indicate "I want to transfer 25 user points of mine to this user" (probably to trade that product in your case).

You could take this even a step further: since flags are fieldable, you could add these fields to such flag (to implement a bidding-system):

A field to indicate the amount of points to be "moved" (= like the price to be payed for the product?).
A field to indicate the price requested by the seller.
A field to indicate the price offered by a potential buyer.
A field for some text to be used for storing some message text. Possibly you may want to "deliver" that message text using the Message module, which has a great integration with Rules also (though it's not obvious to get started with the Message module).

Note: The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.


Display 3 items by default in a multivalue field?

You can do it by jQuery, when page loads simulate the click event on the add more button using onClick()


Combine Token title with url in an email

Have you tried the token_replace function?


I had a similar case, i had to add a few attributes to the basic_html format in the Allowed HTML tags so it could work with the module editor_advance_link which allows the users to add title, class, id and target attributes to the a tag when using the core's CKEditor.

So this is what i did with some code i found here ( https://www.drupal.org/files/issues/allow_image_style_to_be-2061377-224.patch)

if ($filter = FilterFormat::load('basic_html')) {
    if (($filter_html = $filter->filters('filter_html')) && $filter_html->status) {
      $config = $filter_html->getConfiguration();
      $allowed_html = !empty($config['settings']['allowed_html']) ? $config['settings']['allowed_html'] : NULL;
      $matches = [];
      if ($allowed_html && preg_match('/<a ([^>]*)>/', $allowed_html, $matches)) {
        $new_attributes = array_filter(explode(' ', $matches[1]));
        $new_attributes[] = 'target';
        $new_attributes[] = 'title';
        $new_attributes[] = 'class';
        $config['settings']['allowed_html'] = preg_replace('/<a ([^>]*)>/', '<a ' . implode(' ', array_unique($new_attributes)) . '>', $allowed_html);
        $filter->setFilterConfig('filter_html', $config);
        $filter->save();
      }
    }
  }

Don't forget to include:
use Drupal\filter\Entity\FilterFormat;

This code is needed to be run only once, so i had to include it in a .install file in a custom module.


In hook_node_insert drupal_goto with alias name not working

I checked the drupal_goto and found out that you must provide the path for parameter. You can't use alias for drupal_goto. So i think you can solve your problem like that:

While you create node. You will also create the alias for that node. The reference for create the alias for node here. In your code just normally redirect like that

drupal_goto('node/'.$node->nid);

After that you will install Global redirect module. This module will have responsibility to redirect your node/nid to your node's alias

[Updated]

Can you try to generate the alias by using the Pathauto. So can you put these code in hook_insert()

function yourmodule_node_insert($node){
  module_load_include('inc', 'pathauto');
  pathauto_cleanstring($node->title);
  $node->path = array('pathauto' => TRUE );
  drupal_goto('node/'.$node->nid);
}


How do you output views reference field views in Twig?

Got it!

You have to pass the view ID and the display ID to drupal_view() dynamically.

But first let me tell you that what you are doing, printing node stuff inside page level templates, should be considered bad practice. Good practice is to leave templates untouched, and to offer field formatters and other stuff instead that keeps the admin UI intact. So, when you get your first maintenance breakdown in a year or so, don't tell us we didn't warn you.

page.html.twig

{% if node.field_views and not node.field_views.isEmpty() %}
  {% for view in node.field_views.value %}
    {{ drupal_view(view['target_id'], view['display_id']) }}
  {% endfor %}
{% endif %}

You won't get the view title from here. Simply add some Global: unfiltered text to your view HEADER with any title markup. That will get printed.

drupal_view() requires Twig Tweak.


Using form_set_value with commerce in custom form

The code executed from form_set_value() is the following one.

function form_set_value($element, $value, &$form_state) {
  drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
}

$checkout_pane['pane_id'] . '][donation_amount' is a string, even if $checkout_pane['pane_id'] is an array; this is because the string concatenation operator cast an array into a string.
If $element is a string, then $element['#parents'] is a string made of one character, similarly to what happens with $string[0], when $string is set to 'long string with many characters that are added just to make the string longer'.

That explains the error about the second argument.

With form_set_error(), $checkout_pane['pane_id'] . '][donation_amount' works because the function is expecting a string as first argument, and the format of that string is exactly the format of the string you are passing.

The first argument of form_set_value() is a form API array for the form element for which you want to set the value. That is not the content of $form_state['values']. As that is the code for a form validation handler, it should be similar to the following one.

function mymodule_form_validate(&$form, &$form_state) {
  // …
  $form[$checkout_pane['pane_id']]['donation_amount']['#parents'] = array($checkout_pane['pane_id'], 'donation_amount');
  form_set_value($form[$checkout_pane['pane_id']]['donation_amount'], '999', $form_state);
}

You still need to verify the content of $checkout_pane['pane_id'] is effectively the parent of the element you want to change. For that, you can install the Devel module, and print the structure of $form using dpm($form);.

As for the answer given in the other question, I can say it is based on the description present in form_set_value() for the $element parameter.

  The form element that should have its value updated; in most cases you can just pass in the element from the $form array, although the only component that is actually used is '#parents'. If constructing yourself, set $element['#parents'] to be an array giving the path through the form array's keys to the element whose value you want to update. For instance, if you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2');.


After more hours than I care to admit, I came to realize that the issue was very simple... The Pantheon Dashboard's links to "site admin" go to the http:// site and NOT the https:// site, therefore, none of the addresses were resolving correctly. The live site automatically redirects http:// traffic to https:// so it works just fine.


The rules module provides a function called rules_config_delete().

You can call this with an array of rules ids to delete multiple rules in one go:

rules_config_delete(array(3, 4, 5, 6));


Setting a default checkbox value in FAPI

Try this one:

$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = array($unitid->nid);

And please note that node_load returns an object but not a ID. I see you use $unitid as the variable name. It can make people confused.


Composer installation of drupal console missing functions

I'm having the same issue.  Per some other posts, I've tried starting fresh

Deleted drupal/console from composer.json (in docroot)
Deleted composer.lock
Ran composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader
Ran composer update drupal/console --with-dependencies

vendor/drupal/console/bin/drupal shows I've got 1.9.3, but the only generate command I get from list is gsa as shown in sisko's post.  I get the same thing in both Drupal 8.5 and Drupal 8.7.


How to use hook_user_login and hook_user_logout to output content to the page

It will not work in template.php
You need to add this in a module file, check here on howto
instead of myTheme it will be modulename
If module name is foo then it will be foo_user_login

    // @file : foo.module
    function foo_user_login(&$edit, $account) {
      fluenz_user_function($account->uid);
    }
    // and this function name was also different just an FYI
    function fluenz_user_function($uid) {
      for ($i=0; $i < 1000; $i++) {
        echo 'hi<br>';
      }
    }


Okay, I have figured out a solution, although its a bit crude. Before I continue, I should mention that my aim was to also to create hackable URLs.

Installed the Taxonomy_Display module. Created a Content View, and immediately added a contextual filter Content: Has taxonomy term ID with the following configuration:

WHEN THE FILTER VALUE IS NOT IN THE URL:

Provide default value
    --> Type = Taxonomy term ID from URL
    --> Load default filter from node page, that's good for related taxonomy blocks
    --> Vocabularies = Category

WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED

Specify validation criteria
    --> Validator = Taxonomy Term
    --> Vocabularies = Category
    --> Filter value type = Term Name converted to term ID (got this from the Taxonomy_Display module)
    --> Transform dashes in URL to spaces in term name filter values = Checked
    --> Action to take if filter value does not validate = Show "page not Found"

I then added a relationship: 'Content: Taxonomy terms on nodeon my vocabulary, to give me access to the Taxonomy filters, and added a field filter onTerm = Category` through the relationship created.

Finally, I cloned 3 pages based off the above config, with a page path to categories\%\articles, categories\%\photos, and categories\%\videos, and on each of these added a further filter by the respective content-type.

Well, it does what I want it to, but it somehow still doesn't strike me as an ideal solution ... I think it could be simpler, whilst also allowing for dynamically identifying the content-type from the URL. Therefore, I won't mark this yet as the answer, until someone can critique my approach. :)


Limit Migrate explode process plugin to 1 takes whole string

Just found the solution after rereading the PHP explode docs:

  If limit is set and positive, the returned array will contain a
  maximum of limit elements with the last element containing the rest of
  string.

So setting the limit to 1 has the effect that the returned array element contains the rest of the string, which in my case is the whole string. So setting the limit to 2 fixes the problem and gives back the first part of the string:

field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 2
      delimiter: '|'
    -
      plugin: entity_generate


"[node:flag-vote-count]" displays the token name, not the number

OK , so I solve it.

The [node:flag-vote-count] is really not working.
But you can look for another count token for the flag you created, under the TOKEN REPLACEMENT -> nodes.

Good luck :)


How to display the default user picture programatically?

It's a bit of a strangled route - Drupal itself uses some conditionals in template_preprocess_user_picture() to make that decision:

if (!empty($account->picture)) {
  // @TODO: Ideally this function would only be passed file objects, but
  // since there's a lot of legacy code that JOINs the {users} table to
  // {node} or {comments} and passes the results into this function if we
  // a numeric value in the picture field we'll assume it's a file id
  // and load it for them. Once we've got user_load_multiple() and
  // comment_load_multiple() functions the user module will be able to load
  // the picture files in mass during the object's load process.
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

If it suits your use case, you can just set the user_picture_style variable to your style name, and use theme_user_picture():

$build = array(
  '#theme' => 'user_picture',
  '#account' => $user,
);
$picture = drupal_render($build);

The caveat is that user_picture_style is a global var, so if you want to use something different for the style used elsewhere in the site, you're stuck with reproducing the same logic as the preprocess function above.


Sort a Table View by Fivestar Rating Fields

This is incredibly late, but I just found the answer to the Fivestar rating issue:

You need to add "Content: Vote results" as a View relationship, then sort by "Vote results: Value".

Sorting by "Rating: Average Rating" seems to do nothing, as the queried fields seem to be undefined. This method, however, will work.