I want to get all of the allowed values of a field

For list type field you can use list_allowed_values function , You can also use field_info_field($field_name) for more details about field.

$my_field = field_info_field('field_resource_type');
$allowed_values= list_allowed_values($my_field);


Commerce add to cart not adding product to cart

Go to views of the page that contain add to cart button, in advanced and in caching you find none and time based, tick none and the problem will resolved.


Solr search api indexing referenced fields by their id not value

Just to provide an answer, maybe it'll be useful to someone.
You can't At least not without a lot of hacking/patching the solr api module.


How to avoid calling performRequiredValidation() for custom element

That error is caused from the following code.

  if (isset($elements['#options']) && isset($elements['#value'])) {
    if ($elements['#type'] == 'select') {
      $options = OptGroup::flattenOptions($elements['#options']);
    }
    else {
      $options = $elements['#options'];
    }
    if (is_array($elements['#value'])) {
      $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
      foreach ($value as $v) {
        if (!isset($options[$v])) {
          $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
          $this->logger->error('Illegal choice %choice in %name element.', array('%choice' => $v, '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']));
        }
      }
    }
    // Non-multiple select fields always have a value in HTML. If the user
    // does not change the form, it will be the value of the first option.
    // Because of this, form validation for the field will almost always
    // pass, even if the user did not select anything. To work around this
    // browser behavior, required select fields without a #default_value
    // get an additional, first empty option. In case the submitted value
    // is identical to the empty option's value, we reset the element's
    // value to NULL to trigger the regular #required handling below.
    // @see \Drupal\Core\Render\Element\Select::processSelect()
    elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
      $elements['#value'] = NULL;
      $form_state->setValueForElement($elements, NULL);
    }
    elseif (!isset($options[$elements['#value']])) {
      $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
      $this->logger->error('Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']));
    }
  }

It means that the value set for $elements['#value'] (which could also be a value submitted from the users) is not contained in $elements['#options']. In fact, your code contains the following code.

$grouped_types = _getTypesGrouped();

// Override select form element.
$element['#settings'] = [
  'plugins' => ['optgroup_columns'],
];
$element['#type'] = 'selectize';
$element['#options'] = $grouped_types;

Since there isn't a _getTypesGrouped() function, you are essentially setting $element['#options'] to NULL, which means you are removing all the possible values the form field for that widget can have.
The correct code you want to use is the following one.

$grouped_types = $this->_getTypesGrouped();

// Override select form element.
$element['#settings'] = [
  'plugins' => ['optgroup_columns'],
];
$element['#type'] = 'selectize';
$element['#options'] = $grouped_types;

As for avoiding Drupal runs FormValidator::performRequiredValidation(), that is a bad idea. The purpose of that method is avoiding users submit a forget form; removing it means to mine the site security.

As side note, protected method don't need an underscore at the beginning of their name, as per Drupal coding standards.


Is it possible to edit Views code instead of the ui?

An easy way to do this would be if you had the features module that will contain the code of the view.  Otherwise this information is stored in the database.  Simply enable the module, create a new feature and add your view to it.  Then it will be stored in code for you to alter.


How to programmatically add image from external URL using media module?

Make sure your php.ini allows allow_url_fopen. Then you can use something like this in your module:

$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);

Use php's file_get_contents() function

http://www.php.net/manual/en/function.file-get-contents.php

and then use Drupal API's file_save_data()

http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/7

Then you should be able to call it using and save it to a node etc ..

$node = new stdClass;
$node->type = 'node_type';
node_object_prepare($node);
$node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid;
node_save($node);

Edit:

As pointed out in the comments, you can use function system_retrieve_file
See: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_retrieve_file/7


How to add selected users to OG Group from field selection when creating group

This is the rule I created to solved it:

After updating/adding existing content of type
Entity has field Parameter: Entity: [node], Field: FIELD WITH UNAMES
Crete a LOOP
(In Loop) Subscribe user to group -- Parameter: User: [list-item],
Group: [site:og-context--node]

Here is an export of my rule:

{ "rules_watch_list_group_add" : {
  "LABEL" : "Watch List Group Add",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "og" ]
  "ON" : { "node_insert" : [], "node_update" : [] },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_watch_list" } }
  ],
  "DO" : [
    { "LOOP" : {
        "USING" : { "list" : [ "node:field-watch-list" ] },
        "ITEM" : { "list_item" : "Current list item" },
        "DO" : [
          { "og_subcribe_user" : { "user" : [ "list-item" ], "group" : [ "site:og-context--node" ] } }
          ]
        }
      }
    ]
  }
}


Model view and labels are not displayed correctly

You're trying to change the content of your XML to provide structural changes to the XML document. This content is escaped so it doesn't break the XML document.

If the whole goal of theming is set your XML image field to a image:loc element, you should just change add a Label to your field with it set to "image:loc". This will render the XML document image field as an image:loc element.


Straight from the PHP Global space docs:

  Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Devel's dpm() is declared in 'Global space', and since there's no other dpm() function declared in your namespace, the 'global' one is used (no need for the preceeding \).


Why are spaces in the file path rendered with %2520 instead of %20?

I found a kind of workaround: I wrote {{ file__target_id|replace({'%20': " "}) }} in the definition of 'file' field in the view.


What you need is a rule that is fired when the comment is first published and that seems very straight forward to me. If you need any further help on that, please let us know.


Display Suite ignores hook_preprocess_node()

Display Suite does indeed hijack the node rendering to a point where the default preprocess functions may not be used.

The module comes with a set of its own preprocess functions that are documented in ds.api.php.

In this case, hook_ds_pre_render_alter() can be used instead of the hook_preprocess_node() to modify the output via the complete render array. Also, the $entity object is available with all values.


Show field collection fields with profile field

If I'm reading it correctly, you should be able to create a relationship based on your Field Collection field.

Under Advanced (this might be collapsed in the Views UI - it normally is by default) click relationship, and then click on the Field Collection field containing your user information.

Now you'll find when you go to add a field into your Views display, that there are more fields available to you.  These are the fields stored in the Field Collection entity that you can now style in a table, an accordion, a list...whatever you fancy!


Custom node access control not working with access filter?

Lists like views will not be passed through hook_node_access(), as this would create too much overhead. Views does a query on the database to get the results. hook_node_access() is run in PHP, so these won't work (easily/well/efficently) together.

To deal with lists, you will need to create a grant system, using hook_node_access_records() and hook_node_grants(). This system writes to the {node_access} table in the database, and when a list is created, the database query is cross-referenced with that table.

hook_node_access_records() is called when a node is saved. Modules that implement this hook can set up various states by which the node is allowed to be accessed.

hook_node_grants() is then called when the node is viewed/updated/deleted. A set of potential grants is created based on the current environment, and these are compared with the states created in hook_node_access_records(). If there is a match, access is provided.

In your case, hook_node_access_records() should create a state whereby if the node has the field field_content_protect, then a state should be created upon which view access can be either granted or denied in hook_node_grants(). Example:

function MODULE_node_access_records(\Drupal\node\NodeInterface $node) {
  if ($node->hasField('field_content_protect')) {
    $grants = [];

    $grants[] = [
      'realm' => 'MODULE_protect_content',
      // This is set to 1. In hook_node_grants(),
      // A value will be created based on the user's
      // logged in state, and compared to this value.
      'gid' => 1,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    ];

    return $grants;
  }
}

The above sets up a state, whereby if a grant is created for the realm MODULE_protect_content that has a value of 1, the user should be granted view access. The next thing is to implement hook_node_grants() and create a grant based on the current user's status.

function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();
  $grants = [];

  // This will set a value of 0 (zero) or 1 (one)
  // for the realm MODULE_protect_content. If the
  // value is 1 (authenticated user) the user will
  // be provided view access to the node. Note
  // that an array of values must be passed for
  // realms.
  $status = (int) $current_user->isAuthenticated();
  $grants['MODULE_protect_content'] = [$status];

  return $grants.
}

For the above code, a grant is created based on the logged in status of the current user. If they are logged in, $status will equal 1, which is compared with the state provided in hook_node_access_records() providing access to the user.

You could actually alter the above hook_node_grants() to only return a grant if the user is logged in. I'm not sure which one would be more efficient. I suspect the code below may be:

function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();

  if ($status = (int) $current_user->isAuthenticated()) {
    $grants = [];
    // This will set a value of 1 (one)
    // for the realm MODULE_protect_content, which
    // matches the state created in
    // hook_node_access_records(). Note that
    // an array of values must be passed for
    // realms.
    $grants['MODULE_protect_content'] = [$status];

    return $grants.
  }
}


How can I get a relation by the endpoints using the "Fetch entity by property" action in rules?

