You can do it like this:

/**
 * Theme menu links.
 */
function THEME_NAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  // This is the part that removes or changes the last class.
  if (!empty($element['#attributes']['class'])) {
    foreach ($element['#attributes']['class'] as $key => $class) {
      if ($class == 'last') {
        // Use only one of the two following lines.

        // To change the last class.
        $element['#attributes']['class'][$key] = 'new-last-class';
        // To remove the last class.
        unset($element['#attributes']['class'][$key]);
      }
    }
  }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

However, if you are referring to the primary links and secondary links as printed out by default in most themes, they do not run through that function, because they are generated by menu_main_menu() and menu_secondary_menu(), which in turn use theme_links() to generate the links instead of theme_menu_link() - very annoying.

So to get to those you either need to stop using theme default theme menus and use the menu blocks provided by default by the menu module. These blocks use the theme_menu_link() function to generate links so will be affected by the above code.

Alternatively, you would have to override theme_links() also, like so:

/**
 * Theme links.
 */
function THEME_NAME_links($variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    $output = '';

    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading['level'];
      if (!empty($heading['class'])) {
        $output .= drupal_attributes(array('class' => $heading['class']));
      }
      $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class[] = 'first';
      }
      if ($i == $num_links) {
        // *** Use this line to change the last class. ***
        // *** Or comment it out to have no last class. ***
        $class[] = 'new-last-class';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
           && (empty($link['language']) || $link['language']->language == $language_url->language)) {
        $class[] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link['title'], $link['href'], $link);
      }
      elseif (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '' . $link['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

I have added * to the start and end of comments for the line you need to be interested in.
The problem with this approach (maybe it isn't a problem for your site) is that this affects a lot of other lists of links on the site, not just the two menus in question.

It is possible to use
    if ($attributes['id'] == 'main-menu-links')
and
    if ($attributes['id'] == 'secondary-menu-links')

to distinguish between the main menus however that isn't foolproof and isn't the best idea.

For example, the important part of the above theme_links() would be:

if ($i == $num_links) {
  // This would skip the last class for main & secondary menus
  // but would keep it for other links lists.
  if ($attributes['id'] != 'main-menu-links' && $attributes['id'] != 'secondary-menu-links') {
    $class[] = 'last';
  }
}


How to set the default format in text_format and hide the select?

The module suggested (in comments above) seems interesting, but if you want to do it with code only for body field and you don't want to use the module,
you can use hook_field_widget_form_alter instead of hook_form_alter.

Try this:

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_NAME_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['items']->getFieldDefinition();

  // Base fields are not configurable.
  if (!$field_definition instanceof FieldConfig) {
    return;
  }

  if ($field_definition->getName() === 'body'){
    // Set only full_html as allowed format.
    $element['#allowed_formats'] = ['full_html'];
    // Add after build to remove the help wrapper and text.
    $element['#after_build'][] = 'MODULE_NAME_after_build';
  }
}

/**
 * @param array $element
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *
 * @return array
 */
function MODULE_NAME_after_build(array $element, FormStateInterface $form_state) {
  // Remove Guidelines and Help text.
  unset($element['format']['help']);
  unset($element['format']['guidelines']);
  unset($element['format']['#type']);
  unset($element['format']['#theme_wrappers']);
  return $element;
}


AJAX calls fail when the base URL is set

Make sure you didn't already include a base URL in your ajax link. For my development site, http://localhost/project1/ajaxlink, the following will work perfectly when no base URL has been set.

$.ajax({url: 'project1/ajaxlink', ...

In case a base URL has been set, the AJAX call is equivalent to the following, which will not work.

$.ajax({url: 'project1/project1/ajaxlink', ...


Breadcrumb is made up of an array. So to add any element in the breadcrumb you have to give the offset.

So if you want to set t('Du er her') in place of the front page link then you should try this:

$breadcrumb[0] = l(t('Du er her'), 'front');

To know the exact position of element which do you want to add, you can use var_dump($breadcrumb).

I would rewrite the code as follows.

function modeindeks_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    // Instead of front, you can use the URL of your site's front page.
    $breadcrumb[0] = l(t('Du er her'), 'front');

    $output .= '
' . implode(' › ', $breadcrumb) . '
';

    return $output;
  }
}

If you want to add only You are here link then use the below code.

function modeindeks_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '
You are here: ' . implode(' › ', $breadcrumb) . '
';
  }
}


You can use the entity reference field. Entity Reference module provides the autocomplete field for the user reference.

Add an entity reference field on the feedback content type. This field is autocomplete field. So whenever you create a feedback you can select the name of the user for which you want to add the feedback and refer the same.

Still if you are unclear then provide me some more info so i can help you out..

Update: In your case you have to create a link on the user profile page and add the name of the user being viewed in the query string. So if you are viewing the profile of user1 then on the user profile you can generate the link $base_url/node/add/feedback?name = user1

Now when any one clicks on that page you will be redirected on the node creation page and you can get the argument value from the URL. You can set this argument value in the form field using hook_form_alter() hook.

Update 2: I found something like your question here


Recommended tools/techniques for monitoring for spam attacks on multi-site and shared servers

ether try the free mollom service or you can blacklist words before they get submitted. Another solution that does well is just use the disqus module to regulate your commenting. i have switched over to disqus completely. but its not seo friendly as its a js script call from what i remember. if you want seo capability best you blacklist words and links. say if someone posts a link it would throw an error. this would deter any link spammers as most bots posts links.


Custom field widget with text field formatter?

I recently needed to create a widget for file field, that among other things needed to be able to handle multiple uploads via plupload.

Anyways, during the process of getting everything to work, I discovered the #value_callback attribute that you can put on a form item. It allows you to change the data of the submitted data and extra extra infomation, like fid of a file.

This isn't documented yet, but you can take a look at it's use in the file module. There is an issue for this on the Drupal issue tracker, but no good patch has been created with some document example yet.

I'm not sure if this would be a good case for the use of #value_callback, but it seems to me, that it could be of good use in this case.


Redirect a view page to another view page with arguments in the url

So, solving this took a few different directions to figure this one out.
The problem was I needed to redirect a view with an argument in the url (node/%/outcomes) to a new sub-button so there was an actual button. (Yes this is also a UX issue that the user needed to have the button)

So, I created a new panel page and in the content area I created new custom content. I used the module, php filter, this way I can use the PHP input for the wysiwyg. Then I pasted this code to redirect.

global $base_url;
header("Location: %node/:nid");

That redirected and kept the argument so everything would work fine.
Hope that helps someone!


Display a thank you message instead of a page redirect after submitting a Webform in a block?

You can do it, from the webform configuration page: Use Redirection location or Confirmation message.


How to prepend a text of string to a content_type's field?

Create a template override for the field. Because it sounds like a class assignment, I'll leave the actual coding to you.


My question: how can I fetch the previously applied flag in rules so
  that I can update the timestamp and re-save it?

Some good news but mostly bad.

If you add an extra text field to the flag and add an extra rule to set its data value to [flagged_uid]-[flagger_uid] when a flag is created, it seems that you can then fetch the flagging using that field as the Property and [account_uid]-[current-user_uid].

I say seems because while the rule runs without errors and I know my logic is right, I can't do anything to the fetched flagging to prove I've actually fetched it. I get an error when trying to delete it because "Rules doesn't have info about deleting a flagging" and saving it doesn't change the timestamp.

It just feels like it's not fully integrated. Even if you added a date field, I'm not sure Rules could access it on user view.

I guess I would either create a custom rules action to finish the rule or go with a fully fledged Field Collections solution.


Custom module with config exposed in json api

You can't do it. Not with the core JSON:API module. Out of the box, the resources JSON:API exposes are all the entity definitions from EntityTypeManager which includes content & config entities (defined by extending ConfigEntityBase).
However, arbitrarily set config values will not be exposed. JSON:API also doesn't support custom resources, as JSON:API docs state:

The JSON:API module provides no PHP API to modify its behavior. It
is designed to have zero configuration.
• Adding new resources/resource types is unsupported: all
entities/entity types are exposed automatically. If you want to expose
more data via the JSON:API module, the data must be defined as entity.
See the "Resources" section.

The JSON:API Resources project attempts to fill this in if you want to design your own endpoint with custom responses.


Add  element to node body field via WYSIWYG

TinyMCE outputs HTML 4.01 Transitional markup by default, and  is not allowed inside  in that (or XHTML) because styles are not block elements.

You can however force TinyMCE to accept [the invalid] style elements inside the body by overriding the valid_children setting.

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['valid_children'] = '+body[style]';
  }
}

Thanks to TwoD for supplying the answer.


drupal jquery mobile datepicker cannot select year

You can use Date module which has several options regarding to your requirement. You can use date functionalities in your custom form.

For example,

$form['body']['dob'] = array(
  '#type' => 'date',
  '#title' => 'Date of Birth',
);

will have options to select date, month and year.

If #type => 'date_popup', it  will popup with calendar which allows user to select date.

Check this link for more info date example


Problem with database migrating Drupal 8 site from local to web host (multiple databases)