I have managed to fetch relation by endpoint with the help of @marcusx and the patch of @MahmoudMostafa (drupal user names). You can find all in the issue Fetch Relation by Endpoints in rules.
I had also linked your issue to that one.
Resuming the steps here, you need to:

apply the patch

Create a list of any entiy
Put your endpoints in the list
Use the endpoint list to fetch the relation

cited from marcusx comment

(I see you already know this).
Bear in mind that

"fetch relation by endpoints" action in rules, [...] fetches all the relations for the endpoints in the chosen list, even if the list contains only one endpoint.
In this (sub)case, the action fetches all relations pointing to the selected endpoint, whatever the other endpoint.
cited from my comment

And that the resulting fetched_relation is a list (I see you already know this as well).
I believe you only need to apply the patch, which you didn't mention in your question. Is it true?


Here's how I would do it (but I'm rather new to this, so maybe your approach is better)...

function mythemename_preprocess_page(&$vars, $hook) {
  if (arg(0) == 'years') {
    drupal_add_css(path_to_theme().'/css/years.css');
  }
}


Views - Filtering view results by current user profile field

You can filter contents on their term_reference_field by the field_value of a term_reference_field of the current_user:

So we go:

Create a content_view
Create a relationship with "favorite_car"
Create a relationship with "term from favorite_car"
Create contextual filter user:uid with provide default_value: user_id from logged in user and the relationship favorite_car

This works for me!


Why does node_access_view_all_nodes() return true for anonymous users?

whenever drupal needs to check if a current user has the right or not to see a specific node it passes through this process :
1. check if current user bypass node access
In determining access rights for a node, \Drupal\node\NodeAccessControlHandler first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. user 1 (administrator) will always pass this check.

2.check Hook_node_access implementations
Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly forbid, or ignore the access request. If at least one module says to forbid the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted,
in the Example bellow whenever any user(except admin) tries to view a node we will check if field_prevent_webmaster is checked the user will get access forbidden message.
/**
 * Implements hook_ENTITY_TYPE_access
 */
function modul_name_node_access(\Drupal\node\NodeInterface $node, $operation, AccountInterface $account) {

  // 1.limit the action according to the  operation performed on the requested entity
  switch($operation){
    case 'view': // when a user visit a node page ex : /node/52

      // 2.limit the current operation according to the current account information
      if( in_array('webmaster',$account->getRoles()) ){
        //3. then further limit the current operation according to the current requested node entity field
        // ex : if field_prevent_webmaster is checked prevent a user form
        // viewing the node through the /node/{id}
        if($node->hasField('field_prevent_webmaster') ) {
          if ($node->field_prevent_webmaster->value == TRUE) {
            return AccessResult::forbidden(); // send Access denied message to the client
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed(); // send Access denied message to the client
          }
        }

      }
      break;

    case 'delete':// in /admin/content page u won't find the 'delete' button
      if( in_array('webmaster',$account->getRoles()) ){

        if($node->hasField('field_prevent_webmaster') ){
          if(  $node->field_prevent_webmaster->value == true){
            return AccessResult::forbidden();
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed(); // send Access denied message to the client
          }
        }

      }
      break;

    case 'update': // in /admin/content page u won't find the 'update' button
      if( in_array('webmaster',$account->getRoles()) ){

        if( $node->hasField('field_prevent_webmaster')){
          if(  $node->field_prevent_webmaster->value == true){
            return AccessResult::forbidden();
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed();
          }
        }

      }
      break;
  }
}

3.Getting permissions from node_access table
If all modules ignore the access request, then the node_access table is used to determine access and this more complicated then the previous 2 so we need to understand :
the node access table

nid: The node id that will be affected by this permission line.
gid(like user): the grant id, is simply a way to associate a user with a node.
realm(like user type): It can be pretty much anything you want to consider it as a user type that groups a set of grant ids (gid).
grant_view: Boolean indicating whether a user with the realm/grant pair can view this node.
grant_update: Boolean indicating whether a user with the realm/grant pair can edit this node.
grant_delete: Boolean indicating whether a user with the realm/grant pair can delete this node.

Example according to the node_access table bellow:

the user that have gid=2 and realm=node_atuthor, he can view and update the node 52.
the user that have gid=2 but a realm=node_super_user, he can view , update and delete the node 52.

Hook_node_access_records()
when a node is saved this hook will be executed, which enables us to fill the node_access table with the permission privileges that have already explore in the previous step.
/**
 * Implements HOOK_node_access_records
 **/
function entity_access_node_access_records(\Drupal\node\NodeInterface $node) {
   $grants = [];
   if( $node->isPublished() == TRUE) {
     $grants = [
       [
         'realm' => 'node_author',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 1,
         'grant_delete' => 0,
         'priority' => 0,
       ],
       [
         'realm' => 'node_viewer',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 0,
         'grant_delete' => 0,
         'priority' => 0,
       ],
       [
         'realm' => 'node_super_user',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 1,
         'grant_delete' => 1,
         'priority' => 0,
       ]
     ];
   }
  return $grants;
}

Hook_node_grants()
is called every time access to a node is requested to determine access and this is what is used to check the node_access table and decide who what nodes the current user can see:
/**
 * Implements Implements HOOK_node_grants
 */
function entity_access_node_grants(AccountInterface $account, $op) {

  // Allow the user that have 'see_omar_is_nodes' permission and that is also not omar :
  if ($account->hasPermission('see_omar_is_nodes') && $account->id() != 3){
      // to get This gid realm grants ( to see his content + Omar is content)
      $grants = [
        'node_super_user' => [$account->id()],
        'node_viewer' => [3]
      ] ;
  }

 // else if the user acount id =3 (omar)
  else if ($account->id() == 3){
    // get This gid realm grants of current user
    $grants =[
      'node_author' => [3]
    ] ;
  }


How to add multi nodes on a single page without using an iFrame?

Consider using the Rules module, to insert a message with a clickable link in the Drupal Message area, whereas that link points to "/node/add" each time a node is saved.
Here is a summary of the rule to implement this:
Events: After saving new content
Actions: Show a message on the site, whereas the "value" of the message to be displayed should be something like so: Click to add another node.
This assumes you want to do this for all possible content types. If you'd want to limit it to specific types only, you'd have to add appropriate
Conditions (for the desired content types) also.


Clear the cache after adding your custom values to the database.  Might fix the problem as I have seen it work for some in the past.


How to expose non Drupal tables in Views?

The data module is a good start.

You can skip the data module and create your own views type with hook_views_data()
Angie has an example here.

Date times can be tricky, if you post another question with your specific problem with date times there may be a solution.

You don't specify if the DB is the same. You would need to define a second database in your settings.php if you need to connect to a different DB.


This issue I ran into was I did not specify '#theme' in the Block Plugin.

I added

public function build() {
    return array(
        '#theme' => 'myplugin',
        '#title' => 'Test',
        '#color' => $this->configuration['color'],
        );
}

and it worked


What are the ways/strategies to maintain Drupal sites a over period of 10-15 years?

Like you mentioned there are many moving parts about Drupal that can require maintenance, so your strategy should be to remove as many dependencies as you can within your requirements.

If it is not a requirement that your Drupal sites continue as dynamic systems where content can be created, updated, or deleted then you should remove MySQL and PHP by generating static files. There is good documentation for creating static archives of a Drupal site at http://drupal.org/node/27882.

Since you mentioned putting the site into a "maintenance or dormant mode" it sounds like a static solution would be the best for you.

If you require the continual functional use of the site you could consider moving the site to a managed solution. Managed hosting providers can take care of the web and database server, but for further management of the Drupal code you could consider a service like http://drupalgardens.com.


Access field value in template_preprocess_views_view_field function?

It depends how you have your view set up.

If you have your view using the format 'Fields' then you can override the content with template_preprocess_views_view_field() like you say, like this (although you might want to target individual fields with some if statements):

/**
 * Implements hook_preprocess_HOOK() for views-view-field.html.twig.
 */
function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      // Replace characters in the field output.
      $variables['output'] = Drupal\Core\Render\Markup::create(str_replace('find', 'replace', $variables['output']));
    }
  }
}

If you are using the format 'Content' then you could do it at the field template level or node template level instead, since in that case it doesn't use the views field templates.


How to display users associated with a node through Views

It seems to me that since your node reference field is on your user object and you want to list users, all you have to do is:

create a view listing Users
add a contextual filter corresponding to your entity reference field. The entity reference field on the User should appear in the contextual filters list. Choose that one.
Choose where the contextual filter value is coming from. If your view will be at myview/nid, where nid is the node id you want to use to filter, then you don't need to choose any other behavior. If you'll be displaying this view on a node page, use the default->content id from URL option.
Choose your user name fields without relationships. There is no relationship needed unless you need to bring in fields from the node being referenced.


I believe Display Suite module will do the trick.


Load Javascript when a particular form is loaded

Loading which page causes the error? The enabled modules are loaded on every page request, because your module is enabled so it is loaded on pages, it tries to get an element that is not built yet!

Look at hook_init documentation. it says:

  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.
  When this hook is called, the theme and all modules are already loaded
  in memory.This hook is not run on cached pages.To add CSS or JS that
  should be present on all pages, modules should not implement this
  hook, but declare these files in their .info file.

So you shouldn't load the js files in there.

$(document).ready does not wait for images or scripts, try $(document).load


Programatically create 'Send this user a a private message link' for user pages

Hope this will help you,

In Drupal 7, you can use privatemsg_get_link.

privatemsg_get_link - Returns a link to send message form for a specific users.

  if ($enabled_private_messages) {//check user private message settings
    if ($account = menu_get_object('user')) {// Get user object. You can also use user_load to get user object.
      if (is_object($account) && privatemsg_user_access('write privatemsg')) {
        if ($url = privatemsg_get_link(array($account))) {
          return l(t('contact user'), $url, array('query' => drupal_get_destination()));
        }
      }
    }
  }


How do I resolve a unresolved dependency error after using Composer to install modules?

So, the system couldn't decide what version of the modules were installed. Here is a fix:

https://www.drupal.org/project/modifiers/issues/3052416

Basically, install Git Deploy module to add versioning details to modules .info files.


How to display only the years that have content in view filter?

If you go to views page (/admin/structure/views), you will find a view "Archive", you can clone it and use it, it will be displaying content month+year using contextual filter "Content: Created year + month", as you want to display only year, use contextual filter ""Content: Created year" and remove "Content: Created year + month".

Screenshot for contextual filter.

Screenshot of output.

It will list all the years that have content added.

Update

What you can do is to create a block of the view, and place it on the page you want, and then when you will click on an year, you can have the content list accordingly on the same page.


How do I create inline border style in views table for views data export word output?

I have created views template and saved in theme folder. then used styles in template itself like below:

      <th style="border:1px solid #000000; border-collapse:collapse; padding:5px; min-width:80px" <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
        <?php print $label; ?>

Useful link: http://www.wdtutorials.com/drupal-7/drupal-7-how-to-create-custom-template-view#.VWsGAlJp0-Y


This sounds like something you can handle pretty easily with a couple of contrib modules:

If you don't already have them install Views and Entity Reference.
Add a View of type "Content", filtered by content type B. Call it something like "All type B content".
Add an "Entity Reference" display to the new View.
Add any sorting/filtering options and change the display field if required.
Repeat steps 2-4 for a new view called "All type A content", and filter by content type A instead.
Add a new field to content type A of type "Entity Reference".
On the field settings page under "Entity Selection" choose Views: filter by an entity reference view for the mode, choose the "All type B content" View, and save the rest of the field config as normal.
Repeat steps 6-8 for content type B, choosing the "All type A content" View instead.

That should get you exactly what you're looking for, with the added benefit of being able to customise the results easily with Views.


How to create an Enquiry form with ability to submit a collection of enquiries

Switch to Entityform. This uses the core field APIs. Add an entity reference field on your products and services types. Details from the project page:

The Entityform module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)
As with everything in Drupal, there are Pros and Cons to using Entityform. All though Entityform is a powerful tool, it is not always the best solution. The article When to Use Entityform discusses the advantages and disadvantages that Entityform may have over other methods of creating user "submittable" forms. Do not use Entityform for forms that will contain 150+ form elements

Entity form works well with other modules like Rules so you can get really custom with your behaviours.


Avoid duplicate hits in two separate Views

This is not trivial to accomplish, and will in most cases require coding.

First of all, it's necessary to determine in which order the lists should be evaluated. One of them needs to take priority. The gist of the solution, is that in some way, you need to feed the hits from the first list, as arguments to the second list.

In Views, you can add a Contextual filter, or Argument, depending on your version. These arguments can be set to "exclude" their matches, and it's also possible to allow "multiple arguments per filter".

The high priority View can be left as it is, but the low priority View should be configured so that it takes several entity-id's as arguments, and excludes those from the result. The real difficulty for most is going to be in passing arguments between these two Views.

In code:

$first = views_get_view('most_important_view');
$second = views_get_view('less_important_view');

// Get results, but don't render them.
$first->preview('machine_name_of_display');

// Append together a list of node id's to a string.
$nodes_to_exclude = '';
foreach($view->result as $node) {
  $nodes_to_exclude .= $node->nid . '+';
}
// Remove the trailing +.
$nodes_to_exclude = rtrim($nodes_to_exclude, '+');

$second->execute_display('machine_name_of_display', array($nodes_to_exclude)););
return $second->render();

If you are not comfortable using the above code, there is a module called Viewfield that allows you to call a second View from a primary View. But unfortunately I'm not aware of a way to configure this to pass several arguments on, but just a single one, so I'm not sure if that's helpful.


I was wondering how to make "custom fields" in Drupal 7?

No custom module is needed for this in Drupal 7.

Go to Admin > Structure > Content Types, click on "Manage Fields" by the content type you want to add the field to (e.g. admin/structure/types/manage/page/fields), select a type (e.g. "Text"), give it a name, and you're done. (There are some field settings you can change, but you don't need to.)

If you want something that does validation on the URLs, I'd recommend installing the link module, then choosing "Link" as the field widget type in the instructions above.


Features - Should I go for big or numerous?

It's all up to you. There are pros and cons to both and it depends on your use case.

Generally one would tend toward decoupled functionality with granular features instead of a giant feature. Especially if you wanted to potentially use these features on other sites.

Some information to help you out.

One big feature Pros:

It's quick and easy. If you're just using features to track database changes in code and
don't care about re usability, you can just stick everything in one
big feature.

One big feature Cons:

If you make one big feature, you can't re use it at all on another
site unless that site is almost exactly the same.

Decoupled features Pros:

You can re use features on other sites.
Your features are much more manageable, even it if it takes a bit
longer.
You can keep custom code which is directly related to the feature in
the features module, so you're keeping the feature + custom code in
one nice package.
This model fits in well with programming in general, taking big
problems, breaking them down, abstracting them, using dependencies,
etc. It will definitely improve your programming practising
separating your code logically like this.
Helps the way you think about Drupal components and how they mess
together.

Decoupled features Cons:

Overhead of organizing features structure. This will get easier as
time goes on and you get better.
Can be very hard to decide where to decouple, especially for newbies.


Edit your Workflow again (after you created the states) and scroll down to the bottom to 'Access control' section. In there you can set permissions for each state.

You can also look at the Workflow Fields module if you want to set access to individual CCK fields.


Caching - techniques? suggestions? best practices?

In general, I'd recommend using boost if you don't have access to the command line of a server.  Boost creates a static HTML copy of the file inside a cache directory within your Drupal file structure.  It updates cached pages only when content changes.  It is used in conjuntion with the performance enhancement features of Drupal such as CSS and JQuery compression found under /admin/settings/performance.

If you have command line access I'd reccomend APC and memcache/memcached.  This takes a little more effort to set up, but is well worth it IMO.  There are plenty or resources on Drupal.org to help you to set up memcached.

You can also set basic caching on individual views as shown here:

 You'll see the option for caching 7th from the bottom.  There is also a similar option in panels if you use them.

These caching options are designed for end-users really, not specifically logged in users.  Indeed you may want caching disabled for logged in users if they are administrators and/or are making changes to the site.


The main error is that, since your module's short name is beneficiaire, those are the implementations of hook_user_pass_validate() and hook_user_pass_submit(), which aren't hook Drupal utilizes. If you rename the functions beneficiaire_validate() and beneficiaire_submit(), those would not be hooks which are used as validation and submission handlers for the password change form.
See @Clive's answer for how adding form validation and submission handlers, keeping in mind that the validation handler is added with $form['#validate'][] = 'beneficiaire_user_pass_validate';.

As side notes:

If you want to check a validation handler is called, use form_set_error("", "beneficiaire_user_pass_validate() called");
To redirect the user after submitting a form, set $form_state['redirect'] as in $form_state['redirect'] = 'login';


Replace BUNDLE_MACHINE_NAME with your bundle machine name.

Drupal::entityTypeManager()->getStorage("node_type")->load("BUNDLE_MACHINE_NAME")->uuid();

Or you can also load it like this:

Drupal\node\Entity\NodeType::load("BUNDLE_MACHINE_NAME")->uuid();