Okay I figured it out. It was the database prefix value in the settings.php file that was the problem.

I set up the site on another web host and got it to work there, then I compared the two settings.php files and noticed that the working one had the database prefix blank. The problem occurred with InMotion Hosting but it worked fine on Bluehost.

Thanks for the help.


How can i have a SimpleNews signup form as modal/lightbox

It's certainly possible, however, modals aren't as simple as clickkng a few things together (at least not before drupal 8 :p).

One way to do it would be to add a counter to user's Session. Increase the counter every time a new page is viewed and once it reaches 3, trigger the display of a modal, for instance by using ctools modal generation api.


Taxonomy menu module suits your need.

  Transforms your taxonomy vocabularies into menus with ease!


The key point in the error message is:

  ...expects parameter 1 to be a valid callback, function 'user-login' not
  found

You need to use:

drupal_get_form('user_login');

Where user_login is the form builder function in this case.

e.g:

print render(drupal_get_form('user_login'));


How can I modify the result of the core Path listing filter?

You can override admin/config/search/path path using hook_menu_alter
and use a custom function as menu callback.

function oyurmodule_menu_alter(&$items) {
  $items['admin/config/search/path']['page callback'] = 'mymodule_custom_path_admin_overview';
}

Then your mymodule_custom_path_admin_overview shoud be a copy of path_admin_overview with your needed alterations.

This is not optimal as you should keep your function code in sync with original code, so any patches applied to path_admin_overviewfunction should applied to your altered function, but is the only way you can alter the functionality without hacking core.


Use a form instead of content type in maestro drupal module

for those who are  still searching the answer for this question

We can use webform instead of content type with maestro, for that we need maestro_webform_task module, the module will integrates
both web form and maestro and provides the list of already created web forms in web form task->edit->select web form to use

maestro_webform_task


Is there a module that helps link similar articles together and insert them into each other?

You can set up nodes to be used like taxonomy items.  Take a look at this:  https://www.drupal.org/project/entityreference

That module will allow you to set a content type as the source for cross-linking nodes.


How do I append HTML after a form title?

You shouldn't concatenate the result of the t() function, it should rather be built up as a single string:

'#title' => t('Name <span>!</span>'),

Other than that, you're already doing this about the cleanest way possible. Other approaches would involve post-processing the form element(s) to render their title in a different way than standard. I imagine that would end up being more trouble than it's worth unless you wanted to do it globally for every element in every form in the site.


Select groups to relate the node to directly in the node creation form

There is no module that offers this out of the box as far as I know. You'd need some custom programming. I don't know what exactly you need, but here's something that might help to get you started.

Let's assume you want to programmatically relate a node/content to one/multiple groups as soon as the node is created. You could use a hook hook_ENTITY_TYPE_insert() (hook replaced by your custom module's name and ENTITY_TYPE replaced by the entity type (e.g. node).

Here's an example for article nodes:

use Drupal\node\Entity\Node;
use Drupal\group\Entity\Group;

/**
* Implements hook_ENTITY_TYPE_insert().
*/
function modulename_node_insert(Node $node) {
  if ($node->bundle() == 'article') {
    $pluginId = 'group_node:article';
    // Here create some logic to load/chose the group id's you want to
    // add the content to
    // ...
    foreach ($group_ids as $gid) {
      $group = Group::load($gid);
      $group->addContent($node, $pluginId);
    }
  }
}

This would automatically add the (article) nodes that are created to one or multiple groups. This is just a basic example of how to code the differnt parts. You can however make it as complex as you need. Hope this helps


How to add conditional HTML meta tag using drupal_add_html_head to force only IE9 into compatibility mode?

Had similar problem:

function detect_ie() {
    if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) {
        return true;
    }
    else {
        return false;
    }
}

above will detect if IE in general. You will need to change 'MSIE' accordingly (something  like 'MSIE9' but not sure if thats correct).

Then what i did was

if(detect_ie()) {
  $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
  'http-equiv' => 'X-UA-Compatible',
    'content' =>  'IE=EmulateIE7',
     ),
  );
drupal_add_html_head($element, 'IE_cr_ap');
}


How to give meaningful id names to blocks?

Use the block class module. Block Class allows users to add classes to any block through the block's configuration interface.


I would like to be able to use some tokens like %post[key]used in webform, in my custum module how to call these up in my custum module

I think you need these hooks:

hook_token_info() - this hook will allow you to define empty placeholders. Define a few placeholders which you want to make available to the webform.
hook_tokens() - corresponding to the plkaceholders you have defined, pass in appropriate stuff and define a replacement pattern for each placeholders you have defined in your earlier hook_implementation.
Finally, while rendering user submitted value, apply token_replace() function to replace the placeholders entered by user with appropriate values.

UPDATE:

Got you. Have a look at this function _webform_filter_values(). This funciton is responsible for replacement of webform tokens. you can use this funciton in your code, pass in the stuffs you want to replace and the node and submiccions object and have the value replaced.

It will be impossible for me to give you exact direction, as i am not familiar with what you are doing. But i can give you a general idea. Token replacement often happens at the output stage. So it is more concerned with output. So mostly, you need to apply this to your code which displays/prints/uses the webform submission result of your field.

Say you create a webform field. I as an end user, enter a string to it which contains this: %post[key]. Now your submit handler code will need to use the said function. When you pass the input i entered through that function, my %post[key] is replaced by appropriate value.


I learnt adding <none> to the title field does this.


How to render a Get Locations map programmatically?

As per hutch's comment, and my experiments, I managed to solve it. I wrote it down here: https://drupal.org/node/2082137#comment-7832139.

I created a separate function for the task:

/**
 * Load a map from multiple node ids with the appropriate markers
 *
 * @param array $nids The node ids of the nodes you want to get displayed on the map.
 * @param array $getlocations_extra_settings Some extra settings you want to override the default values with.
 * @see https:// drupal.org/node/2082137
 * @todo Patch for getlocations_setlocations() to accept settings which override the defaults, or figure out an alternative solution.
 */
function getlocations_nodemap_multiple($nids = array(), $getlocations_extra_settings = array()) {

  $latlons = array();
  $minmaxes = array('minlat' => 0, 'minlon' => 0, 'maxlat' => 0, 'maxlon' => 0);
  $count_nids = 0;
  // override default settings
  $getlocations_settings = array_merge(getlocations_defaults(), $getlocations_extra_settings);
  $marker = $getlocations_settings['node_map_marker'];
  $typemarkers = getlocations_get_markertypes('node');

  foreach ($nids as $nid) {

    // maybe a less resource consuming method should be used
    // btw., what about entity_load()? (https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7)
    $node = node_load($nid);
    $locations = getlocations_load_locations($node->vid);

    if (isset($typemarkers[$node->type]) && $typemarkers[$node->type]) {
      $marker = $typemarkers[$node->type];
    }

    if (count($locations)) {
      // we should loop over them and dump bummers with no lat/lon
      foreach ($locations AS $key => $location) {
        $latlon = getlocations_latlon_check($location['latitude'] . ',' . $location['longitude']);
        if ($latlon) {
          $minmaxes = getlocations_do_minmaxes($count_nids, $location, $minmaxes);

          if (!isset($location['key'])) {
            $location['key'] = '';
          }
          else {
            if ($location['key'] == 'nid') {
              $location['lid'] = $nid;
            }
            elseif ($location['key'] == 'vid') {
              // not vid?
              $location['lid'] = $nid;
            }
          }

          // term markers
          $marker = getlocations_get_term_marker($nid, $marker);

          // per location marker
          if (isset($location['marker']) && ! empty($location['marker'])) {
            $marker = $location['marker'];
          }

          $count_nids++;

          $name = htmlspecialchars_decode($location['name'] ? strip_tags($location['name']) : strip_tags($node->title), ENT_QUOTES);
          $latlons[] = array($location['latitude'], $location['longitude'], $location['lid'], $name, $marker, $location['key']);
        }
      }
    }
  }

  if ($count_nids < 2 ) {
    $minmaxes = NULL;
  }
  return getlocations_setlocations($latlons, $minmaxes);
}

And now I can call it like this:

function testmodule_any_custom_page_callback_you_want_to_use($blabla) {

  $output = '';

  $nids_array = array(41, 45, 52, 73, 219); // of course, this array is generated

  $getlocations_extra_settings = array();
  $getlocations_extra_settings['extcontrol'] = 'testmodule';
  $getlocations_extra_settings['fullscreen'] = 1;
  $getlocations_extra_settings['streetview_show'] = 1;
  $getlocations_extra_settings['maptype'] = 'Map';
  $getlocations_extra_settings['visual_refresh'] = 1;

  $output = getlocations_nodemap_multiple($nids_array, $getlocations_extra_settings);

  return $output;

}

This solution currently has its limitations, because unfortunately the default settings are hardcoded to getlocations_setlocations (the values of getlocations_defaults() are currently hardcoded). I hope hutch will develop this part further. :)


Extra arguments passed to the initial form function will not be passed to the alter - so the 4th parameter of $node in your form alter function isn't available. If you check your logs you'll probably find a related notice.