Entities based on EntityInterface will have the uuid() method.

See EntityInterface::uuid


How do I add a private file to node's file field from Base64 in code

my final solution was next:

$node = Node::load($data['case_id']);
$files = $node->field_case_file;
$dfSettings = $files->getDataDefinition()->getSettings();
$destination = $dfSettings['uri_scheme'].'://'.$dfSettings['file_directory'].'/'.$filename;
$destination = \Drupal::token()->replace($destination);
$file = file_save_data(base64_decode($fileData), $destination, FILE_EXISTS_RENAME);

$violations = $files->appendItem($file)->validate();

if(count($violations)) {
//throw error
}

$node->save();


You can add as many field you like to the user object using Fields. Just tell your field to be visible on the main user panel.

Once this is working, implement hook_cron and send your mails using drupal_mail().


How do I extract filename and filepath from a file field?

I found a solution to this, however stackexchange won't let me add an answer for 8 hours. I have it all typed out so if I forget to come back and upload it feel free to post on here to request the answer and remind me.

go on...


How can I render a specific node as the content for the maintenance page?

Use the Twig tweak module and create an overwrite template for maintenance-page.html.twig. Then copy & paste stuff from your base theme, but replace {{ page.content }} from the base theme with {{ drupal_entity('node', X) }}
E.g. for stable 9 theme this would look like

  {% if logo %}

  {% endif %}

  {% if site_name or site_slogan %}
    {% if site_name %}

        {{ site_name }}

    {% endif %}

    {% if site_slogan %}

{{ site_slogan }}

    {% endif %}
  {% endif %}

  {% if title %}

{{ title }}

  {% endif %}

  {{ page.highlighted }}

  {# disabled {page.content} here #}
  {{ drupal_entity('node', X) }}

{% if page.sidebar_first %}

    {{ page.sidebar_first }}

{% endif %}

{% if page.sidebar_second %}

    {{ page.sidebar_second }}

{% endif %}

{% if page.footer %}

    {{ page.footer }}

{% endif %}


Passing PHP variables to JS file initiated from theme .info file

You don't access the Javascript file in PHP, rather, you tell Drupal to send values to Javascript variables and then access those from your Javascript files. You would use drupal_add_js.

For example, in template.php add:

drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

Then in your Javascript file, you can access that variable as:

Drupal.settings.myModule.key


When you create an entity node a value type for the content type is required. If your form doesn't provide one, you can add it to the values before creating the node:

  $values = $form_state->getValues();
  $values[] = ['type' => 'article'];
  $node = \Drupal\node\Entity\Node::create($values);


How can I get a GMap Marker field to be a target in my Feeds importer?

Mapping targets for fields are not automatically available. For each field, a Feeds target must be written. Feeds targets for fields provided by Drupal core should be provided by Feeds itself, but Feeds targets for fields provided by a contrib module, should be provided by that contrib module.

You can do the following:

Open an issue in the GMap issue queue and request a mapper for the GMap Marker field.
Implement the Feeds target yourself. For documentation, see https://www.drupal.org/docs/7/modules/feeds/the-developers-guide-to-feeds/the-developers-guide-to-feeds#mappingapi. While the process explained there still works, the documentation is slightly outdated. The recommended way of adding a target now is to use the hook hook_feeds_processor_targets() instead of hook_feeds_processor_targets_alter(). Also in the target callback, the language of the target can be found in $mapping['language']. See feeds.api.php for more information.


How to create a list of users according their roles?

Create a View Page of users with exposed filter as role.


Creating an API via module routing files that includes csrf verification headers

The requirement _csrf_request_header_token: "TRUE" works only if user is connected because CsrfRequestHeaderAccessCheck use session informations.
If you look at CsrfRequestHeaderAccessCheck in the access method there is:
 if ($account
      ->isAuthenticated() && $this->sessionConfiguration
      ->hasSession($request)) {

To check if the user is connected and it there is a session identifier in the request if it's not it will go directly to:
// Let other access checkers decide if the request is legit.
    return AccessResult::allowed()->setCacheMaxAge(0);

so it will not check if X-CSRF-Token is in the headers or not even if you set the route requirement _csrf_request_header_token: "TRUE".
Code
MODULE.routing.yml
MODULE.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\MODULE\Controller\UserAPIController::login'
  methods: 'POST'
  requirements:
    _csrf_request_header_token: 'TRUE'

UserAPIController.php
class UserAPIController extends ControllerBase {

  public function login(Request $request) {
    $response['data'] = 'Some test data to return';
    $response['method'] = 'POST';

    return new JsonResponse( $response );
  }

}

Test

With Connected user

with anonymous user


Using Drupal as a server application user front-end (feasability question)

Absolutely.

Do not be put off by the 'CMS' label, Drupal is actually quite a framework in itself.  Drupal really does a good job for small to mid-sized applications, as the application gets larger though one has to tweak and push the limit a bit more. To be fair, this is true of most any PHP application.

I have built quite a few applications myself that leverage the power of Drupal, some internal, some public: production management, calendaring applications, rental/item reservation for 4000 items +, mailing list management, (and more).

In my (very humble) opinion, Drupal saves a lot of time, especially for the 'user-management' aspect of application building. As a bonus, you have the rest of the framework to play with when developping your app.

Hope that helps, happy coding, good-luck!


It's quite simple, if you want to change a content type default setting, just change it in :

  Administration » Structure » Content types » Edit a content type

Everything you change in the "global" content type settings will be default when you add a new node of this content type.

In the case of a Basic page, it will be this page (admin/structure/types/manage/page) :


How do I use "IGNORE" in a database query?

What you want is a MERGE query with no UPDATE part. Something like this should work:

db_merge('the_table')
  ->key(array(
      'nid' => 8,
      'language' => Chinese,
  ))
  ->insertFields(array(
    'nid' => 8,
    'language' => Chinese,
  ));
  ->execute();


Hierarchical Select Doesn't allow multiple vocabularies in drupal7

You can't I'm afraid; it's actually a limitation of the taxonomy term field type, not of Hierarchical Select.

You can only ever choose one vocabulary per term reference field, regardless of the widget you're using. For example, this is what the field settings page looks like when adding a bog standard term ref field on a Drupal install that doesn't even have HS installed:

As you can see you only have the option to choose one vocabulary.


How can I check for a duplicate node when rendering a view?

If I'm not mistaken, in your view-settings, you can select a distinct query in your Advanced settings in the view. It set under Query settings. I'm not sure if it's already there in D6.


How to edit files without changing the last modified date?

Consider this PHP code:

touch('/path/to/file', strtotime('-1 month'));

That will change a file's modified date to one month ago.

It's pretty easy to mess with the modified date of a file if you've got access to the server, which your hackers obviously have (at least to some degree).


Configure Videojs to use the local library

The README.md included with the downloaded module says:

  Download the Video.js library from http://videojs.com. Extract the module to sites/all/libraries/video-js and make sure that sites/all/libraries/video-js/video.js exists. NOTE: you can skip this step and use the Video.js version from the Video.js Content Delivery Network (CDN).

A comment in the documentation block in the module file suggests that the Libraries API determines where to places libraries.

  Defaults to videojs_directory when using the local file path location
  or whatever location the Libraries API determines.

This location is also set by the videojs_directory configuration variable, which could be set by importing a YAML file via Configuration Management interface or with a tool such as Drush or Drupal Console despite the Video.JS module not having a specific configuration page.


Get Relationship for the Author of the Latest Comment

I'm going to assume here that field_last_name is a field you added yourself to the account fields. I tested using just the user name, and got it to work fine using the following relationships (starting from a Node):

From the node to all comments: was called "Comments of the node using field: comment" here
And then from the comment to the author: just called "Author" here in the Comment category

Then I added the "Name" field (User category), and Bob was my proverbial uncle.


How add a views page url to the admin_menu?

The link needs to get added to the Management menu to show up in admin_menu.

You can add a admin menu link on:
http://example.com/admin/structure/menu/manage/management

Or through the interface at : Structure->Menus->Management->Add Links


How can we apply filter in view for a content type by start date-time and end date-time?

Try the Scheduler module, then just create a view with published exams.

This module allows nodes to be published and unpublished on specified dates.
Dates can be entered either as plain text or with calendar popups. To use calendar popups you need to install the Date Popup module, which is part of the Date module.


Find the password for user admin from a replicated old version of site

Short answer: it can't be done.

The password is a salted hash, and unless you have access to specialist cracking equipment, you're not likely to reverse engineer that hash in yours, or even your great, great, great, great grandkids' lifetimes. Even with access to the original salt.

As Pierre mentioned in the comments, submitting a password reset link on the live site is probably the simplest course of action.

Or contact your hosting provider; most will find you a way back into a server you're locked out for a nominal fee, once they've verified your ownership.

Bottom line, you're not likely to recover the password from the hash in the database, so you'll need come up with a creative workaround.


Displaying view as row-based table, not as grid

You can probably achieve this with CSS, rather than modifying the PHP - or are you saying you want to output as an actual HTML table?  Views should do that for you.


How to list nodes with at least one field empty?

Use Views module.

Create a view, then add a filters  Content: field_name (empty) - one for each field. Change operator from AND to OR and done, you have a list of nodes with at least one field empty.


This isn't exactly a Drupal question but if you add the following to your CSS this will accomplish I think what you want.

div.qtip {
  top: 170px !important;
  left: 370px !important;
}

Adjust the values to suite your needs.

Edit: You may want to qualify that block of CSS further by prepending with it's wrapper or something, just to give it context and not break these qtip menus in other places


Add a calculated column programmatically using views data export

I am going to go ahead and answer my own post to help anyone else out.
A simple way to do this for me was to write a views plugin as suggested in the comments.
Here is a great link to walk you through this: https://www.webomelette.com/creating-custom-views-field-drupal-8
I do not feel I can write any explanation better than what is done in this article so I would jump over there for more information.


How add javascrip file to a node? (module)

You can add your js through drupal_add_js() function. You can control on which pages this js should be added by implementing different hook and calling drupal_add_js() function in those hooks:

1) Use drupal_add_js() in hook_init() if you want to add this js on all drupal pages.

function mymoduel_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js');
}

2) Use drupal_add_js() in hook_node_view() with content type condition check if you want to add this js on only specific content types.

function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'my_content_type') {
    $node->content['#attached']['js'][] = array (
      'type' => 'file',
      'data' => drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    );
  }
}

3) Use drupal_add_js() in module's preprocess function if you want to add this js only on specific node

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 'your node nid') {
    // Add js
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.awesome.js');
  }
}

You can implement this preprocess_page at theme level like mytheme_preprocess_page($variable) in theme's template.php file.


How to replace teaser/content for anonymous users

You can separate teaser from body as a new field, and use module "Field permissions" or similar modules.You can control access for that field.

Another way is custom module which use hook_node_view or hook_node_grants_alter to control if user can access node.


Set the front page in Admin > Config > Site Information. “Promoted to frontoage” is not what you think it means in this context.


EVA field: file entities filtered by taxonomy term of attaching node

I have a similar case of two Content types that share the same Taxonomy vocabulary referenced, and the need to show all nodes of Content type B that are tagged with a certain term to show on the node type A that is also tagged with the same term.

I created EVA views display that lists nodes of type B, under Bundles chose Content type A, under Arguments chose token (Use tokens from the entity the view is attached to) and chose

[node:field-myvocabulary:tid]

for token replacement (I selected it from the list below the textfield).

Then under Contextual filters I added

Content: Has taxonomy term ID

and set it up like this:

When the filter value is NOT available

Provide default value Taxonomy term ID from URL
Load default filter from term page
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary (myvocabulary)
Filter to items that share any term

When the filter value IS available or a default is provided

Specify validation criteria
Taxonomy term:
(myvocabulary)
Filter value type:
Term ID
Transform dashes in URL to spaces in term name filter values
Action to take if filter value does not validate:
Display "Access denied" (this hasn't been triggered for me)


Problems linking Image to product display node

This problem is solved by changing the Content: Path rewrite options to using absolute path.


Please check this out. It is a workaround for converting the currency on checkout https://www.drupal.org/node/789284


How can I pass a value from block to page in a view?

I think this question may have some similarities to How to pass a value from form(block) to the page and show this page?

The trouble with what you are asking is trying to have two distinct parts of your page act on one interaction: the block form submit and then the page search view filter form submit. Each is in fact a separate function which have no relationship in the Drupal backend. To get this to work you could use some jQuery magic to get the value selected in Block filter be cloned into the page search and do a submit on the form. You may have to do some coding using cookies or session values to ensure the values are also reloaded into the block filter criteria if you wish to keep those synchronized.

Since you have several ways of going about this, stick to one that is easiest to work with at first. jQuery is often the most convenient though maybe less elegant in some cases.


flysystem error message. Driver is missing

Requirements
If you look at the flysystem.install file (it's currently the same whether you installed 2.0.x or 8.x-1.x), you can see the code used for flysystem_requirements().
The general structure of the checking is as follows:

Validate the schemes in settings.php
Make sure the dependencies are installed:
a) League\Flysystem\Filesystem
b) League\Flysystem\Replicate\ReplicateAdapter
c) Twistor\FlysystemStreamWrapper
Then, it calls ensure() on the plugin for each scheme, and makes sure the plugin can be instantiated.

This 3rd step calls this code (src/FlysystemFactory.php):
  public function getPlugin($scheme) {
    if (!isset($this->plugins[$scheme])) {
      $settings = $this->getSettings($scheme);

      $this->plugins[$scheme] = $this->pluginManager->createInstance($settings['driver'], $settings['config']);
    }

    return $this->plugins[$scheme];
  }

It also provides the defaults:
  protected $defaults = [
    'driver' => '',
    'config' => [],
    'replicate' => FALSE,
    'cache' => FALSE,
    'name' => '',
    'description' => '',
  ];

Given the above information, your plugin and schema should have declared your driver with 'driver' => 'ftp'.
Solution?
Also, on the main module page under "supported adapters", it says:

Ftp (Requires the ftp extension)

Though I'm not sure, since it doesn't link to another module like the other adapters, I think it means the PHP extension. Try installing the ftp PHP extension. Here's the page for setup instructions.


What happens if a user uploads an image but doesn't save the node?

The image files will be removed during cron runs.

This happens because the status column in file_managed for those files will still be zero, indicating that they're temporary, and can be safely removed after a period of time.

The responsible code is in system_cron(), in case you need to reproduce/analyse further.


Override front page to not display promoted article

You can simply remove nodes attached to the front page in the preprocess.

/**
 * Implements template_preprocess_page()
 */
function THEME_preprocess_page(&$vars) {
  // Remove 'Promoted to front page' nodes
  if ($vars['is_front']) {
    unset($vars['page']['content']['system_main']['nodes']);
  }
}


Customizing main_menu so that it shows nested elements with styling in Drupal 7

As far as I know, it's not possible to make theme('links__system_main_menu' [...]) display the nested elements. That suprised me, too...

One way to fix this: set up a region in the theme for the menu and put a menu block in there. This will display the nested elements, however styling the menu itself won't be much easier than before. theme_menu_tree() and theme_menu_link() hooks could be useful.

Also, check out the Menu block module.

p.s. I'm currently doing something similar that you do and it seems to be quite complicated for me, too, so I just summarized what I've already found.


How to add content in custom menu block?

It's in the Content Type's settings screen under "Menu settings", you have to tick the Footer Menu to make it available for selection.


Found it finally:

Url::fromUri($node->field_image->uri)->setAbsolute(TRUE)->toString()


Setting author when creating a new node via Cron

You have two options.

Either set the uid after the node_object_prepare call and before node_save, or you can set $node->name to the username of the user that should be the author.

The reason is that node_submit will set the uid of the node based on the value of $node->name if set and node_object_prepare will always set author to the current user.


Views exposed filter hide if less then 10 items

Add this to your theme's template.php file:

function THEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYID' && $view->total_rows <= 10) {
    $view->exposed_widgets = '';
  }
}

This will remove all of the exposed filters. If you have more than one and you only want to remove a single exposed filter, you will have to parse that filter out of the $view->exposed_widgets html string.


It should be pretty simple by creating a content type "events", with the date fields using the Date module http://drupal.org/project/date. Then adding in the signup module for users to RSVP http://drupal.org/project/signup. You can also add in the calendar module for some displays http://drupal.org/project/calendar or the full calendar module http://drupal.org/project/fullcalendar


saadlulu is right - this is a notice (not an error) provided by the core node module and relates to the preview functionality you have enabled. Are you trying to disable preview?

If you just want to disable the message, try the 'disable messages' module and make sure to heed the advice here and use the following wildcard:

The trimmed version of your post shows what your post looks like when promoted to the main page.*


How to disable aggregation from either drush or PHPmyadmin?

Drupal 8 version to disable aggregation:

disable CSS/JS aggregation

drush -y config-set system.performance css.preprocess 0
drush -y config-set system.performance js.preprocess 0


Option 1 - Ask for a password reset link

If eMail is working in your site, ask for a password reset link. Use that link to then reset the password.

Option 2 - Use Drush

If you have Drush available, then you can use eiher of these Drush commands:

drush upwd --password="NewPsw" "username", to reset the password for username to NewPsw.
drush uli username, to generate a 1 time login link for username.

Option 3 - Copy an encrypted password that you know

Just copy the encrypted password from the same user table from any other user for which you know the password. Then paste that encrypted password in the record for your admin user. You should then be able to use that password for login with your admin user.

If you don't have another user yet (or don't know any of their passwords), then use standard Drupal facilities to create a new user first (and remember the new user's password).

If you don't have any user that is allowed to create new users (or you can't login with such new user), then (temporarily) create a new Drupal site and use the user/1 password of that new site.

Option 4 - Create a new admin user

Insert a new user in the "user" table (with an encrypted password for which you know the password). And make that new user an administrator also by inserting an appropriate row in the "user_roles" table (cloned from the row related to the user/1).

Then use the newly created user to perform a reset of the password for the admin user.


Using a computed field: How to extract a field value from a referenced node into field collection. (Multiple value)

You can do something like this:

$referenced_titles = array();

foreach ($item2 as $indice => $values) {

  // use node_load($nid) to load the node.
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
  $referenced_titles[] = $referenced_node->title;

}


How to add a menu tab to a user profile?

You should implement hook_menu_alter() instead of hook_menu.

function add_menu_tab_menu_alter(&$items) {
  $items['user/dashboard']['type'] = MENU_LOCAL_TASK;
}

Then you should clear the cache, at least the menu cache, as Mołot suggested.

There is also another approach using hook_menu_local_tasks_alter(). But the first method is better since it is called only once, after the hook_menu and saved in the database, while the latter is being called each time the local tasks are rendered.


I managed to clear the cache by emptying all the _cache tables in the database. I then navigated to the theme (Corolla) settings page and clicked on save settings.

And gone. All errors now seem gone.

Thank you very much Patrick K, I wish I could vote your suggestion up! (Will do if you repost it as an answer rather than a comment.)
Cheers!


hook_views_query_alter creating additional OR statements

Thanks to iLLin I was able to figure out an acceptable answer to this question by using the in operator, and replacing the entire array for the condition.

function customedm_views_query_alter(&$view, &$query) {
  if ($view->name == 'course_catalog') {
        foreach($query->where[1]['conditions'] as &$condition){
            if ($condition['value'] == 422){
                $newvalue = array(
                    field => 'field_data_field_course_subject.field_course_subject_tid',
                    value => array(311, 316, 326, 321),
                    operator => 'in'
                );

                $condition = $newvalue;
            }
        }
    }
}


I miss to determine the language of the menu ... I am stupid it fix by adding the language of each menu i wanna to display on specific language like this


Change Password/Confirm_Password Password Tips

so I managed to tinker enough to get something to work and I'm sharing it in case other people need it or something. Of course, I dunno if this is optimal or follows standards or shouldn't even be done in the first place but please feel free to add your input. It's in the my_module.module file, by the by. Oh and don't mind the text, was just kinda testing this out and all that jazz.

Without further ado, here's the code:

/**
 * Implements hook_form_alter().
 */
function <my_module>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === <my_custom_form_id>) {
    // Note that this isn't actually a hook
    $form['#after_build'][] = '<my_module>_confirm_password_after_build';
  }
}

function client_confirm_password_after_build($element) {
  $drupal_settings = $element['pass']['#attached']['drupalSettings']['password'];

  $drupal_settings = [
    'confirmTitle'          => t('Do the passwords match?'),
    'confirmSuccess'        => t('Yeah'),
    'confirmFailure'        => t('Nope'),
    'showStrengthIndicator' => TRUE,
    'hasWeaknesses'         => t('Password Suggestions:'),
    'tooShort'              => t('Make it at least 50 characters'),
    'addLowerCase'          => t('Add 7 lowercase letters'),
    'addUpperCase'          => t('Add 8 uppercase letters'),
    'addNumbers'            => t('Add 8 numbers'),
    'addPunctuation'        => t('Add 10 punctuations'),
    'sameAsUsername'        => t(''),
    'weak' => t('Forgettable'),
    'fair' => t('Meh'),
    'good' => t('Almost'),
    'strong' => t('You got it'),
    'username' => '',
  ];

  $element['pass']['#attached']['drupalSettings']['password'] = $drupal_settings;
  return $element;
}


Login box on one site to log you into another site too

Sure it's possible. There are many ways to do this.

A simple solution, if both sites are running the same drupal version, would be to make a custom form, and connect to the other sites database, and get the login form. You would need to make sure that the submit path would go to the project manage site.

When the form is submitted, they would automatically go the that site, and if user/pass is correct, they would also be logged in.

Disclaimer: I haven't actually tried this before, but it should work just fine. Drupal wont know where the form was submitted, so should be the same as being on their project site and using the login form.


There's almost certainly no such thing as "no individual considerations" on Drupal sites.

Even on a Drupal 7 site with no contributed or custom modules, this isn't easy to do.  You might have many content types, with all their fields and associated configuration.

Some tables you'll need to look at are node, node_type, node_revision, field_data_*, field_revision_*, maybe taxonomy_*, maybe others.

Migrate module, Feeds module, and others can help with this too, as Ayesh mentioned.


A simple solution might be to something like Rules, and Rules Link.

Create a rule that clones the data from one node into a new node. Have it actioned to happen when a certain link/button is clicked (hence, Rules Link). The last set of actions in the rule would be to set an entity reference back to the original node (or set a common taxonomy term)

Otherwise, create a small custom module that basically does the same thing. mapping fields onto each other and creating a new node. You'll have more control on what happens with the data but its not easy if you are not a developer.


Prevent form regeneration when a callback function is called through ajax

If you need a entity (which could be a node) to be created whenever the form is loaded, can create the enitiy, and pass it to your form, rather than creating it within your form. Then you can also use the same form for editing the entity.

For example, in a module called nodeform:

function nodeform_menu() {
  $menu['nodeform/add'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_add_page',
    'access arguments' => ['some_create_permission'],
  ];

  // Note: using %node will call node_load(), passing it
  // the value given in that index of the path. If no node
  // is loaded, or the user does not have access, a page
  // not found error is returned (or maybe access denied)
  $menu['nodeform/%node'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_edit_page',
    // The page argument is the 1st index of the path
    // which is %node. So the page argument will be a
    // node object.
    'page arguments' => [1],
    'access arguments' => ['some_edit_permission'],
  ];

  return $menu;
}