For any node form (including webform), you should be able to get the node object directly from the form:

$node = $form['#node'];


How to have node id value set depending on some other id?

Take a look at migrate module and this hands-on guide (disclaimer: I work for that company, so to balance: lullabot's guide ) Both are good to understand everything that's necessary for what you asked.

You might want to consider creating a field_old_node_id field to ease on the transfer if you can't set the ID through this, and use Pages module to create a separate /node/%nid page that uses that field instead to display the node.


Sorting non-english characters in multilingual website

It may help to somebody.

I end up with doing a simple module (which I'm gonna improve later) that inject COLLATE while doing query to Database so it sort everything properly.

Please feel free to comment this solution :)

<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}


I was missing to check Enable insert button under the INSERT settings in my image field configuration where yo also select the Enabled Insert styles


After Upgrading from D7 to D8, D8 does not look like D7 at all

Drupal 8 is very different from Drupal 7, same goes with previous major versions of Drupal.

This means that themes and modules can only work for a single Drupal major version (fx 6, 7 or 8).

When you migrate a site from D7 to D8 you have to re-implement the theme. In Drupal 8 we now use Twig as the template language so you pretty much have to start from scratch (unlike 5 -> 6 -> 7 where the theme differences wasn't that big and a lot could be reused).


How to add "publish content" to a node view tab

There's already a module called Publish Content that does what you exactly describe. You can browse the source code if you want to see how it's implemented there.


Class not found in drush command definition

As @Berdir says it seems Drupal is not fully bootstrapped when the hook_drush_command() is called as I tried to use a service defined in a custom module and I get the following error:

\Drupal::$container is not initialized yet.

So the solution for the moment is hardcode the values that should be returned by the function.


Are the templates that are overriding your templates included in a Theme? Themes always take precedence over modules, so any template in a theme will always override the corresponding template from a module. You may want to consider re-phrasing your question to reference the original issue you are solving with your template files.

If you are referring specifically to Views output with your desire to create semantic markup, I would suggest the Semantic Views module.


How to form_alter fields attached to an unlimited field collection?

Check the array to make sure you are using the correct names and structure.  You can use dpm() from the devel module to check this.

Both hook_form_alter or hook_field_widget_form_alter allow you to alter field collection child field form elements.

<?php

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';

        }
      }
  }
}

The following will also work:

/**
 * Implements hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {

    $element['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';
    $element['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';

  }
}


Programing date custom field into content type

Like 4k4 suggested, I used https://www.drupal.org/docs/8/api/entity-api/using-the-ui-to-export-the-code-for-your-custom-fields to create and export all my needed fields and it worked really well.

Note: With a lot of changes you may need to delete config for the already created settings.
Remove it with: drush config-delete field.storage.node.field_name
Found that here


How do I delete all menu links from a menu using the menu machine name in Drupal 8

$mids = \Drupal::entityQuery('menu_link_content')
  ->condition('menu_name', 'browse')
  ->sort('weight')
  ->execute();

$controller = \Drupal::entityTypeManager()->getStorage('menu_link_content');
$entities = $controller->loadMultiple($mids);
$controller->delete($entities);


The output on the screen is caused by a bug in Drush.

From https://github.com/drush-ops/drush/issues/4004#issuecomment-479155241:

  The problem is that Drush is setting tty mode even though output is redirected. This is wrong.

Workaround 1 via the command line:

drush -Dssh.tty=0 @site.alias sql-dump > ~/Dumps/dumpy.2019-02-19.sql

Workaround 2 via the YAML file that defines the remote, as suggested at https://github.com/drush-ops/drush/issues/4004#issuecomment-500157166:

  For anyone coming across this issue. I had a similar problem with Drush 9.7.0 where sql:dump output was sent to standard output instead of a file. Based on the above workaround, I fixed it with the 'ssh' option in the drush alias of the remote site:

site.alias:
  ssh:
    tty: 0


array('value' >= 4) is not the correct syntax to define an array containing the index value.

Basing on Fixed conditionals to allow OR and XOR constructions, you can use the following code.

$form['model'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => array(0 => t('- Select -')) + $options,
  '#default_value' => 0,
  '#states' => array(
    'visible' => array(
      array(
        array(':input[name=platform]' => array('value' => 4)),
        array(':input[name=platform]' => array('value' => 5)),
        array(':input[name=platform]' => array('value' => 6)),
        array(':input[name=platform]' => array('value' => 7)),
      ),
    ),
    'required' => array(
      array(
        array(':input[name=platform]' => array('value' => 4)),
        array(':input[name=platform]' => array('value' => 5)),
        array(':input[name=platform]' => array('value' => 6)),
        array(':input[name=platform]' => array('value' => 7)),
      ),
    ),
  ),
);

Using this code, the form field will be visible when the other form field value is one of the following values: 4, 5, 6, 7. It works with Drupal 7.14, or higher.


Extracting the values of Field Collection

Do you want to access the values or the rendered output of those field collections?

For the second, you're supposed to configure the view display to display the fields of the collection. I don't know how it works exactly. Looking at the code, the field collection itself should have a view display UI, just like the node itself, where you can configure each field.

If you want to access the values, then you should do the following:

Do not use getValue(). It returns non-computed properties only and it returns them as a simple array. You want the field item object.
content is the rendered output, node is the node object with the values. So, you'd use for item node.field_robot. Looking at the code, it seems you'd need to use item.getFieldCollectionItem() and from there, access a certain field again, e.g. item.getFieldCollectionItem().yourfield.value.

But... from looking at the code a bit and that it has two major 8.x branches and not even an alpha release yet... it might be too early to use that project. Maybe you want to look at Inline Entity Form (8.x-2.x actually seems to depend on that) together with e.g. a node type or custom entity type or Paragraphs. We use the second quite actively and it's pretty well progressed for Drupal 8.


On 'Add content' page, please check which 'Text format' you have selected in drop-down below the CKEditor.

Make sure that you have selected the Full HTML or Filtered HTML according to your field settings.


how to make relations link when editing taxonomy not show

You may create your custom permission in the hook_permission and then hide this part of the form in using hook_form_alter if user shouldn't have access to this element.


How to create charts in Drupal while working offline that integrate with the Quiz module?

You can use Flot since it has views integration as Quiz.
Flot can be used offline while Google charts can't because of their TOS.


How to override template for view mode of a entity within a module?

I did this using hook_process_HOOK($variables) for nodes view mode tpls :

function view_mode_tpl_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' .$vars['view_mode'];
}

hope this will help you.


How to allow access to page variant (Page Manager) if user belongs to list

Currently I'm using a selection rule that checks if the logged-in user has "flagged" the Event with a Signup. This works but checking if the logged-in user is on the list would be a waterproof solution.


Referenced Entity not Updating Correctly When Saved

What is the reason you use a Entity Reference Revisions field? Normally this is more suitable for entities edited inline like paragraphs.

In your case this behavior seems to be what you would expect from this field, because you reference a specific revision of node B and not the latest version you've saved. If you want to do this, then use the core reference field.


Have a look at

user_external_login_register

  Helper function for authentication modules. Either logs in or
  registers the current user, based on username. Either way, the global
  $user object is populated and login tasks are performed.

The example at:

https://api.drupal.org/comment/13434#comment-13434

Is a worthwhile read too.


How do I run PHP code when visiting a specific URL?

Apart from controllers, one could also listen for Events,  using code similar to the following. Depending on what the custom logic mentioned in the OP is expected to do, this could be an alternative answer.

nncbt.services.yml:

services:
  nncbt_event_subscriber:
    class: '\Drupal\nncbt\EventSubscriber\NNCBTSubscriber'
    arguments:
      - '@logger.factory'
    tags:
      - { name: 'event_subscriber' }

src/EventSubscriber/NNCBTSubscriber.php:

<?php

namespace Drupal\nncbt\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Drupal\Core\Logger\LoggerChannelFactory;

/**
 * An EventSubscriber for REQUEST and TERMINATE events.
 */
class NNCBTSubscriber implements EventSubscriberInterface {

  /**
   * The logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_channel_factory
   *   For logging purposes.
   */
  public function __construct(LoggerChannelFactory $logger_channel_factory) {
    $this->logger = $logger_channel_factory->get(self::class);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['earlyCode'];
    $events[KernelEvents::TERMINATE][] = ['lateCode'];
    return $events;
  }

  /**
   * This method is called for KernelEvents::REQUEST events.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The incoming event.
   */
  public function earlyCode(GetResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

  /**
   * This method is called for KernelEvents::TERMINATE events.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The incoming event.
   */
  public function lateCode(PostResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

}

Good luck!


Why isn't my composer installation working?

As shown in the example reported in the documentation page you linked, you need to add drupal/ to the machine name of the module you want to install. The given example is exactly for the Devel module.

composer require drupal/devel:~1.0

The name of the packages handled from Packagist has the format vendor/package, so if you simply use the machine name of the module, Composer will not be able to find the package you meant.

Remember to run the commands from the directory containing the composer.json and the composer.lock files, not from the core directory.


It looks like you have a different domain either registered or for testing with Google Webmaster Tools.

e.g example.com vs www.example.com

When the bot requests example.com, it is redirected to www.example.com with an HTTP 302 Found reponse.

The solution would be to register the same preferred domain with Google Webmaster Tools that is used for regular site visitors.

As for 0 pages of a new site being indexed in Google, give it time. If you've registered the sitemap, and signed up for Google Analytics, the googlebot will arrive soon. It can take a couple of weeks.


How to check term ID present in database table before updating

Your compound key you need to check for is for uid & tid. You can check for a row's existance (thus, need to insert) with a db_query function call & rowCount method call.

if(db_query('SELECT totalview FROM {custom_file_download_count} WHERE tid = :tid AND uid = :uid', array(':tid' => $tid, ':uid' => $GLOBALS['user']->uid))->rowCount() == 0) {
  db_insert('custom_file_download_count')
  ->fields(array(
    'totalview' => 0,
    'tid' => arg(2),
    'timestamp' => REQUEST_TIME,
    'uid' => $GLOBALS['user']->uid,
  ))->execute();
}
db_update('custom_file_download_count')
->fields(array(
  'totalview' => 1,
  'tid' => arg(2),
  'timestamp' => REQUEST_TIME,
  'uid' => $GLOBALS['user']->uid,
))
->expression('totalview', 'totalview + 1')
->execute();


Image Editor will do that,

Drupal 6 version allows to edit Imagefield items and save them back either by replacing the original image or adding new Imagefield item. but I'm not sure it will integrate with webform, You need to test it.

See the Demo Here

  Bring image editing (draw, text, crop, scale, etc.) functionality into
  your Drupal website! Edit/create any images online in the powerful and
  feature-rich image editors and save resulted images back to your site!


Paragraphs is focused on reusing layouts not content. The most obvious implication is on revisions.

In a standard reference field you reference the latest revision of the target. When you roll back the parent the target keeps the actual content. Paragraphs on the other hand keeps track of the revisions and allows you to rollback an entity including the content of the paragraphs that are owned by the entity. And that's the problem, if Paragraphs would allow reusing, how a rollback should be handled for paragraphs that are shared among multiple host entities.

So Paragraphs is by design not a tool for reusing content.

But there is good news, there will be a library entity, which will make this possible:

  Implement Library entity type

  We want to make this separate entity type:
  - Autosync with bundles + fields of Paragraphs
  - Still add a label (plus more administrational fields if needed for managing them).

  A reusable paragraph will be typically stored as a clone of a previous
  paragraph. It is NOT a composite of the original. Reusable paragraphs
  have an own separate edit form and can also be creted independently
  through the Add form.

  A user can click the action "Add to library" that makes a paragraph
  reusable. This clones the paragraph and the original host entity will
  have a new paragraph instance added that contains a reference to the
  effective reusable paragraph.

  The paragraph type "From Library" contains nothing but a entity
  reference to the reusable paragraph. Initially, using autocomplete
  widget here is fine.

https://www.drupal.org/node/2843917


Well, I did it, for anyone that needs this:

public function pageAction() {
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  // If you want modify the form:
  $myform['field']['#value'] = 'From my controller';

  $build = [
    '#theme' => 'mytemplate'
    '#form' => $myform,
  ];
}

In twig:

{{ form }}


This renders within a block plugin:

class myModule extends BlockBase {
  public function build() {

    $default_form = \Drupal::config('contact.settings')->get('default_form');
    $entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $entity->id(),
      ));

    $form = \Drupal::service('entity.form_builder')->getForm($message);

    return $form;
  }
}


drush is not ready for that right now (as far as I know), so you'll need to write custom drush-scripts or do some other execution. drush cr rebuilds the whole cache, drush cc is not working with drupal8.
the method drupal_flush_all_caches shows how to flush all core caches.
$module_handler = \Drupal::moduleHandler();
  // Flush all persistent caches.
  // This is executed based on old/previously known information, which is
  // sufficient, since new extensions cannot have any primed caches yet.
  $module_handler->invokeAll('cache_flush');
  foreach (Cache::getBins() as $service_id => $cache_backend) {
    $cache_backend->deleteAll();
  }

  // Flush asset file caches.
  \Drupal::service('asset.css.collection_optimizer')->deleteAll();
  \Drupal::service('asset.js.collection_optimizer')->deleteAll();
  _drupal_flush_css_js();

  // Reset all static caches.
  drupal_static_reset();

  // Invalidate the container.
  \Drupal::service('kernel')->invalidateContainer();

  // Wipe the Twig PHP Storage cache.
  PhpStorageFactory::get('twig')->deleteAll();

  // Rebuild module and theme data.
  $module_data = system_rebuild_module_data();
  /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  $theme_handler = \Drupal::service('theme_handler');
  $theme_handler->refreshInfo();
  // In case the active theme gets requested later in the same request we need
  // to reset the theme manager.
  \Drupal::theme()->resetActiveTheme();

  // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
  // sufficient, since the list of enabled modules might have been adjusted
  // above due to changed code.
  $files = array();
  foreach ($module_data as $name => $extension) {
    if ($extension->status) {
      $files[$name] = $extension;
    }
  }
  \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
  // New container, new module handler.
  $module_handler = \Drupal::moduleHandler();

  // Ensure that all modules that are currently supposed to be enabled are
  // actually loaded.
  $module_handler->loadAll();

  // Rebuild all information based on new module data.
  $module_handler->invokeAll('rebuild');

  // Clear all plugin caches.
  \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();

  // Rebuild the menu router based on all rebuilt data.
  // Important: This rebuild must happen last, so the menu router is guaranteed
  // to be based on up to date information.
  \Drupal::service('router.builder')->rebuild();

  // Re-initialize the maintenance theme, if the current request attempted to
  // use it. Unlike regular usages of this function, the installer and update
  // scripts need to flush all caches during GET requests/page building.
  if (function_exists('_drupal_maintenance_theme')) {
    \Drupal::theme()->resetActiveTheme();
    drupal_maintenance_theme();
  }

There's a module too, enable admin_toolbar's admin_toolbar_tools submodule to have it all in the toolbar:


You can implement hook_preprocess_field() in your template.php and remove the classes you want after checking the field name .

Update: As @tenken suggested you can also look into Display Suite module.


Passing object by reference in form element of type 'value'

Objects are 'passed by reference' in the context of being passed to a function in a single page request.

Once the page has reloaded (e.g. when you submit your form), the memory for the original object is freed and it's impossible to maintain a reference to it (at least with standard PHP to the best of my knowledge).

You can keep a copy of the object (which is what Drupal does), and instantiate a version of it on the next page, one that has exactly the same characteristics as the original even, but it's not a reference to it.

What you're doing is absolutely fine, but if you're worried about changes being made to the object after it's been attached to a form, but before it's been submitted, then you should keep hold of the object's identifier instead, and use whatever helper function is available to re-load that object in the submission process. That would be safest I think.

But if your class is dumb, and doesn't have DB persistence/unique identifiers/something that's going to be changed by some other part of the system, then just add it as a value as you're doing already.


Where is the result of the query is stored?

You could get the nids like this:

// load and display view
$view = views_get_view('view_name');
$view->set_display('block_1');
$view->execute();
$nids = [];
// get all nids from the result
foreach ($view->result as $result) {
   $nids[] = $result->nid;
}
// render view
print $view->render();


It's not uncommon to customize block contents based on URL arguments. I don't see any reason to not do that.

However, since your block contents can change based on the URL, you need to use either no cache at all or DRUPAL_CACHE_PER_PAGE.

If your block contains any Ajax elements, note that arg() will return the ajax path.


Drupal 8 Custom Twig Templates not being loaded

Can we start easy? I think 9 times out of 10 when my templates dont load it's due to file naming issues. Do the file names match what's in the database as your content type machine name?

One thing that has happened to me a couple times is I hit enter too soon when creating content in drupal. That ajax just needs a little time to catch up and fill in the machine name. Too soon and your dash_c page could actually be named dash_

Do you have devel enabled? Can you see the *FILE NAME SUGGESTIONS when you "view source" of your webpage?


In views you need to add in relationship "Taxonomy term: field name" and in contextual filters you need to set "(field_name) Taxonomy term: Name" or "(field_name) Taxonomy term: Id".


Is there a way to override paths defined in *.libraries.yml

Yes, this is possible. hook_library_info_alter() is used to alter basically anything in the library definition.


From what directory should "drush cc all" command be run?

It's irrelevant. The command:

drush cc all

clears all caches. The directory has no affect on what is cleared. If you want to target modules use:

drush cc module-list

Or if you want to target another cache use:

drush cc

which will prompt you for a cache to target.


How to give a content editor access to the theme settings?

You could use a hook_form_alter in your custom module.

The following assumes you already have a role called editor existing in your website.