function nodeform_add_page() {
  global $user;

  $node = (object) array(
    'uid' => $user->uid,
    'name' => isset($user->name) ? $user->name : '',
    'title' => t('Default title'),
    'type' => 'some_node_type',
    'language' => LANGUAGE_NONE,
  );

  return [
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The edit page receives a loaded node as its argument:
function nodeform_edit_page(array $node) {
  return [
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The form then receives a node:
function nodeform_default_form($form, $form_state, $node) {
  // Get the node from the form state if it exists, or use
  // the node passed to the form if it does not.
  $node = isset($form_state['nodeform_node']) ? $form_state['nodeform_node'] : $node;
  // Save the nodeform to the node
  $form_state['nodeform_node'] = $node;

  // Add your form elements:
  $form['title'] = [
    '#title' => t('Title'),
    '#type' => 'textfield',
    '#default_value' => $node->title,
  ];

  return $form;
}

function nodeform_default_form_submit($form, $form_state) {
  $node = &$form_state['nodeform_node'];
  $node->title = $form_state['values']['title'];
  node_save($node);
}

You may not need all of the above example, but if you look at the nodeform/add menu path, it shows how you can always create a node when the form is called, and it will only happen once, rather than every time the form is built. If you don't need to use it in the form, then call node_save() on the node in node_add_page().


Creating nodes with Views Bulk Operations

This can be done using views bulk operations. But you may have to implement hook_actions_info in a custom module to create an action and the use that action in the views bulk operation.

Following code illustrates the process.

function custom_test_action_info(){
  return array(
    'custom_test_create_new_node' => array(
      'type' => 'node',
      'label' => t('Create New Page'),
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
    );
}

function custom_test_create_new_node($node, $context = array()){
  global $user;
  $page_node = new stdClass();
  $page_node->type = 'page';
  $page_node->status = 1;
  $page_node->title = $node->title;
  $page_node->field_body[LANGUAGE_NONE][0]['value'] = $node->field_body[LANGUAGE_NONE][0]['value'];
  $page_node->uid = $user->uid;
  node_save($page_node);
}

After saving this code flush the drupal cache and the views bulk operations form will have the action available.

After saving the view you will get the operation available in the views bulk operation page.

select a node and then execute the operation and you will have a new basic page created.

i am attaching an export of the view which i created you can import this view in your system and give a try to understand the workflow.

Export code of the view:

$view = new view();
$view->name = 'test_vbo_node_creation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test VBO node creation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test VBO node creation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::custom_test_create_new_node' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 1,
    'label' => 'Create a new node',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-vbo-node-creation';


Adding a date time field value within a node programmatically

[0] => Array
                            (
                                [value] => 2012-11-27 09:38:00
                                [timezone] => America/Phoenix
                                [timezone_db] => America/Phoenix
                                [date_type] => datetime
                            )

As seen above,
the error was occuring due to improper date format So when I changed the date format to  date(Y-m-d\TH:i:s, REQUEST_TIME);
the $download_node->field_download_time['und'][]['value'] did not gave any error .


This happens usually when you provide both filepath and filecontent.

Please check this answer: https://drupal.stackexchange.com/a/186157


Quicktab problem on the argument of view and block

Looks to be an issue with the quick tabs module. I have the same issue on version 7.x-3.4. It seems to break as soon as you use the % URL variables

UPDATE: After looking at the code, the module calls args(), in my case, the values returned from that are different than the URL. For example, my URL is "product/reading" however, quicktabs gets this Array ( [0] => node [1] => 180 ). So I have to change my view to use the node ID instead of the node title. This should have been noted in the modules documentation.


How do I render an image from a Twig template?

you could just use {{ content.field_image }}

Here is an example of a template file from a paragraph

{%
  set classes = [
  'paragraph',
  'paragraph--type--' ~ paragraph.bundle|clean_class,
  view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}
{% block paragraph %}

  {% block content %}

              {{ content.image }}

  {% endblock %}

{% endblock paragraph %}

Notice that I only need to write {{ content.FIELDNAME }}, if I wrap everything in a {% block content %}


access node field variables in theming view-field

You can simply check "exclude from display" for this field.


display different header text if view has taxonomy term

Instead of a Global: text area, you should embed another (new) view in the header.

This blog post explains how you can display the term description that way. That way you would have a different text for each term.


How do I use CCK fields with the form API?

I believe in this case you want to create a new content type with the appropriate cck fields to collect the location data. This will be much, much easier than trying to recreate the same experience with the forms api, custom tables and some custom module to integrate CCK fields.


Q: How to control theme colors for Drupal 7 mass contact email

After re-reading the post I mentioned several times, I found one of the comments to actually be the answer to my problem.  That post, created by dwils03, indicated:

  In case anyone was looking for a quick and dirty fix, I just included
  a blank mail.css file in my theme's folder. The result is an
  html-formatted, NON-STYLED email.

I did the same and added an empty mail.css file in my theme folder and it solved my problem.


I run into this when using Omega 4.  What I do is set my base img tag to have an auto height:

img {
  height: auto;
}


You can use 'node--webform.tpl.php' template for all webform nodes.


Views and Filter Criteria - is this normal behavour? Drupal 7

I think you should change the 2nd AND statement to OR and last OR statement to AND. Looks like everything else is fine.


Why is there a module for version 9 of core?

Well the "Bad Judgment" module you linked to claims:

  This module provides an explicit dependency for modules whose usage requires bad judgement. Joke modules often require "bad judgement".

So I wouldn't take that version number too seriously.

From the core download page you linked to:

  Placeholder for the Drupal 9.x release. Not intended for actual use by anyone except the issue queue version selector.

It's just a placeholder for the next version (forward-thinking and all that). It doesn't mean there's anything wrong with Drupal 8, and it doesn't mean Drupal 9 will be out any time soon.


In your filter settings there is an option "Limit to the selected items".
Check that and select "Development" from the select field of options and it should do what you are trying to achieve.

Then change the label of your filter as required.

See the attached image:

The view itself looks like (note I changed the filter to be cat, not car as in the previous image, because I already had content tagged with cat):


How to redirect to a edit node page with RedirectResponse?

Note that \Drupal::url() is deprecated. You should use the static methods of the Url class to create URLs from routes.

To find the route names, use the Drupal console drupal router:debug. From that I found:

 entity.node.edit_form  /node/{node}/edit

I think what you need is Url::fromRoute('entity.node.edit_form', ['node' => 1]) where 1 is the node ID to be edited.


What field is Views using to determine the pager 'offset'?

It offsets by row.

If offset = 5, it will skip the first 5 rows of your view result.

By default, the View SORT is using Post Date.

Remove Post Date and add the desired field to the SORT area. (when adding, look for your custom date field that you created.)


Why isn't this functionality in submitForm firing?

I googled the Mpdf library and it supports a string output. So you can use the string output to build a response and return it via $form_state:

use Symfony\Component\HttpFoundation\Response;

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $content = '%PDF-1.3...';
    $headers = [
      'Content-Type' => 'application/pdf',
    ];
    $response = new Response($content, 200, $headers);
    $form_state->setResponse($response);
  }


Using node author information in a module (efficiency)

It is a standard issue of efficiency versus convenience. You can, of course, simply join {node} and {users} tables on uid field and do it in simple select, taking just that one field you really need. And indeed it will be faster. But you will need to rebuild that part of the code if some day one of these tables will get renamed or restructured. That's why people are using CMS in the first place - to stop worrying about low level and get the job done simple and easy. Computers are cheaper than people these days.

It is possible that you will save a second of CPU time and 30kB of RAM. So what? Do you really expect so high traffic that it'll be a problem? Databases cache their results in RAM too, so it might be actually faster, overall, to always read whole node. It means one node set to cache instead of dozen sets with different fields selected. Or might not. It depends on to many variables to know, so it seems usual to considered adjusting these variables better than complicating code.


Is there a way for a rules execute PHP action to return a value?

I think that's not possible. More info here: http://drupal.org/node/1415628


Views change "Exclude from display" at run-time

You need to save your view with hidden fields and then load it again

<?php

function test () {
  // Loading arbitrary node
  $node = node_load(44165);

  $select_fields = array();
  foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
    $select_fields[] = $value['value'];
  }

  $name = 'MY_VIEW_NAME';
  $display = 'views_data_export_1';
  $view = views_get_view($name, TRUE);

  // Hide selected fields.
  foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
    if (in_array($key_field, $select_fields)) {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
    }
    else {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 0;
    }
  }

  // Save view.
  views_save_view($view);
  // Load updated view.
  $view = views_get_view($name, TRUE);
  $view->set_display($display);

  // Gets the exposed filters.
  $exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
  $view->set_exposed_input($exposed_filters);

  $output = $view->preview();

  $file_string = 'sites/default/files/private/' . time() . '.xls';
  file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);

  $view->destroy();
}


Service to interface with sessions table?

You can make use of Dynamic Queries
instead of Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);

You can do:

  // Create an object of type Select.
  $database = \Drupal::database();
  $query = $database->select('sessions', 's');
  // Add extra detail to this query object: a condition, fields and a range.
  $query->condition('s.uid', $uid, '=');
  $query->fields('s', ['expires_at']);
  $result = $query->execute();


Display Suite module is not displaying field labels

The page you see is from the "Default" Manage Display. Make sure you use this instead of others. The Display Suite layout is based on per content type, not per node. To change the Default display, you should go to "Structure > Content types > Your content type > Manage display" or "Strurture > Display Suite > Manage display(your content type)".

=== Update: June 25, 2015 at 8:37am - screenshot for @Kaimei Wang ===


How can I redirect a user after login to the current page?

The way to solve this can be done by adding the destination parameter to the login link.

Whenever the user is navigating a page, you update the destination based on the current page.

This can be done by implementing the hook_link_alter as the following:

/**
 * Implements hook_link_alter().
 */
function custom_link_alter(&$variables) {
  $routes = [
    'user.login',
    'user.logout',
  ];
  /* @var Drupal\Core\Url $url */
  $url = $variables['url'];

  if (!$url->isExternal() && $url->isRouted() && in_array($url->getRouteName(), $routes)) {
    // Get current path.
    $current = \Drupal::service('path.current')->getPath();
    $variables['options']['query']['destination'] = $current;
  }
}

This works fine for login and also for logout links. So when user login/logout through menu link he will be redirected to the previous page.

One problem might face you with that is cache, Drupal will start caching the destination value and won't be updated when you move between pages.

You can solve this problem by implementing hook_preprocess_menu and add destination as cache contexts.

/**
 * Implements hook_preprocess_HOOK().
 */
function custom_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'account') {
    $variables['#cache']['contexts'][] = 'url.query_args:destination';
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, \Drupal::service('path.current')->getPath());
  }

}


How to show only values matching filter in a view?

It's most important for you now to get how Views works. Views are nothing more than (really good and elaborate) query builder. Each time you set a filter, what you are really doing is adding another condition to query's WHERE line. It does not, in any way, affect anything before WHERE - especially not list of fields to obtain.

Now, you are not first one to need this. So there is Views Filter Field module, that simply allows you to display filter's value as a field. That way if you want nodes with A, don't show the terms attached to a node. Just show a filter's value of A, and you will get what you wanted: A, but not B even if node contains both A and B terms.


Render one Paragraphs Module field value inside another Paragraph field's .html.twig template

You could try a template for the paragraph itself, rather than the individual fields. If you look in the modules/paragraphs/templates you'll see the default template used to render paragraphs. Copy this into your theme and rename it to paragraph--XXXXXX--default.html.twig replacing XXXXXX with the machine name of the paragraph.

You can then access the values of your fields using {{ content.XXXX }} where XXXX is the machine name of the field, e.g. {{ content.field_list_item_link_url }}


Disable caching (for theme develoment) doesn't work

You need to follow the procedure in /sites/example.settings.local.php:

/**
 * @file
 * Local development override configuration feature.
 *
 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path, such as 'sites/example.com', copy
 * this file to 'sites/example.com/settings.local.php', and uncomment the lines
 * at the bottom of 'sites/example.com/settings.php'.
 */

This will enable the service for a null cache backend in development.services.yml, which you then can assign to cache bins of your choice by uncommenting these lines:

# $settings['cache']['bins']['render'] = 'cache.backend.null';
# $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Then you no longer need to truncate the cache tables.


How to show an Inline Entity Form on a PM page or panel?

This is a very crude, brute force answer. Basically, it's: create a PHP block that loads the user edit form with all fields except the Inline Entity Form field hidden, then display it.

Enable PHP Filter module (part of Core but disabled by default)
Create a new block with this code:

..

<?php
global $user;
module_load_include('inc', 'user', 'user.pages');
$account = user_load($user->uid);
$form = drupal_get_form('user_profile_form', $account);
print render( $form );
?>

Hide the fields except the ones you want. Two ways to do this:

The tricky, 'proper' way: in the block, hide the array elements in $form by either unsetting or setting type to hidden. There could be complications with this.
The quick and dirty but safe way: just set them to display: none; with CSS. This way the full form is present and unadulterated, but invisible.

This is fine unless you're adding a multiple values Inline Form to a user profile. If that's the case, when you try to add a new item to the multiple value field, you'll hit this error:

  Call to undefined function user_profile_form_validate()

It's because the AJAX doesn't know it's dealing with a user form and so doesn't think to load the necessary pages from the user module. The only way around that I can find is to create a custom module with the following (then flush caches etc):

function custom_module_name_init() {
    module_load_include('inc', 'user', 'user.pages');
}

This isn't ideal since it loads a page of code which is normally unnecessary everywhere - but the overheads for PHP scanning then ignoring one sheet of code are pretty small. If anyone knows a cleaner way to do this, however, please share it!


How to change or influence the block id and class of a view block

The HTML ID is generated by concatenating block-view_name-block_name and
it seems there's a length limit of 32 characters. My block exceeded that limit.
So for me the solution was to shorten the block-machine-name.


Show content that is tagged to both current node and translation source

The problem isn't getting both the source and translation nodes into Views results, that's easily done.

The problem is when you apply the Contextual filter. Because the plain Entity reference field Contextual filter isn't translation aware.

But you can make it aware of translations with the help of the Relationship Content translation: Translations.

I don't know if your filter for Media to be in English will cause any trouble, so try to remove it if you see any problems.

Also as far as I can see you don't need the Entity Reference: Application Ref Relationship, you're not using it in any of the Fields and unless you need it for something not visible here you can safely remove it.

List nodes referencing a node, along with nodes referencing its translations

Here are the steps you need to do on your Views to make it Contextually sensitive to not only the referenced entity, but also to that entity's translations:

You already have Training materials views showing some fields.

Don't include any language filters, unless you plan on allowing all the languages which defeats the filter's purpose anyway.
Add the Content translation: Translations Relationship and configure it:
Don't Require it (although I haven't noticed any difference)
Translation option: All
Add the Content: Application Ref Contextual filter and configure it:
Use the Translation Relationship!
When the filter value is NOT in the URL
[whatever you like, All results or Default Content ID from URL]
When the filter value IS in the URL or a default is provided
Specify validation criteria
Content
Application
Node ID

Now if you enter an Application node ID of any language, you will see all Training nodes referencing it AND all Training nodes referencing translations of the Application node.


You have 2 options:

Go to /admin/structure/types/manage/webform/fields and add a field. Then all your new webforms will use the new field.
Install the Webform Share module, create a webform as usual, create your field, click the Export tab, go to /admin/structure/types/manage/webform and paste your configuration in the Publishing options > Webform default components box.

If all you need is one simple field, I recommend the former option.


How do I construct the JSON data with session info for creating node?

{
   "title": "Just another drupal Post",
   "type": "Article"
}

notice no comma after the type:article tag so that your json works.


I think usage of profile2 module works only with 1 -1 relationship with user to each profile type. Node or custom entity might work better for your use case. Field collection is one way of creating such entity. This article (Creating your own entities) might help, if you replace task -> role_licence and task_type -> role_licence_template.


Menu that conditionally shows webform, or edit previous submission

You can do it using hook_node_view and redirect functionality to redirect if webform is submitted. Your menu link always point to webform page.

function YOURMODULENAME_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($node->type == 'webform' && $view_mode == 'full' && arg(0) == 'node') {
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid));
    $submission_count = webform_get_submission_count($node->nid, $user->uid);
    if ($submission_count >= 1) {
      // Get first submission
      $submission = reset($submissions);
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid . '/edit');
    }
  }
}


There is Profile 2 module

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)

Also check this wonderful answer by kiamlaluno


How to set webform to show previous submissions to users?

Be sure to confirm "Access own webform submissions" and "Edit own webform submissions" permission for the roles in question.


Adding a field with an automatic link in a content type from entity registration module

Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

  Provides a field type that can reference arbitrary entities

If that's not what you're looking for, then consider editing your question to rephrase it somehow or to add more details to it.


Display Suite: Edit tab missing on user profile

Further answers are welcome, however, I eventually found an easy solution to this issue. Because Display Suite supports tokens, I was able to create a custom field that outputted an edit button. Here's an example of the html I used: CUSTOM ICON.

In order to hide this icon from unauthenticated users, I enabled field permissions which is available when the Display Suite Extras module is enabled. Once enabled, you can adjust what fields are displayed for each user role in the permissions menu. Hopefully this is helpful to anyone experiencing a similar issue.


Help with contextual filter and entity reference fields

Apparently I had the following selected under the "more" tab in the contextual filter:

Exclude If selected, the numbers entered for the filter will be excluded rather than limiting the view.

Which lead to all kinds of odd behaviour...

If it is of use to anyone else, the correct answer appears to be:

Content using field_related_pages with the relationship required.
The contextual filter set to Content: ID with  with the ```default value set to Content ID from URL`` and
Relationship dropdown set to the field_related_pages


How to determine the code for settings.php config override based on .yml?

The first key is the name of the config object/file, so... commerce_payment.comerce_payment_gateway.stripe_test.

The rest you already figured out, it's an array that's recursively merged into the other one.


You can still use hook_form_alter and have a special variable (in the $_SESSION for example) to define which part of the form do you need to show. Code sample below:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
  if ($form_id === 'user_register_form') {
     switch ($_SESSION['register_step']) {
         case 1:
              // confirm smth
         break;
         case 2:
              // establish the connections to other services, etc.
         break;
         default:
              // show initial form
         break;
     }
  }
}

Hope this is helpful.

EDIT

Some links:

Creating a user programmatically
Custom submit
handlers


The image links are the problem here, I think. The images are shown on the front page but aren't shown on other pages. So, on the front page it understands the image link (by adding the http://localhost/ in front of the image link you gave) but on the other pages, for example on http://localhost/node/3 it tries to show an image from http://localhost/node/3/sites/all/themes/custom/themename/images/facebook_top.png but there is no image on this address.

Therefore, use the full link (http://localhost/sites/all/themes/custom/themename/images/facebook_top.png etc).


You'll need a custom Stream Wrapper, which provides read/write operations to your remote file system (those docs are for Drupal 7, but the concept, if not implementation, is identical).

Fortunately, for Drupal 8 someone's written a stream_wrapper_example module, which contains a lot of boilerplate code for re-use.

There are also a bunch of existing community-supplied stream wrapper modules, a Google search like "drupal stream wrapper modules" will list them all for you. Obviously whether or you can re-use any of those depends on exactly what you mean by "remote", and how you're implementing the connection.