Create a mymodule folder (e.g. in http://www.example.com/sites/all/modules/custom/mymodule)
Create two files in that folder. mymodule.module and mymodule.info
Past the following code in mymodule.module

 <?php

  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'system_theme_settings' && in_array('editor', array_values($user->roles))) {
    // unset the elements you don't want your content editor to have access to
    // unset($form['css3']);
    // Here we want to hide some form elements.
    // To hide/show an element we must use $element['#access'] key in the render array.
    // Using unset($element) might cause issues in form_validate and form_submit processes.
    // So instead of unset($form['css3'], $form['layout']) we set their access to FALSE
    $form['css3']['#access'] = false;
    $form['layout']['#access'] = false;
  }
}

Past the following in mymodule.info

name = Mymodule
core = 7.x
Enable your module at http://www.example.com/admin/modules
Clear your cache

Please note that these are the minimum requirements for creating a custom module and you should definitely read up on best practices for creating custom module at https://www.drupal.org/node/1074360


Is this a "secure" table?

Depends on what you mean by secure.

  Are there tasks (cache-clear or other) that
  could automatically remove values from this table?

No.

  Is it a good idea to create a custom form to let users to set some
  states?

This is kind of looking at it from the wrong direction. States are a solution to an issue. If you have something that is to be stored, for which states are a good solution, then they are good to use. In other words, if you have a form that does something that states would be good for, then use states. Deciding to use states then creating forms for them doesn't really make sense.


How do I programmatically update the order status?

You want to use the State Machine methods of the Commerce Order class.

It would be something like this, but it will depend on what you called your order states.

$order_state = $orderObj->getState();
$order_state_transitions = $order_state->getTransitions();
$order_state->applyTransition($order_state_transitions['complete']);

$orderObj->save();

If you aren't sure, you can always check the $order_state_transitions array to see what options you have.


I assume you are using D7 with Entity Reference.  You should be able to do this with stock Rules, without any PHP code:

Create a new rule
Event, select "After updating existing content"
Condition, select "Content is of type" to match whatever content type it is.  This will qualify the fields so that you can use them later
Condition, select some other limiting condition so that you don't target every single node with updated content.  You could, for example, do a data comparison to check if the content has a given taxonomy term
Action, select "Set data value".  Your target should be node(updated content):author.  Your new value should be node(updated content):field-new-author


How to change widget's icons in the service-links module?

CSS solution for position:
for services widgets (FB, pinterest, linkedin) you can not change images, for General Services (twitter, G+) you can upload your own images.

Here is my CSS code and links appear centered inline.

/* services share links */`
.service-links ul li {
 text-decoration: none;
 display: inline;
 overflow: hidden;
 list-style: none;
 padding-right: 10px;
 vertical-align: baseline;
 float: left;
 }

.service-links li {
 display:inline;
 vertical-align: bottom;
 position: relative;
 }
.service-links .service-links-linkedin-share-button {
top: 5px;
}

.service-links .service-links-facebook-share {
bottom: 5px;
}


Open a Make Meeting field inside colorbox

The easiest way to do this is through views. You can configure a view with an "Contextual Filter" of the node id to show and then configure it to show your makemeeting field here. Here's a screenshot of a view that worked for me (note the important parts are marked with arrows.

Then when I go to /meeting-popup/6 (where 6 is the id of a node with a meeting field) i see the following.

Then you can add a link to /meeting-popup/ on the nodes page using the lightbox-load class so it will showup in a popup.

Lastly you can theme the meeting-popup pages so that they only show the content and don't show any regions/sidebars, etc.

Alternatively you can have views make it into a "block" if you know of a good way to do it that way.


How to show specific rows within an unlimited field group?

Yes you can do it by form_alter. Seeing through the code of other similar question, I see that unsetting the Add More button can do it for. You can review that code & apply for your case.

You can do it by help of Field Validation module too, which has been mentioned in 2nd answer & more feasible way. I have also used it for some projects of mine, where I did set minimum & maximum required for a field accepting multiple values.


How to specify a twig template for a custom Drupal 8 page?

I got that to work. Here's my solution.

Create a template in path/to/your/module/templates/my-custom-page.html.twig.

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path)
{
    return [
        'my_custom_page' => [
            'render element' => 'custom_page',
            'path' => $path . '/templates',
            'template' => 'my-custom-page',
            'variables' => [
                'var1' => 'default value for var1',
            ],
        ],
    ];
}

I couldn't figure out what render element is for, but it is required.

variables element defines the variables available in your template and provides default values for them. You can override them in your controller.

use Drupal\Core\Controller\ControllerBase;

/**
 * Class CustomPageController
 */
class CustomPageController extends ControllerBase
{

    public function getPage()
    {
        return array(
            '#theme' => 'my_custom_page',
            '#var1' => 'Actual value for var1',
        );
    }

}

Clear the cache and visit your custom page route. Everything should work.

Helpful links:

Render API
overview
hook_theme()


After perform R&D, I found that uid of the node was not matching with uid in {users} table, which mean there is no existing user which is author of the node.

As I am importing the node from external database and it was importing properly previously, so I did not noticed the same.

Now, when I changed the uid of the node, everything starts working properly.


I think you want to keep it in table. Lets try with putting it in one like this --

$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => '

',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '

',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

I haven't tested this code, so please try this & let me know if it works :)


I did it with module_invoke().

$block = module_invoke('views','block_view','-exp-machinenameoftheview-page');
if (!empty($block)) {
  // The view is enabled.
}
else{
  // The view is disabled.
}


As far as I can tell the DFP module doesn't load API version specific files and so unless you are using additional custom JS or loading the DFP JS files directly from your site (instead of pulling them from Google), there is no reason the API change should effect the module itself.


How do I hide nodes tagged with a specific taxonomy term in views?

You need to add a new filter to your view.

Filter criterion: Has taxonomy term
Vocabulary: Corresponding vocabulary
Operator: Is none of
And select the hidden term in the dropdown


You don't need to create this action programmatically. You can simply use the Rules UI.  I'm pasting an export of a sample Rule that does this. You can import it using the Rules UI import link.

{ "rules_email_administrators_when_new_node" : {
    "LABEL" : "Email administrators when new node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_delete" : [] },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "Node added or modified.",
          "message" : "Hi, administrator(s),\r\n\r\nA node has been added or deleted.\r\n\r\nNode ID: [node:nid]\r\nNode title: [node:title]\r\n\r\n"
        }
      }
    ]
  }
}

EDIT: Now, if you MUST do this programmatically, I would first look at the Examples for Developers project (it contains an action example). In a nutshell:

First, I would use dpm($context); and 'dpm($object); to see what parameters are being passed to the function. You can probably use some of the information there to include in the email, like the node ID and the author ID.
Then I would load an array of administrator users, maybe using EntityFieldQuery or a db_query.
Then I would use drupal_mail() to send the email. It shouldn't be hard to do.


If "mahjong" is just an arbitrary object type, you need to declare it to Rules using hook_rules_data_info and specify the "token type" so that Rules knows what to pass to the token API.

But if the "mahjong" object is a Drupal User entity, you shouldn't need to implement hook_token_* at all.

Instead, when you define your Rules event, the argument should be of type "user". Rules will then know what fields are defined on the entity.


Verify that salt.txt was located and being used by Drupal?

You can check this with drush by using Settings::get('hash_salt'):

drush ev "var_dump(\Drupal\Core\Site\Settings::get('hash_salt'))"


Uploading from within fieldset using drupal 6 forms API not working

Add this to beginning of your form

You need this:

$form['#attributes'] = array('enctype' => 'multipart/form-data');

Also:

file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME)

you have

graphic1 = file_save_upload('graphic1', file_directory_path(), FILE_EXISTS_REPLACE);

you should have

$graphic1 = file_save_upload('graphic1',,file_directory_path(), FILE_EXISTS_REPLACE);

One thing I've noticed in D6 with file uploads is that using only file_save_upload() will result in your file being purged on a subsequent drupal cron run. This happens because all files are uploaded in Drupal with a status of 0.

Therefore, you should be calling your hook_submit more like this...

// Save new file uploads.
if ($file = file_save_upload('file_upload', $validators, file_directory_path())) {

// Do something with $file here.

//Make file permanent
file_set_status($file, FILE_STATUS_PERMANENT);
}


Forced rendered node view results in empty node links

Use renderPlain():

$message['body'][] = \Drupal::service('renderer')->renderPlain($body_data);

From the documentation:

  Renders final HTML in situations where no assets are needed.

  Calls ::render() in such a way that placeholders are replaced.

  Useful for instance when rendering the values of tokens or emails,
  which need a render array being turned into a string, but do not need
  any of the bubbleable metadata (the attached assets and cache tags).

Source: Renderer::renderPlain

"When I render the same content into an html page, node__links are correctly filled."

render() in a page works, because the page has a render context for the metadata to bubble up, so that the placeholders can be replaced later.


The author of the module Facebook Album Fetcher has already posted a reply to a similar/identical problem that was posted in drupal.org. The general idea is that if you have followed the 10 steps that are described in the module page, you should log in to your facebook account and make sure that the album that you are trying to fetch is actually public.


Give an individual cron task for each Feeds import

You can indeed use Elysia and define a cron job for each of the feed imports like this:

/*
 * Feed import managed by Elysia
 */
function MYMODULE_cronapi($op, $job = NULL) {
  $items['fetch_MYFEED_cron'] = array(
    'description' => 'Fetch MYFEED',
    'rule' => '*/10 * * * *', // Every 10 minutes
    'callback' => 'MYMODULE_fetch_MYFEED_cron',
    'arguments' => array(array('MYFEED')),
  );
  return $items;
}
function MYMODULE_fetch_MYFEED_cron($feednames){
  if (function_exists('feeds_source')){
    foreach($feednames as $feedname){
      $source = feeds_source($feedname);
      $source->import();
    }
  }
}


To rewrite the ID of the block (if you really want to), you would either use a preprocess function or a custom template file.

Looking at the preprocess function for blocks template_preprocess_block() found here.

https://api.drupal.org/api/drupal/modules!block!block.module/function/template_preprocess_block/7

You can see how the ID is created: $variables['block_id'] and what the theme suggestions are: $variables['theme_hook_suggestions']

You should be able to create a function in you themes template.php as follows:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block_id'] == 'old_id') {
    $variables['block_id'] = 'new_id';
  }
}

However, with a filterblock, there might be some special relationship to the view that might be damaged, I'm not sure, but either way, you do not need to use Rules.


How to edit webform's email field default error message?

String Overrides module may be an alternative.

  Provides a quick and easy way to replace any text on the site.


I am looking for this for Drupal 8, however it appears that the module Commerce Product Add-on provides a solution for Drupal 7 (I have not tested it).

  Commerce Product Add-On allows users to attach products as options to
  the add to cart form of another product. This is particularly useful
  for things like event sponsorship, optional accessories, and other
  up-sells.


How to display content from a second database

Maybe consider the Forena module for accessing your data in your custom database. It seems like a perfect fit for what you're asking for. It also includes charting features, which is typically a related requirement. Not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS. You didn't specify if your custom database is any of those, but any of these will do ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

Note: I'm a co-maintainer of Forena.


very simple form in block rendering incorrect values

That form expects an array representing the current term as edited as its first argument. The vocabulary is the second argument. Add an empty array as first argument and you should be OK.


Create a connection using FileTransferFTP

The code used to create an FTP connection is similar to the following one.

try {
  $ftp = FileTransferFTP::factory($jail, $settings);
  $ftp->connect();
  // Copy the files.
}
catch(Exception $e) {
  // An error happened.
}

$jail is the directory to which the operations are restricted. Any tentative to write files externally to this directory will raise a FileTransferException exception.

$settings contains:

$settings['username']: The username
$settings['password']: The password
$settings['advanced']['hostname']: The hostname for the FTP server (default to localhost)
$settings['advanced']['port']: The server port (default to 21)

FileTransferFTP::factory() returns the instance of the sub-class that takes care of the file transfer, if there is one, or raises an exception, if there aren't sub-classes.

The code currently executed from FileTransferFTP::factory() in Drupal 7 is the following one.

  $username = empty($settings['username']) ? '' : $settings['username'];
  $password = empty($settings['password']) ? '' : $settings['password'];
  $hostname = empty($settings['advanced']['hostname']) ? 'localhost' : $settings['advanced']['hostname'];
  $port = empty($settings['advanced']['port']) ? 21 : $settings['advanced']['port'];

  if (function_exists('ftp_connect')) {
    $class = 'FileTransferFTPExtension';
  }
  else {
    throw new FileTransferException('No FTP backend available.');
  }

  return new $class($jail, $username, $password, $hostname, $port);

Future versions of the class could implement the method differently, and create different instances of the FileTransferChmodInterface interface basing on different conditions.

In Drupal 8, the class has been renamed Drupal\Core\FileTransfer\FTP.


How to render only markup in region template?

/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
 function hook_preprocess_page(array &$variables) {
   $variables['page']['footer'] = [     # Specify the region name
     '#theme_wrappers' => ['region'],
     '#region' => 'footer',             # Specify the region name
     'phantom_block' => [
       '#markup' => ' ',
       '#weight' => "-100",
     ],
   ];
 }

This way you are adding a block with a space to the region. Forcing Drupal to render that region. But as you will put a static HTML in that region, the content of the phantom block will not be rendered.


Branched user permissions for editing content types

I think you may try Node Privacy by Role module.
First create three roles Parent Editors, Child Editors, Subchild Editors
Then while creating a node you will be asked about the permission to edit the node.
But this might not help you when you want to protect nodes per user.

There is also another module Taxonomy Access Control Lite which governs access to nodes based on the taxonomy terms applided to nodes.
In this you can create terms for Parent Editors, Child Editors and Subchild Editors

Apart from that there is also good discussion here:

http://drupal.org/node/24073

http://drupal.org/node/285369


The page prefix is meaningless, it can be changed by the user and can be anything.

So you just want display.*.display_options.path.

It would match on other displays that have a path setting (e.g. REST or feed). If you want to avoid that, you add a second condition on display_plugin = page.


Does the Bootstrap 3 Theme for Drupal meet WCAG 2.0 and ATAG 2.0 standards?

As you can see in this bugreport: https://github.com/twbs/bootstrap/pull/11757 Bootstrap aims to be WCAG compatible. But it does not claim it already is. Also, there are a lot of WCAG guidelines that are not theme-only. The very first one:

  Guideline 1.1 Provide text alternatives for any non-text content so that it can be changed into other forms people need, such as large print, braille, speech, symbols or simpler language.

Obviously, theme cannot force you to comply with it.

Audit

WCAG is now, effectively, a part of law in European Union. This means that no one will claim to be WCAG compliant lightly, and specialized law / audit companies charge big bucks to give you a "WCAG compatible" document with their signature on it. From my experience, we talk about 4, 5 digits sums, if you need it for government cooperation purposes (like, you want to sell website to a city). Possibly more. Open Source projects hardly have funding for that, that's why you "did not find any information on the Bootstrap 3 page", and you will not in predictable future.

Pay from your own pocket, or use at your own risk.


How to get all parent menu items' titles of the current node?

Even shorter using the MenuActiveTrailInterface.

$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    $breadcrumb->addLink(
      new Link(
        $menu_link_manager->createInstance($value)->getTitle(),
        $menu_link_manager->createInstance($value)->getUrlObject()
      )
    );
  }
}


Bakery decouples the multisites — if you're sharing a table, you must use exactly the same Drupal version on all sites in the multisite configuration, and update them in lockstep.  With Bakery, the Master and Slaves can be running different Drupal versions.  Additionally, any modules that modify the users table on the Master site would need to be applied to the Slave sites with corresponding settings.

Bakery improves scalability — user accounts are not created on slave sites until they are needed, conserving server computational and data storage resources.

Bakery synchronizes sessions — for example, if the user logs out of one Bakery site, the user will be logged out of all Bakery sites in that group.  (To achieve equivalent behavior with shared tables, you'd also need to share the sessions table, which would further complicate maintenance.)


modified value in form_state but it is not being saved

Use

$form_state->setValue($key, $value);

In your case, that should be

$form_state->setValue(['field_total_payment'], $total_payment);


show images for taxonomy terms in referenced node

I beleive you can achieve this with the normal "Term reference" field, and a custom template file: field--field_my_custom_field.tpl.php in your theme folder which renders the image. You can access the value of your custom field through $items[$key]['#options']['entity']->field_my_custom_field where $key is the array index (if you have more than 1 value for this field, first item is index 0, second is 1 etc, usually you should just loop through the $items like foreach($items as $item) and then you can do $item['#options']['entity']->field_my_custom_field)

You may need to have a field.tpl.php (copy from root/modules/field/theme then duplicate it and rename the duplicate into field--field_my_custom_field.tpl.php) in your theme folder in order for it to work (or templates folder inside your theme folder, basically same folder as your custom field--field_my_custom_field.tpl.php) (Not 100% sure, but this was the case in Drupal 6)

API documentation for field.tpl.php

This may also come in handy: taxonomy-term.tpl.php

Sorry for unsure answer with a lot of unknowns, just trying to help :)


Externally Requesting Browser Test Created URL for Relaxed Replication

I found the answer. To target the current test instance in a request one needs to set the http  client user agent header to drupal_generate_test_ua(drupal_valid_test_ua()).


how to update price from front end in ubercart product in drupal 7?

This functionality isn't built into Ubercart. In order to do something like this, you're going to have to implement your own custom form to manipulate the options data, or, better yet, invoke uc_object_options_form (the options form display on node/$nid/edit/options) with drupal_get_form().


if I understand you correctly, I think you should look at preprocessing the VBO form. You can then theme it as you would any other form.


Save and preview differences in hook_form_alter()

First, you should use #access = FALSE which will disallow access to a element. #type hidden is not safe, it means that it is printed as a hidden input field which can be easily changed by the user, for example with Firebug.

When you do that, you can also directly set #access on the field element, like $form['field_versio']['#access'] and it will disallow access to all subelements (if there are multiple).

Not sure why it doesn't work in Preview, try adding a drupal_set_message('test') call to see if your hook is called.


How can I show field from profile2 instead of username depends on user's role?

You can show an alternative name using the Real Name module.

However, you can't show one field for employers and a different field for applicants with Real Name out of the box.

What I would do is reuse the field_real_name in profile_employer and change the label to the company name; this will allow you to use field_real_name as a token for both employers and applicants.

In Drupal, you generally want to reuse fields across content types instead of making new fields if the uses are similar. Doing so makes it much easier to use modules like Real Name, Views, and Rules to manage your entire site.


How do I programmatically use an external database?

Setup the external database on settings.php
Select the correct database

$con = \Drupal\Core\DatabaseDatabase::getConnection('default','my_other_db');

I took the example from
 http://www.drupal8.ovh/en/tutoriels/175/use-multiple-databases-drupal-8.


Alter content translation page access based on content's field value

I think something like that already has been answered before:

Could you take a look and tell us if that helps you ?

https://drupal.stackexchange.com/a/208817/8375

Other outside resources: https://www.previousnext.com.au/blog/controlling-access-drupal-8-routes-access-checks


Missing argument in hook_theme and Ilegal offset

That function is taken from Drupal as an implementation of hook_custom_theme(), not hook_theme(). Since the former doesn't get any arguments, PHP is complaining about the function declaring arguments for which it doesn't get any value.

The fix is changing the short name of the module from geocoder_custom to geocoder, for example.


Converting static site to Drupal 7 - How to set-up department sites?

I think multisite is not the optimal solution for you. With a multisite installation, you will end up with completely separate sites that have their own content, categories, users, settings, user files etc. etc. In my experience, that is often too much separation for a site like yours.

For instance: With multisite, if one person needs to get access to two or more departments, you need to create a user account for him in each site. He will also need to login in every site. Another example: With multisite, it's not easy to take content from a department site and promote it to the main home page.

In your case, I would look into a solution built with Workbench and Workbench Access, or perhaps Domain Access. With those modules, you will end up with a system that is technically a single site, but where Drupal is configured to split the site into sections and control user permissions on a per-section basis.


Javascript running twice when not logged in

I finally found out what was causing this issue. It was a module named Drupal for Firebug.
So, if anyone finds this, disable this module and you will be fine.


|slice filter does not work with special characters

Actually the culprit is |striptags

  The problem with using twig's |striptags is double encoding of html entities,
  not markup, so & becomes & and then &amp; – Berdir

  source: How do I get the raw field value in a twig template?

If your setup relies on you running striptags last, you will need to do this all of this magic in a preprocess function with php setting a variable here and then printing your formatted variable on twig.


How to set the sizes for image thumbnails

These are the same settings as for your normal image styles. You can manage them here: admin/config/media/image-styles. Klick on edit on the rhs, then "override defaults", then edit the effect.


How do I alter the path of an uploaded image/file such that it includes the path of the node I attach it to via an image field?

Seems you are looking for a File (Field) Paths module:

The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

Be aware that it's not yet stable. Test intensively before using in production environment. On the other hand, I don't know anything better and I know for a fact it may work all right.


By default it provides a way to pass the term from current node and not from user. But there are two different ways to do this :

By Custom Code : Get the term id using $user variable and pass term id to the views_embed_view function which is used to render the views.
Create two views :

First view : User list with contextual filter term field that is added in account settings.
Second View : User view with contextual filter uid that filters the
current logged in user.

-- In field section add term id field and
exclude it from there.

-- Next field would be the first view  which
prints the list of users by taking the term argument.

-- Pass the token
of tid in argument section of view field.

To add a views as a field you need a module : Views Field View.


field slideshow module and image field caption

Did you try this particular patch? Do you use 'Long text' field? I think that this patch doesn't work with standard 'Text' field.


Can I search Taxonomy terms within display suite

What do you mean by search?

You can apply ds layouts to taxonomies


Content teaser view, Read more shows only in admin mode

The "Read More" link is part of the contextual links for each post. So, you need to simply tell Views that you do not want the links shown.

Go to: Format, Show, Teaser (the first image you showed in your question).
Under the dropdown for "view mode", you will see a checkmark for Display links. Uncheck that and they should disappear.


How do I include a required context in a ctools content type plugin?

You can define the required context in the plugin definition array. Use the 'required context' key and the ctools_context_required class.

Here are a few lines of stripped down code you can find in the CTools Plugin Example module:

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t('Simplecontext content type'),
  'description' => t('Simplecontext content type - works with a simplecontext context.'),
  'required context' => new ctools_context_required(t('Simplecontext'), 'simplecontext'),
);


How can I load comment IDs using the comment type?

I itself got the answer i just guessed the name to be passed in condition.

$cids = $entity_manager
    ->getStorage('comment')
    ->getQuery('AND')
    ->condition('entity_id', '25364')
    ->condition('entity_type', 'node')
    ->condition('comment_type' 'post_trp_comments')
    ->execute();


How to insert records in different table

if you wants to simple insert the field values in a different table you can write insert query in form submit.

 function lawyer_register_form($form,&$form_state)
{
$form = array();
$form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
);

$form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,
);

 $form['fname'] = array(
 '#title' => t('Full Name'),
 '#type' => 'textfield',
 '#size' => 20,
 '#maxlength' => 20,
);

 $form['phone_no'] = array(
 '#title' => t('phone_no'),
 '#type' => 'textfield',
 '#description' => t(''),
 '#size' => 20,
 '#maxlength' => 20,
);

$form['street_address'] = array(
'#title' => t('Street Address'),
'#type' => 'textfield',
'#size' => 50,
'#maxlength' => 100,
);

$form['county'] = array(
'#title' => t('County'),
'#type' => 'textfield',
'#autocomplete_path' => 'lawyer_register-autocomplete-engine',
'#size' => 20,
'#maxlength' => 20,
 );

$form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1,
 );

 $form['submit'] = array(
  '#value' => 'Submit',
 '#type' => 'submit'
 );
 return $form;
 }

    function lawyer_register_form_submit($form, &$form_state)
         {
         $username = $form_state['values']['name'];
         $new_password = user_password();
         $edit = array(
          'name' =>  $form_state['values']['name'],
          'pass' => $new_password,
          'mail' => $form_state['values']['mail'],
          'init' =>  $form_state['values']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_first_fname' => array(LANGUAGE_NONE => array(array('value' =>     $form_state['values']['fname']))),
          'field_first_street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['street_address']))),
          'field_first_phone_no' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['phone_no']))),
          'field_first_county' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['county']))),
          );

    user_save(NULL, $edit);
$user_id = db_query("SELECT uid FROM {users} WHERE name = :username", array(':username' => $username))->fetchField();

        $insert = db_insert('table_name') // in which table you want to insert
                  -> fields(array(
                        'uid' => $user_id,
                        'fname' => $form_state['values']['fname'],
                        'country' => $form_state['values']['country'],
                        'phone_no' => $form_state['values']['phone_no'],
                       //write other fields you want to save
                        ))->execute();
                }


Show translated content in view listing page when accessing translated site

Have you added a filter to the view for the translation language?

You should be able to set one to only show content in the language of the current page (Which should be welsh if your language detection is setup and working correctly)


How can I create menu links to external URLs?

mymodule.menu_external_link:
  title: 'External link'
  url: 'https://www.drupal.org'
  menu_name: main
  weight: 10
  options:
    attributes:
      target: _blank
      class: my-class


What are some examples of filter Correct faulty and chopped off HTML?

In Drupal, there is rule that a text filter should never change anything that the user saves.  The "Correct faulty and chopped off HTML" follows this rule. That is why you don't see any changes in the body field when you edit.

However, the filter will fix your HTML when the text in the body field is rendered (i.e. displayed to the user).

For instance, if you use the Drupal 6 or 7 "Filtered HTML" text type (which makes use this filter) and put the following faulty and chopped off HTML in the body (this is all you put in the body of a node):

xyzzy

and examine the rendered HTML in your browser (for instance using Ctrl-U or Firebug in Firefox), you'll see that it is corrected to:

xyzzy

Screen shots

Text in editor:

Rendered text, as displayed by Firebug:


How to prevent CKEditor from removing content and tags written in source?

I had the same requirement, I followed this tutorial for that, How to Display Icons in Drupal using Icon API.

It needs two modules (1) Fontawesome and its dependencies Library module & Fontawesome Library. (2) Other module you need is Icon API which has sub-module Icon_filter that will convert the icons in the images.

I am afraid that Icon API module will work for D8 or not, but it has D8 version but unstable as you can see on the module page.

I am using this way on D7 site.

Update: Filter setting


How do I add a CSS class to a p tag in CKEditor?

Using WYSIWYG/CKEditor in Drupal, you can add classes in the UI and they will show up in the Style drop down.

In the CSS tab of the WYSIWYG Profile you are editing:

You need to have the "Font style" plugin checked off in the config.

Now any element you add here can have it applied, so you would add:

Center P Tag=p.text-center

line to this config.

Then, add some text in the editor, and highlight the text (CKEditor should automatically wrap regular text with a p tag). You should then see the option in the drop down as "Center P Text". You will only see these options available when you've highlighted elements that are applicable. It will then apply the class to the highlighted element, the p tag.

I use this all the time to add classes to various elements just as you are trying to do.


Customise Drupal 7 Taxonomy View / Template (without module)

As described in Drupal 7 Theme Hook Suggestions, the template files that Drupal looks for a taxonomy term page are the following:

taxonomy-term--[tid].tpl.php
taxonomy-term--[vocabulary-machine-name].tpl.php
taxonomy-term.tpl.php

Replace [tid] with the taxonomy term ID, and [vocabulary-machine-name] with the machine name set for the vocabulary. Supposing that the machine name is programming_languages, then the template filename that Drupal looks is taxonomy-term--programming-languages.tpl.php. (The underscores are replaced with hyphens.)

The first file that is found is the one that Drupal uses.


Drupal 7 website with landing page and two sections with different templates

These sites look almost identical. In fact, I would say that given the pictures, the layouts are close enough to use the following templating strategy:

In Drupal, it's very easy to create a front page that will be your landing page. You will simply create a template file called page--front.tpl.php and put whatever html you want in here, exactly like you want to lay it out. This will be what people see when they come to example.com/

I know we keep calling these 'sites' but they are pages instead. Indeed 'site-a' and 'site-b' will be two 'Basic Pages titled 'Civil' and 'MEP'. In my mind these are so close I would simply have have one layout template (page.tpl.php) with the same regions, etc.  It looks like the only difference is in the content. So, to handle that I would use blocks and Drupal's default functionality to force blocks to appear on one page and not others.

So far you would have to templates - page--front.tpl.php for the home page and page.tpl.php for all other pages. In the event you indeed wanted to have a different layout for pages Civic and MEP you could even have templates for these. If Civic had a node ID of 3, for example, and MEP of 4, the template names would be page--node--3.tpl.php and page--node--4.tpl.php.  Please see the Drupal theming guide for more details.

Site-a menu and site-b menus:

You will have two menus created for site-a and site-b. There will be blocks for each in the Blocks section under structure. You will put both blocks in the same region (say, 'menu-region' if that's what you decide to call it). Then, edit one block to 'appear only on the following pages' and type in:

site-a
site-a/*

Then, edit the other block to 'appear only on the following pages' and type in:

site-b
site-b/*

Drupal will automatically know which menu to load. Also, each of these blocks will have their own css tags in the markup, so it will be easy to style them.

For the other sections, you would repeat the process - add all the blocks you need to appear in one regions, but edit them to show or not show based on what site (page) you are on.


The function votingapi_add_results() is responsible for writing records to the votingapi_cache table. Immediately afterwards, it invokes hook_votingapi_results() which any module can use to wipe out the table.

For example:

/**
 * Implements hook_votingapi_results().
 */
function MYMODULE_votingapi_results() {
  db_truncate('votingapi_cache')->execute();
}


Try the Shortcode module. It was the among the first hits when I searched for Drupal 8 shortcode.

For the second part of your question I'd recommend Insert View. You can embed a view via a short code in your content and also pass arguments to it.

  Insert View is a filter that allows users to embed content lists
  generated by the Views module into node bodies and blocks using
  relatively simple tag syntax.

  Why would you want to use an Insert View tag when you could just
  invoke a view using PHP? Simple. When you want to allow users to
  insert views or edit content on a page with an inserted view without
  granting them permission to use PHP.

  The tag syntax is [view:name=display=args]

  The parameters are: view name, view display id, view arguments.

  Valid examples:

  [view:my_view] is replaced by the content listing.
  [view:my_view=my_display] invokes the view using the specified display.
  [view:my_view=my_display=arg1/arg2/arg3] invokes the view using the specified display and passes arg1, arg2 and arg3 to the view.
  [view:my_view==arg1/arg2/arg3] passes arg1 to the view and will use the "default" display set for the view.


Turn off template suggestion for specific fields

As it seems, that there is no solid alternative that works for field values I have written a Twig-Filter which returns the value via this php function:

public function removeHtmlComments($string) {

  $output = preg_replace(array('/<!--(.|\s)*?-->\s*/', '/\t+/', '/\n+/', '/[\r\n]/', '/[\n\r]/'), '', $string);

  return $output;
}


How can I access webform submission values from webform-confirmation.html.twig

You can access submissions using 'webform_submission' variable. I know the webform-confirmation template file doesn't mention that variable but, if you look closely to the controller you see there additional variable being passed to this template.

N.B on your form setting make sure to set confirmation type to be "age (redirects to new page and displays the confirmation message)"

And always the latest one on the array is your last submission.


How to load a entity or node in form builder class?

You need to make it an optional argument. Annoying but unavoidable workaround with the current design.

And to have it already upcasted to a node, you need to name your variable {node}.


Be sure that you added the sell price of product and after that in product feature add recurring fee ammount of 2$.


This is already built-in in Drupal 6 and 7, in the function node_validate.

The relevant piece of code is reproduced below:

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done. The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.

This warning message serves the same purpose as locking, but IMHO it does it better and less prone to deadlocks.

The problem with an outright lock is that users may open a node edit page but don't actually do any edits.  If they just abandon it (i.e. don't press "Save") it will remain in that state until reset.  Doing it on save is better because it avoids the deadlock situations that may arise from locking something the user may abandon.


How can I promote content by number of hits (reads)?

The near defacto solution for this is the Radioactivity module:

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.

As opposed to straight pageviews, this uses an algorithm to take activity-over-time into account.  With straight statistics / counts, an old page with low activity per day can perpetually stay at the top of lists because it slowly accumulates statistics.

Radioactivity takes time into account, so that your newer pages can appear at the top when appropriate, and then roll off at the appropriate time.  It relies on Rules, but integrates nicely with Views, for building the lists of things (either pages or blocks).


Why is $base_url = http://{$_SERVER['SERVER_NAME']} in settings.php? Will this cause any problems?

If the site is served by a single application server and that name will never change, then this isn't wrong, but not the way I would do it.

If you want to use SERVER_NAME and avoid issues if it's not initialized:

$base_url = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';

Or, instead of empty quotes, specify the server name if it doesn't change.


How do I display the products and nodes of the same author in the current page?

The trick is in the relations and contextual filters.

You need to add a relation to the Author and then another relation to Product using the Author as a relationship, then go to add a Contextual filter Content ID (Provide default value [Content ID from URL]) and use Product as Relationship.

Something like this:


What does "Prefetch views unpack data" in APDQC module do?

Really depends on your workload. In some cases having all of the views data prefetched is faster, in other cases it's slower. If you have 50+ views then it's best to leave it off, if you have just a couple views, turning it on is faster.

Side note: I created the patch for creating this cache in views, now I wish it was prefixed by the view name so prefetch would be easier.


You can use Commerce Custom Offline Payments to handle this.


Can't get hook_field_attach_view_alter to set the value of the field

Ok, I found the answer: the key "#items" in the output array needs to have an array with an array as the value - not just the array:

$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => '&nbsp;'),
  );

becomes

$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(array()),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => '&nbsp;'),
  );


Using an address field widget on a custom form and storing data

You can limit the $form array's elements by setting their #access property to FALSE.

The validation and storing should be handled by the form for the corresponding entity by itself.


You can try to check if array element exist before assigment, and only if so, assign it, an this way avoid undefined offset:

  if (isset($node->field_addendum['und'][$i]['filename'])) {
     $variable1 = $node->field_addendum['und'][$i]['filename'];
    }


The easiest way would be to use entity_load()

$nodes = entity_load('node');

If you don't provide the second argument ($ids) it will load up all entities of the given type:

  $ids: An array of entity IDs, or FALSE to load all entities.

Just for the sake of completeness node_load_multiple() doesn't require the $conditions parameter so you could also grab all of the node ids from the database

$nids = db_query('SELECT nid FROM {node}')->fetchCol();

And then use $nids to load the nodes:

$nodes = node_load_multiple($nids);


How to create a full project on drupal.org?

For promoting the sandbox module to full project requires for going through a one time review process.

Check:
Apply for permission to create full projects

Before creating an issue for the promotion, make sure you go through the project application checklist to get good reviews.


This might not be the best way, but I had this same issue today. I ended up renaming language.entity.en.yml to include .OLD at the end of the filename for a backup, then I re-ran drush cim. After that it accepted my system.site.yml file. Then I took a look at the language.entity.en.yml file and for some reason it had the exact same UUID as the system.site file. I suspect the import is confused about which file is which because they both had the same UUID.


How to Execute a Specific Part of a Function

If I'm reading you right you're asking a basic program flow-control question.  In PHP, like most programming languages, you can use flow control statements like switch and if to only execute certain blocks of code, or move some blocks into separate functions.

Since it's your own function you're calling here it completely up to you how to handle it. As you gain experience you'll learn ways to determine what to separate out into unique functions and what to just use if statements to control.

To use an if statement, you'll probably need to add a parameter to your function to let you determine which pieces to execute.