Looking for a strategy to optimize a big body field on a node

Using the Paragraphs module is probably the current go-to solution for a more manageable setup than a large body field. Functionally, it's right in between a single text field and completely separate nodes. It enables you to create more manageable chunks of content that replace the traditional body field. Each chunk can be simple text, or more complex things. Each "paragraph" is an entity with fields, and the node references those entities. When editing, it feels like a more focused interface. The content creator stays on the node, so the complexity is hidden in the background.

Another strength it has is good support for revisions. In fact, it requires the Entity Reference Revisions module, and its project page suggests using the Diff module.


What is the equivalent of theme_menu_item in Drupal 7?

Looking at the function that called the theme function theme_menu_item() (menu_tree_output()), and comparing it with the Drupal 7 version of the same function, I can say that the equivalent of theme_menu_item() is theme_menu_link().


Image-clicking Q&A captcha alternative that is customisable?

Here's one option I've found - Fancy captcha - based on a library which uses icons. Looks like a simpler stack than Confident Captcha, but no stable release on D7.

Pros:

Based on a re-purposed library installed locally, so you can modify the files
Doesn't require a third-party service

Cons:

No stable non-dev release yet (at time of posting)
I can't see any evidence of an accessible fallback for screen readers etc


I hope I understood correctly:

FileItem.php

Have a look at public static function defaultStorageSettings() and public static function schema(FieldStorageDefinitionInterface $field_definition)


How do I get the current path and add a condition in page.html.twig?

Try this

{% if 'location/all' in url('<current>')|render|render %}

Alternative solution would be to add the following to your THEMENAME.theme

function THEMENAME_preprocess_page(&$vars) {
  $vars['path'] = \Drupal::service('path.current')->getPath();
}

and use this in your page.html.twig

{% if 'location/all' in path %}


How to get a specific field in a table layout in Views templates

@Chaulky it should be pretty easy to make the changes suggested by @enhance.

Take the views table template and copy it to your theme.
Make the edits to your copy of the template as per @enhance's directions.
Since you mentioned adding classes, you could either add the classes in the template or in the views interface.
Save it as views-view-table-YOUR_VIEW_NAME.tpl.php.
Clear caches, at least twice if once didn't do it.
Continue theming and enjoy.


How to, in a View, get list of links up against each other (concatenated without line breaks when displayed)?

Under Format click on settings and uncheck Add views row classes and uncheck Add striping (odd/even), first/last row classes

Edit:

You could use html list instead of unformated list.

Then use css to add the comas see JS Fiddle

or

since you added the commas's manually you could display inline or float left see this answer


Assign unique IDs to HTML elements via twig file

Copy /core/themes/bartik/templates/classy/navigation/menu.html.twig
and modify a bit:
{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see https://twig.symfony.com/doc/1.x/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% set count = 1 %} {# <------------------ Added #}
    {% for item in items %}
      {%
        set classes = [
          'menu-item-' ~ count, {# <------------------ Modified #}
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
      {% set count = count + 1 %} {# <------------------ Added #}
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Result

Then you can do, Ex: #menu-block-id .menu-item-1 { border: solid green; }


How to Restrict views Date popup to only year/month

You'll need a external library to do that. Something like jQuery UI Month Picker Plugin and you'll probably will need to use a textfield rather than date.

OR

Use the Month Year module

  This module provides a month year field type.


Can Apache Solr Search allow a user to search 'within' current results?

This is from my experience using Database Search not Solr but it might work.

I'm also not sure it's exactly what you're looking for but it might be a starting point.

Clone your view, but keep the URL the same.

This allows you to run two exposed forms both of which re-direct to the same view. So I have one on my homepage and then one on my search results page. When you search from the home page the values are automatically populated into the second exposed form when you land on the results page.

Because the exposed forms are different this means you can show more fields on the exposed form on the search results page and because it remembers the first search, technically, you're searching within the original search.


Reading the documentation for hook_link_alter() I find the following sentence.

  Perform alterations before links on a node or comment are rendered.

The hook implementation you are using is missing the last argument: the definition of the hook given by the documentation is hook_link_alter(&$links, $node, $comment = NULL).

Looking at the code of comment_render(), which is the function that renders all the comments of a node, you can notice that hook_link_alter() is invoked right after the data is loaded from the database (and after hook_link(), of course).

if ($comment = db_fetch_object($result)) {
  $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
  $links = module_invoke_all('link', 'comment', $comment, 1);
  drupal_alter('link', $links, $node, $comment);

  $output .= theme('comment_view', $comment, $node, $links);
}

hook_comment is invoked from theme_comment_view().

if ($visible) {
  $comment->comment = check_markup($comment->comment, $comment->format, FALSE);

  // Comment API hook
  comment_invoke_comment($comment, 'view');

  $output .= theme('comment', $comment, $node, $links);
}
else {
  $output .= theme('comment_folded', $comment);
}

hook_comment(), which is invoked with a call to comment_invoke_comment(), is not called for comments that are not visible.

The implementation of hook_link_alter() you created should at least check which comments it is altering, if it is supposed to alter only specific comments. At least, it should check the last parameter ($comment) is not NULL; if that happens, the hook is invoked to alter node links, which is not what you want as you need to alter comment links.


I searched for SORT CRITERIA to sort by last modified date there is a field named "Content revision: Updated date". This field helped me to sort by modified date.

Credits: @ismini (for posting the comments that helped me).


Drush does not support such a feature, but it sounds like it would be an interesting enhancement.


Simplenews does not apply templates and does not resend

About You Second Issue - Here is a "dirty" solution.

Go to phpMyAdmin and find simplenews_newsletters table
Edit that table and change s_status on the newsletter you want from 2 to 0.

s_status - 2 Newsletter has been sent

s_status - 0 Newsletter has not been sent

s_status - 1 Sending Newsletter


You can use node--[content_type].tpl.php for changing the output for view mode.

if ($teaser) {
  // node is being displayed as a teaser

} else {
  //all other cases
}


How to disallow users with certain emails form posting?

You can create an access rule and deny creating an account or logging in with an account that matches certain criteria.

Go to admin/user/rules and add a new rule. In your case, the access type should be deny, rule type should be e-mail, and the mask can be '%@blablamail.com' for instance. You can test your new access rule by clicking on the Check rules tab afterwards.


You are looking for responses. For example, in a controller, you can return a renderable array, a Symfony Response object, or specific responses (AjaxResponse, JsonResponse) to respond to the request.

For example, AjaxResponse in the docs, and here is an example of a controller responding with it:

https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8


Drupal website goes offline every 2 days for 15 minutes

Drupal can be configured to use a "poor man's cron" (exectuting jobs after a normal visitor's HTTP request). If you have access to the Drupal Admin UI, check Admin > Reports > Recent log messages, this is a core module helpful for debugging (it might be disabled though)


To translate the tokens in their values, you can use:

token_replace

e.g:

$nid = token_replace('[node:nid]', array('node' => $node));

You need to be able to pass the required parameters for that token, e.g $node for node tokens.


How to get the label values for list fields in Twig?

There are a few ways:

It calls List allowed values and it stores in the field configuration.

When field cardinality is 1

  {% set list_value = node.filter_list.value %}
  {{ node.filter_list.getSetting('allowed_values')[list_value] }}

When field cardinality is more than 1

  {% set allowed_values = node.filter_list.getSetting('allowed_values') %}
  {% set list_values = node.filter_list.getValue() %}
  {% for list_value in list_values %}

      {{ allowed_values[list_value['value']] }}

  {% endfor %}

In case when your template is node.html.twig you can render it based on field formatter in your view mode.

  {{ content.filter_list }}


Set Generate automatic URL alias during import in Taxonomy

use views bulk operation module and then you can update nodes or taxonomy on the fly via view....

I have the same problem now for nodes...


How can render a Block on a Contact form Page

Following the logic exactly as you have laid it out, you could test for

if (arg(0) == 'contact')

to output the block on the contact page. However, is there a reason you're not using the block admin page to place this block instead? Other options here that might be easier to maintain would be:

place the block in the region you want using the Context module
copy the page.tpl.php file from your theme to page--contact.tpl.php and add your block content there


Start with upgrading to Drush 8 ... see http://drush.org/en/master/install


Drupal7 template suggestions for node is not working

Your usage is right.Check your code in detail!


How to make my site's categories appear in Google results?

Drupal is fantastic for building SEO sites but still I think you can not do this.
Google does this.
The official source is:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=47334


How to pass an array from module to template file?

In form.

/**
 * Implements hook_theme().
 */
function YOURMODULE_theme() {
  $themes = array(
    'example' => array(
      'template' => 'templates/example',
      'arguments' => array('data' => NULL),
    ),
  );
  return $themes;
}

after this you can pass your data as

  return theme('example', array('data' => $data));

Refer this

And if want to use preprocess to alter data, see hook_preprocess_HOOK


How to reduce BARCODE FONT in barcode module?

Add this to your theme css file, in /sites/all/themes/yourtheme/css

.barcode { font-size: 10px; }


Is there any technical reason why we now should put third-party modules in the [docroot]/modules folder?

Technical? Not really, it isn't faster or anything like that.

It's basically about Developer/User Experience. It's 2 clicks less to go there and find a module.

Also, there multiple issues to either drop multisite entirely (although most people disagree with that) or not exposing it by default and just have a settings/settings.php by default.

Move settings.php to /settings directory, fold sites.php into settings.php
Discuss whether to deprecate multisite for removal in 9.x


Module to cache URLs commonly request by bots?

You can alter the fast404 code inside of setting.php to handle this. It will handle *.asp & *.pl; changing the regex so it handles paths like

/postnuke/article.php
/wp-content/
/mailman/
/phpBB/page_header.php

Can be done by replacing this

$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

with this

$conf['404_fast_paths'] = '/^(postnuke|wp-content|mailman|phpBB)|\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

All i did was add ^(postnuke|wp-content|mailman|phpBB)| to the start of the string, right after the first /. This means that if any path starts with any of these strings we'll skip booting drupal and 404 right here taking very little server resources.

To enable fast404

  Go to the sites/default directory. Open up to the setting.php file.
  Around line 500 uncomment this drupal_fast_404(); by removing #

Source: https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.g385c64257_0178

If you have dblog enabled you can run this query to find what paths are the worst offenders

SELECT
  COUNT(*) AS count,
  watchdog.*
FROM watchdog AS watchdog
WHERE type = 'page not found'
AND message NOT LIKE 'sites/all/%'
AND message NOT LIKE 'sites/default/%'
AND message NOT LIKE '%/styles/%'
GROUP BY message
ORDER BY
  count DESC,
  wid ASC


It is fairly common practice to use symlink on web server. You might also see it on your private folder so that I can be hosted on a NAS or AWS EFS for example.

Symlink should work regardless of the web server you use as they are specific to the server operating system and not to the web server by itself.


Using git over ssh from localhost to my Shared Hosting

Perhaps you are looking for

git clone ssh://username@63.23.133.162:portnumber/~/public_html/drupal

Note the ~ which is indicating that the public_html resides in your home directory.


Even when Display Suite is enabled, you need to set a layout for it to be enabled for that particular content type. If you just want one column you can select the "One Column" and it will add all the fields available with Display Suite.

It should look something like this:


I get this error after changing the minimum version of drush/drush to ~9.0 in my composer.json and running composer update drush/drush afterwards.

I solved it by just executing composer require drush/drush:~9.0 which lead to the error message drush/drush 9.5.x-dev requires symfony/config ^3.4, so I had to execute composer require symfony/config:^3.4 before composer require drush/drush:~9.0 could be finished successful.

Don't know if this is the only way or best practice to solve such a dependency conflict but in short this worked for me:

composer require symfony/config:^3.4
composer require drush/drush:~9.0


How do I check if a link exists in a page?

To answer my own question, I realized (even without clicking on the link) that fields can be asserted by DrupalWebTestCase::assertFieldByName().


I'm not sure about D8, but for a D7 site I would read the XML file within a hook_form_alter() function, and use this to select enabled or disabled each form element depending on the rules set forth within the XML.

Of course as lovely, or convoluted as that sounds, it's a pretty nasty performance hit to show a form so caching would be important here.

I hope I understood your question correctly.


The view is not filtering the duplicate nodes

You can handle most duplicate node issues using Views Aggregation options.

Go to advanced in the view and select "Use Aggregation"

Then in the fields area, set the aggregation settings.  Generally, you just want the group together option with Entity ID as the group column.  Sometimes you have to play around with other settings as well.


What is wrong with your code is that the code that outputs the content of the block needs to be executed, such as:

$block['content'] = test_get_block_content();

This code makes sense if the code needs to output something in the page; if the code that needs to be executed doesn't need to output anything in the page, then hook_exit() is always executed, even on cached pages. The documentation for that hook reports the following text:

  Only use this hook if your code must run even for cached page views. If you have code which must run once on all non cached pages, use hook_init() instead.

As for redirecting a user, you can look at what the Redirect module does to redirect a user. The purpose of the module is to redirect a user basing on the currently visited page, and on settings decided from an administrator user. The code that redirects the user is contained in this function, which is the implementation of hook_init():

/**
 * Implements hook_init().
 */
function redirect_init() {
  if (!redirect_can_redirect()) {
    return;
  }

  $current_path = current_path();
  $current_langcode = $GLOBALS['language']->language;
  $current_query = drupal_get_query_parameters();
  if ($redirect = redirect_load_by_source($current_path, $current_langcode, $current_query)) {
    redirect_redirect($redirect);
  }
  // …
}

The redirect_redirect() function is a wrapper for redirect_page_cache_clear().

function redirect_page_cache_clear($redirect = NULL) {
  if (!variable_get('redirect_page_cache', 0)) {
    return;
  }

  if (isset($redirect)) {
    $path = url($redirect->source, array('absolute' => TRUE));
    // Use a wildcard to catch paths with query strings.
    cache_clear_all($path, 'cache_page', TRUE);
  }
  else {
    // Clear the entire page cache.
    cache_clear_all('*', 'cache_page', TRUE);
  }
}

If you would implement a way to redirect a user through drupal_goto(), you should consider implementing hook_init() in a similar way.


How do I enable a REST resource for a custom content type?

sorry my english is not very good

If you want to access these types of content separately, you must do the following:
1) download the module restui: https://www.drupal.org/project/restui/releases/8.x-1.x-dev

2) Go to Extend, activate modules, HAL, HTTP Basic Authentication, RESTful Web Services,
Serialization, REST UI.

3) go to the path: / admin / config / services / rest

4) Edit the RESOURCE NAME Content, and mark all the checkboxes.

5) you should perform a test in the browser with the following path: drupal8 / node / 1? _format = json

note: if the information is displayed, it means that the rest server is set correctly.

6) Create a view and select the type of content you want to display and in the "REST EXPORT SETTINGS" section mark the "Provide a REST export" checkbox and in "REST export path" type "car_makes".

This way if you go to the route: "/ drupal8 / en / car_makes" you will see that it will show the information in json format.


Firstly, why template.php for reordering the fields of an entity edit form? You should put this logic in a module and not a theme, look up hook_fomr_alter and hook_form_FORM_ID_alter.

Secondly, if the profile is the default user profile in D7 or you have created one using profile2, you can go to the manage fields section of the entity and reorder the fields just by dragging them. That should change the order on both view page and edit page of the entity, no?

Can you try it out and see if it works! You might not need to write code at all!


Why are URLs with non-existing subdomains not triggering an error 404?

While you have stated that hosting is the same for both your sites it is most probably that this is either a server configuration issue or a DNS configuration issue rather than a Drupal setting issue.
In .htaccess the following catches 'wildcard' subdomains

RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

In Apache configuration the following catches 'wildcard' subdomains

<VirtualHost *:80>
        ServerAlias *.example.com
        Redirect 301 / http://www.example.com
</VirtualHost>

In Nginx confiuration the following catches 'wildcard' subdomains
(as you are using .htaccess you are obviously not using Nginx but for completeness..)

server {
  server_name *.example.com;
  return 301 $scheme://example.com$request_uri;
}

server {
  server_name www.example.com;

  #add in further directives to serve your content
}

These are the most common configurations that will catch wildcard sub-domains on the server.

It is possible to do redirects in settings.php also but not for wildcard.

The other possibility is that the issue is at the DNS entry. You may have set up a wildcard sub-domain which may also be known as a catch-all-subdomain.

The layout of this will be determined by your DNS provider.
This Drupal guide illustrates how it would be acheived on cPanel: https://www.drupal.org/node/1068894


Any reason why you are not using the module cas? It seems like a fairly stable module with over 5000 people using it. I would give that a shot before attempting any custom code in hook_init().


It seems you're trying to override output of a field in Views using information from one of the fields.

If you turn on the option to Output the field as a link, you shouldn't include the anchor HTML <a href="..., Drupal does that on its own when you turn this option.

If you want to control the HTML you shouldn't use the Output as link option. Instead enter your HTML into the Text area of the Rewrite field.

Or, if you want to use the Overwrite as link option only enter the HREF value into that field.

If we assume that the ID is a separate field then it needs to be added to the Views.

You can use the Exclude from display option if you don't want that field to be visible, but it must be present if you want to be able to use it.

Rearrange the order of the fields so the ID field is above the Map name field.

If the ID number is a part of the Map name field then you have the ID information already available as a token under Replacement patterns.

Edit the Map name field and open the Rewrite results option, then open the Replacement patterns under it. You will see a token for all fields available for that field. One of them will be the ID field. Copy that token and paste it into your HTML override, or the Link href (depending on which option you're using).

Save and check that your token is evaluated correctly and that the link/href is working as expected.


I was looking for an answer for hours... I thought I made a mistake, but it seems there is a bug in the Views module! I guess I'm not the only one with this problem, so I'd like to share the sollution I finally found.

Make a custom module and add these lines of code:

function mymodulename_views_query_alter(&$view, &$query) {
  // Fix bug where multiple terms in search index filter returns no results
  if (isset($query->relationships['search_total'])
      && !empty($query->fields['score'])
      && empty($query->fields['score']['table'])) {
    $query->fields['score']['table'] = 'search_total';
  }
}

The sollution was found here: https://drupal.org/node/1948510


Error during "composer drupal-update" for Drupal 8.0.5

There is a patch available here - https://www.drupal.org/node/2664274#comment-10954323, which is RTBC.

I can confirm it's working :)


Clearing the cache changes the nice menu every time

If you have turned CSS file aggregation off, changes take effect immediately unless you have an external cache like Varnish of the css file. If you are not seeing changes after checking this, maybe your CSS file is not included or the rules implemented is overridden by other CSS rules.


Auto fill billing information in cc avenue payment

Finally found the answer with help of this issue queue https://www.drupal.org/node/2310505

In commerce_ccavenue.module added few lines inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method)

$billing_address = $wrapper->commerce_customer_billing->commerce_customer_address->value();
  $order_data = array(
    'merchant_id' => $payment_method['settings']['merchant_id'],
    'amount' => $wrapper->commerce_order_total->amount->value() / 100,
    'order_id' => $order->order_id,
    'cancel_url' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'redirect_url' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'working_key' => $payment_method['settings']['working_key'],
    'access_code' => $payment_method['settings']['access_code'],
    'language' => 'EN',
    'currency' => $currency_code,
    'billing_name' => $billing_address['name_line'],
    'billing_address' => $billing_address['thoroughfare']. ' ' . $billing_address['premise'] . ' ' . $billing_address['sub_premise'],
    'billing_zip' => $billing_address['postal_code'],
    'billing_city' => $billing_address['locality'],
    'billing_state' => $billing_address['administrative_area'],
    'billing_country' => 'India',
  );

These lines are missing inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method). Works fine after adding those lines.


Permissions/access caching per node and per user

Access results can store cache metadata like cache tags and cache contexts. As a shortcut AccessResult has two specific methods to apply the correct cache metadata. Different membership in roles or a modified role results in a different set of permissions, use cachePerPermissions() to add a cache context for the hashed permissions. The second method is for the cache context of the current user cachePerUser().

If you get field data from a node or user, add addCacheableDependency($node) or addCacheableDependency($user).

See this example from the node module:

core/modules/node/node.module, line 938

function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node
    ->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account
        ->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()
          ->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account
          ->hasPermission('edit own ' . $type . ' content', $account) && $account
          ->id() == $node
          ->getOwnerId())
          ->cachePerPermissions()
          ->cachePerUser()
          ->addCacheableDependency($node);
      }


Can you elaborate on the error?

I just did a quick test and was able to add comment count to a view:

Go to the views admin page , click fields, add

  Content: Comment count The number of comments a node has.


How to set the permission for each file separately for downloading?

You have to set your site's file management to private, and then use a module or code your own management stuff using the files API.


Programmatically add items to the menu - not hook_menu

I solved this by just appending my links to the menu tree with hook_preprocess_menu_tree

<?php

function my_module_preprocess_menu_tree(&$vars) {

  if($vars['theme_hook_original'] != 'menu_tree__primary') {
    return;
  }

  $node = menu_get_object();

  //Check to see if this is a group node or group content and return the group_node
  $group_node = my_module_check_for_group_node($node);

  if($group_node) {

    global $user;

    $vars['tree'] = str_replace('last leaf', 'leaf', $vars['tree']);

    $result = db_query('SELECT menu_name FROM og_menu WHERE gid = :nid ORDER By weight', array(':nid' => $group_node->nid));

    $menus = $result->fetchAll();

    foreach($menus as $menu) {
      $tree = menu_tree($menu->menu_name);

      if(!empty($tree)) {
        // render the organic group menu as HTML
        $tree = drupal_render($tree);

        $tree = str_replace('menu nav', 'dropdown-menu', $tree);

        $menu_array = menu_load($menu->menu_name);

        //format
 and top-level  for bootstrap
        $li = '
'.$menu_array['title'].''.$tree.'
';

        $vars['tree'] .= $li;
      }
    }

    $vars['tree'] .= $li;
 }
 ?>


Pathauto taxonomy term alias for content paths

Pathauto taxonomy terms in content paths
there is a comment to the answer on this post that links to a drupal.org issue.

http://drupal.org/node/741914#comment-3714746
This is a patch for Token. It seems to be for an older version than the latest beta I've got installed... So I had to hand apply the patch to token.tokens.inc "by hand".

It gave me taxonomy for content paths. stuff like [node:term], [node:term:tid], [node:Term:vocabulary], etc.

I don't have files in front of me atm but I will post the token.tokens.inc later if need be. (would post the text, but it's more than the limit for a post here)

Token.tokens.inc - 7.x-1.0-beta


Migration failed with source plugin exception

I find when I get these errors it is because initially I make an sqlmap using an integer key -- then see I don't have an integer key and try to change it. The migration still expects the initial configuration of an int key. You likely have to clear it out as seen in this issue comment.

  Everything looks OK to me. Is it possible that when you initially
  defined your migration, you had an integer key in the MigrateSQLMap
  call? Changing the key in the code will not automatically change the
  associated tables. What you can do is:

  Rollback the AttSubject migration, so the map and message tables are
  empty.
  Drop the migrate_map_attsubject and migrate_message_attsubject
  tables.
  Run "drush ms". This should call the ensureTables() method and
  recreate the map and message tables using your ca_varchar1 key schema.
  Check the structure of the map and message tables and make sure
  sourceid1 is a varchar in both.

Also see this issue which describes the same problem and solution with more examples/details.


The few times i have had a similar issue i have resolved it by turning off 'Cache menu in client-side browser' on this page admin/config/administration/admin_menu


How can I remove the "Your vote was recorded." message in the polls?

The messages set with drupal_set_message() are saved in $_SESSION['messages'][$type] as an array of strings ($type can be "status", "warning", or "error"). The message you see, is set in poll_vote(), which is the form submission handler used for processing a vote, used from poll_view_voting(), the form builder for the vote form.

In order to remove the show string you should:

Implement hook_form_FORM_ID_alter() to add a form submission handler that is executed after poll_vote().
Implement the form submission handler to remove the string added from poll_vote().

Code similar to the following one should work.

function mymodule_form_poll_view_voting_alter(&$form, &$form_state) {
  $form['vote']['#submit'][] = 'mymodule_poll_view_submit';
}

function mymodule_poll_view_submit($form, &$form_state) {
  if (isset($_SESSION['messages']['status']) && is_array($_SESSION['messages']['status'])) {
    $messages = array_flip($_SESSION['messages']['status']);
    unset($messages[t('Your vote was recorded.')]);
    $_SESSION['messages']['status'] = $messages;
  }
}


Image re-sizing while uploading via drupal 7 dashboard

Follow the steps.

1) Add new image style from Configuration->image style

2) Go to your content type and Edit the image field

3) Select your newly created image style from the "preview image style" dropdown list and then save settings.

Now the images will be resized according to your created style.


Assuming an unchanged core codebase, and assuming you mean that your final line is returning a SelectQuery (not the db_or(), which returns a DatabaseCondition), the only way you could be seeing a SelectQuery is if you're inspecting the wrong variable, i.e. $filterSparten. The query will remain a query, you need to assign the results to something else:

$results = $filterSparten->condition($or)
  ->execute()
  ->fetchAssoc();

Inspecting $results should give you what you're expecting.


Path aliases not updating or setting automatically

The aliases are generated when you create an object in your site and are based upon the pathauto patterns (placeholders) you specify at:

For 6.x: Administer > Site Building > URL aliases, in the "Automated alias settings" tab.

For 7.x: Administer > Configuration > Search and Metadata > URL aliases, in the "Patterns" tab.

Pattern tab provides several default patterns that automatically alias the different content types.

Settings tab allows to refine length and case, as well as defining if an alias is to be replaced or added to the list.


You can try using the Domain access module that does the work. Version 8.x works with not issues. Go ahead and use it with no fear.


Render multiple taxonomy term input as unordered list

This may not fit your need exactly, but did you know that the Separator in the 'Multiple field settings' accepts html?

That means that you could use "
" as the separator, and they'll render on different lines, even if they are not in a list.

Would that be enough for your needs or do you need a list?

====================== Edit based on comments =======

Maybe just a simple css rule added to your theme then that places the break there for you:

.your-content-type .your-field-class a {
    display: block;
}

It looks, based on your comments, that the above example may be something like this for you:

.node-content-type .field-name-field-client a {
        display: block;
}

That should do it for you.  The 'block' (vs inline) display will put each link on a separate line.  If you do that, you can remove all the commas and other separators, or those will appear on separate lines too (because of the block display of the link).

** Note: I added one more selector (the content type selector) to make this rule even more specific.  Based on the rule above, this 'display: block' property will be applied only to nodes of this specific content type (so if you use this tag somewhere else, they won't just come out on separate lines unexpectedly).  Does that make sense?

To find what the content-type class for your node is, look into the page source again and find the line that looks like this:

The content type should be the second word in the class... in Drupal, all pages have the content type they belong to as a class, so that's awesome for theming!!

Finally, after changing your css, you may not see the result right away - you may need to clear your cache before your change will be applied.

Hope this helps!


As Eugene Fidelin said, we'd really have to have a better feel for the site in order to give you the best advice. It depends - will each gallery have the same fields for each entry? Or does one gallery have videos while another does not? However, I will try to do so anyway.

If there are only a few galleries AND they differ in their fields, I would create a content type for each gallery entry and use them to populate a page with a view. I would do this because otherwise you're going to have to create a single content type with each type of field used by every type of gallery entry, and then for each one you're going to end up having a bunch of empty fields since they are used by the other types of entries.

However, assuming each gallery entry across all galleries has the same fields for the most part, I would just create one content type for gallery entries and then use taxonomy terms and then just use radio buttons to specify what type each entry is (so you might have Animals, People, Places, etc.) and then have views for each type that just filters by the taxonomy terms.


How do I set the text format used in a message (from the Message module)?

You can set the permission for user role to use filtered_html or full_html in Administer -> people -> permission.


How do I add code to browse for a file in a Drupal Form?

I recently created a few custom blocks with image upload and preview fields. Here's the relevant code that should be helpful for you:

function mymodule_block_configure($delta = '') {
  // Uploaded image path is saved in a variable.
  $pic_path = variable_get('mymodule_pic1', FALSE);
  $form = array();
  if ($pic_path) {
    $form['preview'] = array(
      '#markup' => '<img src="'. image_style_url('mymodule_img_preview_style', $pic_path) .'" alt="'.t('Preview').'" />',
    );
  }
  // Image upload field.
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Upload image from your computer'),
    '#description' => t('Allowed extensions: jpeg, jpg, png, gif'),
  );
  return $form;
}

function mymodule_block_save($delta = '', $edit = array()) {
  // Functionality to validate and save the file.
  $validators = array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg'));
  $file = file_save_upload('image', $validators, file_build_uri('mymodule_images'), FILE_EXISTS_REPLACE);
  if ($file) {
    $file->status |= FILE_STATUS_PERMANENT;
    $file = file_save($file);
    variable_set('mymodule_pic1', $file->destination);
  }
}


How to display a image and some text instead of unset a field using form_alter hook?

Using unset() with form elements is always wrong.

To avoid the form element is shown, just set its #access property to FALSE or to the value returned from a function, and that form element will not appear in the form, or it will appear basing on what returned from that function.
Once you make it not accessible from the currently logged-in user, you can add the form elements you need, not forgetting to add the form submission handler to handle the input given from the users for those form elements you add.


How can I include Guzzle as a library in a distribution?

I disabled composer system wide on my machine and create a make file and it works fine installing Drupal 7 core plus the following modules: composer, composer_autoload & guzzle.

This is the content of platform.make

$Id$

; API

api = 2

; Core

core = 7.x

; Drupal project.

projects[drupal][type] = core
projects[drupal][version] = 7.x
projects[drupal][download][type] = git
projects[drupal][download][branch] = 7.x

; Modules

projects[composer] = 1.x-dev
projects[] = composer_autoload
projects[] = guzzle


You can alter the node link to anything you would like with "Rewrite the output of this field", it should link to something like /yourviewpath/$nid, where $nid is the node id and the argument for the view that contains the node details.


How to change permission for dynamic routes?

The _permission route setting isn't a callback function like the access callback in Drupal 7; it defines one or more permissions that are checked before granting access to the route. There's nothing dynamic about the setting. Adding one (or more) 'administer taxonomy_id vocabulary terms' permissions will restrict access if the user doesn't have those one or more permissions.

If you need to define a dynamic access check, you'll need to utilize _custom_access and define your own callback function that takes into account a specific permission check based on the context (see Structure of routes for more information).


What values can I use for _entity_access in a configuration entity I am developing?

According to the Drupal 8 documentation:

  _entity_access: In the case where an entity is part of a route, can check a certain access level before granting access (e.g.,
  _entity_access: 'node.view').

The part after the dot is the type of access you want to check on the entity. To find the full set of possible values, you have to look at the code of the entity (in your case, in \Drupal\search\Entity\SearchPage). The default possible values are view, update, delete, create. Entities implemented by SearchPage can also be disabled and enabled. (See search.routing.yml and SearchController.)

See also EntityAccessCheck::access().


This is a bit of a cheat following the code that's used by the glossary view, but it works:

function module_views_query_alter(&$view, &$query) {
  if ($view->name == 'custom_page' && $view->current_display == 'page_1') {
    if ($view->args[0] == '0-9') {
      $query->where[0]['conditions'][2]['field'] =  "SUBSTRING(node.title, 1, :node_title) in ('0','1','2','3','4','5','6','7','8','9')";
      $query->where[0]['conditions'][2]['value'] = array(':node_title' => 1);
      $query->where[0]['conditions'][2]['operator'] = 'formula';
    }


How to add certificate to drupal_http_request()?

You need to supply a context parameter in the options for drupal_http_request. The value is a stream context created using the PHP function stream_context_create.

There are a lot of possible parameters so you may have to hunt through the parameter list to find the ones you want.


How to add a new CSS class to a Drupal7 ?

You need to add it to the #attributes key of the $form array:

function shop_form($form, &$form_state, $nid) {
  $form['#attributes']['class'][] = 'cart'; // Classes are added to an array and internally converted to a single string by Drupal later on

  $form['my-item-name'] = array(
    '#type' => 'hidden',
    '#title' => t('Name'),
    '#value' => isset($node->title) ? $node->title : '',
  );

  return $form;
}


I cannot sign into my drupal site. The login page just refreshes and there are no error messages

So after failing to log in a couple times, drupal will block your ip and makes it so you can't login until some arbitrary amount of time, which explains a lot. To unblock ip addresses use drush sql-query "delete from flood" I also did not have the error messages popping up when you put in a wrong password.


How to configure view filter to search on the basis of two conditions

You can add filters twice.  So, to avoid getting gmail or yahoo, you can first add a NOT gmail e-mail filter, and then add a second NOT yahoo filter.

This is not a great way to do it if you have an extremely large number of requirements, but if you only have a few, then it should be fine.


Can I override a theme function from a contributed module

The page you are referring is for Drupal 5.

In Drupal 6, you alter a theme function defined in a module by defining the theme function, as in the following code. (Replace mytheme with the short name of your theme.)

// Drupal 6
function mytheme_guestbook_entry($uid, $entry, $comment_entry = NULL, $zebra, $confirm_delete = FALSE) {
  // Your own code.
}

// Drupal 7
function mytheme_guestbook_entry($variables) {
  // …
}

In Drupal 7, if you just want to alter the variables passed to the theme function, you need to implement the preprocess function for that theme function.

function mymodule_preprocess_guestbook_entry(&$variables) {
  // Alter the values passed to the function, such as $variables['uid'], $variables['entry'],
  // $variables['comment_entry'], $variables['zebra'], or $variables['confirm_delete'].
}

The code I shown works whatever a theme function is implemented in Drupal, or a third-party module.


How can I create a menu link that shows only to authenticated users?

Long story short, you create 2 different Menu versions and give each version different visibility rules.

All you gotta do is configure your menu link block

Then in Roles, check mark ☑ Authenticated users and  you may want to also ☑ Administrator

Now create another Menu (/admin/structure/menu) which does not have the "add node" link. Then go to blocks (/admin/structure/block) in Primary Menu (Assuming you're using Bartik, may have a different name if you're using a custom theme) click add, and add the Menu you just created and configure it.

This time for Roles, only check mark ☑ Anonymous

  PS: In pages you can restrict so it only shows up in certain pages.


How to deal with the "Payment failed at the payment server" error?

I had a similar problem with the token conversion, be sure you're using the -dev version (2014-May-23 or later) of Commerce Sagepay before trying anything else.

Note: probably related to: https://drupal.org/node/2115203


You do it the same way, the only difference is that you need to make your block class aware of the container first.

Example:

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
...
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $aliasManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->aliasManager = $alias_manager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('path.alias_manager')
    );
  }
}


Youtube Media with Media Module, won't render

The media module currently only has support for embedding images via WYSIWYG.

What version of media are you using? If you use media 7.x-2.x you can get it to work by using this sandbox module - http://drupal.org/sandbox/DevinCarlson/1823634
(note that you also need separate http://drupal.org/project/issues/file_entity module with 2.x because it has now been split out of media - it was part of media in 7.x-1.x)

That sandbox module allows configuring which view modes are used for different file types when embedding via WYSIWYG.

There is a related issue for the media module here http://drupal.org/node/1792738 - It has been decided in that issue that the sandbox module will be integrated into the media module.
So you can safely use the sandbox knowing that the functionality will eventually be in the media module, at which point you won't need to rely on a sandbox project.

When using that setup of modules I find that in a lot of cases it is also good to use http://drupal.org/project/entity_view_mode - which allows you to create new view modes (the file_entity 7.x-2.x module doesn't provide many view modes out of the box).


Always keep admin UI in English when translating content

This functionality is partially achievable since Drupal 8.6.4.

Navigate to Detection and selection
(admin/config/regional/language/detection)
Adjust your settings accordingly. Be sure to activate "Account administration pages". Your content language detection methods are optional.

Edit your user profile and set your "Administration pages language" to English.

Now your Admin UI will stay in English no matter what the other language detection methods resolve to. That means while creating a translation, the interface will remain in English.

However, the unsupported part is keeping the Admin Toolbar in English when being redirected to the translated page on saving it. But when going back to the Admin UI it's in English again.

These issues are dealing with that:
https://www.drupal.org/project/drupal/issues/2313309

And if you use the Admin Toolbar module:
https://www.drupal.org/project/admin_toolbar/issues/3004575


Same as shipping checkbox in admin is not showing

I'm guessing this checkbox is meant to copy the address from the billing address to the shipping address?

As Ryan pointed out on the frontend this will require ajax as the shipping and billing profiles could be on different steps, however on the backend they are both on the same page so all that is required is some javascript.

For example...

Add the checkbox and custom javascript to the page in a hook_form_alter:

/**
 * Implements hook_form_FORM_ID_alter() for commerce_order_ui_order_form.
 */
function MY_MODULE_form_commerce_order_ui_order_form_alter(&$form, &$form_state, $form_id) {

  // Add the checkbox
  $form['commerce_customer_billing'][LANGUAGE_NONE]['profiles'][0]['copy_from_shipping'] = [
    '#type' => 'checkbox',
    '#title' => t('Copy address from shipping'),
    '#attributes' => ['class' => ['copy-address-from-shipping']],
  ];

  // Attach our custom js
  $form['#attached']['js'][] = drupal_get_path('MY_MODULE', 'taronga') . '/js/copy-address-from-shipping.js';

}

And then for the javascript:

(function($) {

    /**
     * The Drupal behaviors to copy address from shipping to billing on admin order edit page.
     */
    Drupal.behaviors.copyShippingAddress = {
        attach: function(context) {

            // Only bind our click event handler once
            $('.copy-address-from-shipping').once(function(){

                // Bind the click event
                $('.copy-address-from-shipping').click(function () {

                    var $shipping = $('#edit-commerce-customer-shipping-und-profiles-0');
                    var $billing = $('#edit-commerce-customer-billing-und-profiles-0');

                    if($(this).is(':checked')) { // Copy values from shipping

                        // Loop over inputs & select in shipping fieldset
                        $shipping.find('input, select').each(function () {
                            // Skip any inputs without a name attribute (e.g. chosen)
                            if($(this).is('[name]')) {
                                // Get the name of this field and convert it to the billing name
                                var billing_name = $(this).attr('name').replace('shipping', 'billing');
                                var $billing_field = $billing.find('[name="' + billing_name + '"]');
                                // Make sure the billing field exists
                                if($billing_field.length) {
                                    // Replace the value
                                    $billing_field.val($(this).val());
                                }
                            }
                        });

                    }
                    else { // Clear values

                        $billing.find('input, select').each(function(){
                            $(this).val('');
                        });

                    }
                });

            });

        }
    };

})(jQuery);


I think the problem with your Drupal 8 code is that '#url' needs a URL object.

External URL

'#url' => Url::fromUri('https://www.drupal.org'),

Internal URL from a route

'#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),

In Drupal 8 you are not supposed to render yourself. When porting code from Drupal 7, remove all rendering and return only render arrays.


Is it possible to hook to variable_set() event?

It seems that it's impossible using only Drupal, which means:

variable_set() itself doesn't invoke any hooks, but it uses db_merge(). That function is using the MergeQuery class. Now, it would be nice to hook with hook_query_alter(), but it only works for query classes that implements the QueryAlterableInterface interface. Sadly, this interface is now implemented only by the SelectQuery and the SelectQueryExtender classes, not by the MergeQuery class.

Note that even if you will find a way to create a child class of MergeQuery, that will implement QueryAlterableInterface, and make Drupal use it. hook_query_alter() only works on queries that have tags, and variable_set() doesn't tag its query, so the hook would not be used anyway, unless you are willing to hack core. But if you are, you don't need all that, you could simply hack in a hook call.

If you feel hardcore you can use a more indirect PHP approach: $conf is a global array of configuration variables; you can write a module that will replace it with object acting like an array, as described on Stack Overflow. To make it a good substitute you need to implement ArrayAccess. Pull all values from original $conf into your object. Then, in ArrayAccess::offsetSet() implement your logging logic.


Replace Ubercart radio button with image?

You can use CSS like so to target the labels:

label[for*="edit-attributes-51-"]{
   /* ADD YOUR IMAGE HERE */
}

or target the individual ones (135,136,xxx):

label[for="edit-attributes-51-135"]{
   /* ADD YOUR IMAGE HERE */
}


You can set a default value for each field on your webform.  The default value you would use would be

For Webform v3 and under:

%get[customer_name]

For Webform v4+:

[current-page:query:customer_name]

To get a first and last name you could do something like:

URL:

http://mysite.com/myform?first_name=John&last_name=Doe

First Name Default Value:

%get[first_name]                 //webform <= v3
[current-page:query:first_name]  //webform >= v4

Last Name Default Value:

%get[last_name]                 //webform <= v3
[current-page:query:last_name]  //webform >= v4


Make download available after purchase of a physical good

Sounds like a possible job for the Commerce File module

  This module is an extension of Drupal Commerce that provides the ability to sell file access.

  Ability to limit access to the file with limit settings
  Default limits: duration, download count, IP address count
  Limit default values can be inherited at the product level such that the product always uses the current default value
  After purchase of a file, limits are statically recorded to the line item so that they do not reflect any changes to the product's file limits.
  A user's limits reflect changes to an order, even after order is completed.

You can add a file field to your product entity type, and use the above module + rules to manage access to the file references by granting access licences. The licences are as liberal or as strict as you want to make them, so should be useful for your situation.

I've been using this module for a while and it works great


When the "Body" field is required, how can I force users to input, say, at least 400 characters?

You should be able to just use the Field validation module to set a minimum length on the body field.

  This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

  By using the hooks provided by this module, you can also define your
  own validation rules in your own modules.


How to use the YML structure of routes to control access to Group Content

in group.services.yml you'll find access_check entries like:

  access_check.group.permission:
    class: 'Drupal\group\Access\GroupPermissionAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_permission' }
  access_check.group.member:
    class: 'Drupal\group\Access\GroupMemberAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_member' }

you can use these in your routes like:

tam_api.group_gid_members_uid:
  path: 'group/{group}/members/{member}'
  defaults: { _controller: '\Drupal\tam_api\Controller\TamApi::getGroupMember' }
  methods: [GET, HEAD]
  requirements:
    _group_member: 'TRUE'
# or    _group_permission: 'view group membership content'
  options:
    _format : ['json']
    _auth: ['oauth2']
    parameters:
      group:
        type: entity:group
      member:
        type: entity:group_content

Note: the parameter argument must be named {group}


Can we display region label from Layouts?

The labels are for administration purposes and should not be used in templates as they are hard coded and can't be changed in the UI. A better option would likely be to use a Text field where you want to display the label as that can easily be changed.

That said, you can output the region name in the twig template like this:

{{ layout.regions.theregion.label }}


Create short link automatically with ShURLy

As per the current module functionalities it does not seem to have that feature. So I think you need to create custom module.

In your custom module you will require to use hook_node_insert (For Drupal 7) this hook to execute after each node is added. Then Shurly provides API to create short link, using those APIs you can create short link as an when required.

Hope this helps.. :)


How to get the selected items (with VBO) in the buildConfigurationForm of a custom Action

Provided you use the Views Bulk Operations contrib module, you can use code similar to the following, inside the buildConfigurationForm() method. Most importantly, you need to extend ViewsBulkOperationsActionBase instead of ConfigurableActionBase.

class YourAction extends ViewsBulkOperationsActionBase

...
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    ...
    $selectedItems = array_map(function ($listItem) {
      return reset($listItem);
    }, $this->context['list']);
    ...
  }
...

This will give you an array whose values are the entity ids of the selected items in your view. The keys of the array are the bulkFormKey for each selected entity.

See ViewsBulkOperationsFormTrait::calculateEntityBulkFormKey() and ViewsBulkOperationsFormTrait::getListItem() for more information about bulkFormKeys.

Hope this helps, good luck!

P.S.: And for anyone else landing here, the related VBO's documentation page is over at https://www.drupal.org/docs/8/modules/views-bulk-operations-vbo/configuring-an-action


$form_state['values'] partial empty, while $form_state['input'] is filled

The reason drupal_get_form() doesn't work in your code is that it contains the following code.

  $form_state = array();

  $args = func_get_args();
  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;

  return drupal_build_form($form_id, $form_state);

What the function passes to the form builder is a newly created $form_state array, not the one being passed to your form builder.

Using drupal_build_form() is not working because the function is retrieving the form from the cache. (See the comments before the code.)

  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

You can implement hook_form_alter(), hook_form_FORM_ID_alter(), or hook_form_BASE_FORM_ID_alter() for a form that has been already altered.

About calling drupal_get_form() from a template file, see Be careful with drupal_get_form() in theme layer. As reported in that blog article, you would have problems with the validation error messages which will not appear.


How do i disable price, shipping and payment in ubercart

You can use UC Price Visibility Module.

  Often, you want to advertise your products without revealing the prices, and show something
  like, "contact us for pricing." This Ubercart module allows you to show or hide product pricing per role, on a product-by-product basis. You can configure what message should be shown when the price is hidden, and which field should be replaced with this message (either the display price, sell price, or add to cart button).


How can I get Autocomplete behave as in most of the sites out there?

I think this is a JQuery problem rather than a Drupal problem.

You should be able to add a JavaScript function, something like the following:

$("#searchField").select(function(event, ui) {
    $("#searchField").val(ui.item.label);
    $("#searchForm").submit();
});

It's necessary to assign the value before submitting the form because if the user clicked on a list entry with the mouse, the value won't have been assigned before the select event occurs.

I haven't actually tested this, but hopefully this will send you in the right direction.


I have finally found what was the issue. It's absolutely not related to the fact I have two forms but that I was implementing my theme variable in a node preprocess function.

Errors messages are prepared in upper function so the result is that you alter a variable after it's actually called. The result is the message is displayed on reload.

See here : form_set_error message delayed one page refresh


How to alter cck field title using hook_form_alter?

First, you may check the exact field array with dsm()

function MODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

In the result returned by dsm(),  #title is set in 2 places. So just try :

$form['field_bibliographie']['#title']= t('Foo');//doesn't work
$form['field_bibliographie']['und'][0]['#title']= t('Foo');//correct one

I see no reason for which it would not take the correct value if you set the exact field array


Drupal Commerce: How to get payment module settings?

I'm using this:

$payment = commerce_payment_method_instance_load('foo|commerce_payment_foo');

where foo is the payment method string identifier.

The resulting array contains the 'settings' index, with the data saved in the settings form.

In other words foo|commerce_payment_foo is instance id which consist method_id|rule_name.

The method_id can be found by executing commerce_payment_methods() and rule_name can be found in URL when editing Payment action (at /admin/commerce/config/payment-methods).


Programmatically creating users attach profiles to correct uid on localhost but uid 1 on production

Sounds like somewhere in the first few lines of code your $account variable is getting switched to the user 1 or perhaps the currently logged in user. Perhaps trying to change the "$account" variable name to something definitely unique to see if that fixes the problem.


301 redirect one site in multi-site installation

In the root .htaccess file is a set of rewrite rules. You can add a rule to that to redirect to the new site.

RewriteCond %{HTTP_HOST} ^www\.olddomain\.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

untested, but should be about right.


CMIS Browser, a submodule of CMIS API, handles CMIS links. We are using CMIS API v7.x.x.
Here's the function responsible for the breadcrumb:
# cmis/cmis_browser/cmis_browser.theme.inc #125

function theme_cmis_browser_browse_breadcrumb($variables) {

  $next_img = theme('image', array('path' => drupal_get_path('module', 'cmis_browser') .'/images/next.gif'));
  $contents = '';
  $currentpath = '';

  $contents .= '
';
  if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
    $contents .= l('Root', 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
  }
  else {
    $contents .= l('Root', 'cmis/browser'. $currentpath);
  }

  $currentpath = '';
  foreach ($variables['bcarray'] as $space) {
    $contents .= $next_img .' ';
    $currentpath .= '/'. $space;
    if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
      $pagelink = l($space, 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
    }
    else {
      $pagelink = l($space, 'cmis/browser'. $currentpath);
    }
    $contents .= $pagelink;
  }

  $contents .= '
';

  return $contents;
}

Our workaround is simply to return an empty
 earlier:

function theme_cmis_browser_browse_breadcrumb($variables) {
  return '

';

  .....
}

Be careful since it's not a persistent solution.


Submit values and redirect user from to external URL

You can generate form like that using '#type' => 'hidden' form API fields, and using '#action' on form itself.

If you want to submit values to Drupal and then redirect user to external site, you cannot do it directly. HTTP protocol does not allow you to send anything from your server to another "on behalf" of your user. The only way to do it is:

Get data from user
Save data, process it, do whatever you need
Generate form with action pointing to external service (usually payment gateway), and data required by it in hidden fields
Use JavaScript to make user's browser submit it.

If you are trying to do it using drupal_http_request, it's your server that starts payment procedure, not client's browser - certainly not what you want. And payment server will not allow switching procedure between different computers - it would be a security risk to allow that. If you could hand your session on payment server to your user, what would prevent attacker from doing the same (but with his bank account, not yours)? I know that's simplified explanation - for more details you may try to ask on Information Security.


How to force a redirect (override the destination query string in the URL)

To force a redirect remove the destination query string from the request:

\Drupal::request()->query->remove('destination');

After this you can also reset the RedirectDestination service, although this seems not to be necessary for a form:

\Drupal::destination()->set(NULL);

When you have already a URL object set it directly in $form_state:

$form_state->setRedirectUrl($url);


Hide a CCK fieldgroup using #states in hook_form_alter()?

/**
 * Implements hook_field_group_build_pre_render_alter.
 */
function mymodule_field_group_build_pre_render_alter(&$element) {
  if (isset($element['#form_id'])) {
    if ($element['#form_id'] == 'mynodetype_node_form') {
      $element['group_myfieldgroup']['#states'] = array(
        'visible' => array(
          ':input[name="field_myfield[und]"]' => array('checked' => TRUE),
        )
      );
      $element['group_myfieldgroup']['#id'] = 'group_myfieldgroup';
    }
  }
}

I use this hook to hide my field group. It's visible only if the checkbox field_myfield is checked.

To explore $element variable in this hook I used

die('<pre>'.print_r($element, 1).'</pre>');

instead of dpm().

Hope it helped :)


How do I disable the password recovery link?

You can use hook_menu_local_tasks_alter().

E.g.

/**
 * Implements hook_menu_local_tasks_alter().
 */
function MY_MODULE_menu_local_tasks_alter(&$data, $route_name) {
  if($route_name == 'user.login') {
    $data['tabs'][0]['user.pass']['#access'] = FALSE;
  }
}

Note: Make sure to replace MY_MODULE with the actual name of your module.


What is the best practice for writing a link to the screen through t()?

For a link enclosed in translatable text, Drupal core suggests to use t() and embed the HTML anchor tag directly in the translated string. In LinkGeneratorInterface::generate(), the example code for this case is the following.

$text = t('Visit the content types page', array(
  ':url' => Url::fromRoute('entity.node_type.collection')->toString(),
));

Searching for :url in the Drupal core code finds code like the following.

BlockContentController::add()

if (count($types) === 0) {
  return [
    '#markup' => $this
      ->t('You have not created any block types yet. Go to the block type creation page to add a new block type.', [
      ':url' => Url::fromRoute('block_content.type_add')->toString(),
    ]),
  ];
}

ListingEmpty::render()

  $element = [
    '#markup' => $this->t('Add a custom block.', [
      ':url' => Url::fromRoute('block_content.add_page')->toString(),
    ]),
    '#access' => $access_result->isAllowed(),
    '#cache' => [
      'contexts' => $access_result->getCacheContexts(),
      'tags' => $access_result->getCacheTags(),
      'max-age' => $access_result->getCacheMaxAge(),
    ],
  ];

Alternatively, Drupal core uses the following code.

block_help()

$themes = \Drupal::service('theme_handler')->listInfo();
$output = '
' . t('Block placement is specific to each theme on your site. Changes will not be saved until you click Save blocks at the bottom of the page.') . '
';
$output .= '
' . Link::fromTextAndUrl(t('Demonstrate block regions (@theme)', [
  '@theme' => $themes[$demo_theme]->info['name'],
]), Url::fromRoute('block.admin_demo', ['theme' => $demo_theme]))->toString() . '
';

template_preprocess_forums()

    if ($variables['tid'] != $topic->forum_tid) {
      $variables['topics'][$id]->moved = TRUE;
      $variables['topics'][$id]->title = $topic->getTitle();
      $variables['topics'][$id]->message = Link::fromTextAndUrl(t('This topic has been moved'), Url::fromRoute('forum.page', ['taxonomy_term' => $topic->forum_tid]))->toString();
    }


Just got the error. remove space from "entity_type "
from this line
$result = $query->entityCondition('entity_type ', 'node') ->execute();


Print password confirm field in user register template file

You can always debug your twig template by printing the present variables, with help of of the Kint module (part of Devel) for example:

{{ kint(form.account.pass) }}

Or you can also print all of them:

{{ dump() }}

Further information on this page.


$form_state is one of the arguments passed to a form submission handler, or a form validation handler; its main usage is to retrieve the values entered from the user in the form see the content of $form_state['values']), but it contains other values that can be used for other purposes.
The documentation for drupal_build_form() contains the list of other values contained in that array, which include the following ones:

  rebuild: Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and drupal_redirect_form() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect. This is used for multi-step forms, such as wizards and confirmation forms. Normally, $form_state['rebuild'] is set by a submit handler, since it is usually logic within a submit handler that determines whether a form is done or requires another step. However, a validation handler may already set $form_state['rebuild'] to cause the form processing to bypass submit handlers and rebuild the form instead, even if there are no validation errors.
  redirect: Used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with drupal_goto(). See drupal_redirect_form() for complete information.
  cache: If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which ajax_process_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of $form and $form_state happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.
  storage: $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

Other functions that get $form_state as argument are hook_form_alter() and hook_form_FORM_ID_alter().

As example of code that use that argument you can look at comment_form_submit(), which contains the following code:

function comment_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $comment = comment_form_submit_build_comment($form, $form_state);
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    comment_save($comment);
    $form_state['values']['cid'] = $comment->cid;

    // Add an entry to the watchdog log.
    watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));

    // Explain the approval queue if necessary.
    if ($comment->status == COMMENT_NOT_PUBLISHED) {
      if (!user_access('administer comments')) {
        drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
      }
    }
    else {
      drupal_set_message(t('Your comment has been posted.'));
    }
    $query = array();
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    if ($page > 0) {
      $query['page'] = $page;
    }
    // Redirect to the newly posted comment.
    $redirect = array('node/' . $node->nid, array(
        'query' => $query,
        'fragment' => 'comment-' . $comment->cid,
      ));
  }
  else {
    watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
    drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
    // Redirect the user to the node they are commenting on.
    $redirect = 'node/' . $node->nid;
  }
  $form_state['redirect'] = $redirect;
  // Clear the block and page caches so that anonymous users see the comment
  // they have posted.
  cache_clear_all();
}

To understand what $form_state['values'] contains, you need to look at the values added to $form in comment_form(). For example, $form_state contains $form_state['values']['name'] because $form contains $form['author']['name']. Generally, if $form['field'] is a form field, then $form_state will contain $form_state['values']['field'].


How do I execute a function every 3 months?

watchdog() is not appropriate place for storage; the $variables parameter is for formatting the display of variable data (e.g. the USERNAME in "User USERNAME has logged in"), not for long term storage of application data.

Instead, use a combination of hook_cron() and the persistent variable functions (variable_get() and variable_set()) to execute a cron task that remembers when it was last run.

/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Look up last time MYMODULE_function() was run compared to 3 months ago.
  if (variable_get('MYMODULE_function_last_run', 0) <= strtotime('-3 month')) {
     // Run my function
     MYMODULE_function();

     //Store the time when MYMODULE_function() was last run.
     variable_set('MYMODULE_function_last_run', time());
  }
}


Primitive types are special case.

By default, they get the PrimitiveType validation constraint in TypedDataManager::getConstraints().

<?php
// Auto-generate a constraint for data types implementing a primitive
// interface.
if (is_subclass_of($type_definition['class'], '\Drupal\Core\TypedData\PrimitiveInterface')) {
  $constraints[] = $validation_manager->create('PrimitiveType', array());
}
?>

Validation constraints are usually provided in one of the following places:

The plugin annotation (see e.g. EntityReferenceItem)
base field/property definitions (see e.g. Node::baseFieldDefinitions(), title field)
By overriding the getConstraints() method on a typed data class.


Hook insert/update

The Book module update the book menu title during node insert/update.

You can implement hook_node_insert and hook_node_update to update the title in place.

/**
 * Implements hook_node_insert().
 */
function my_custom_module_node_insert($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

/**
 * Implements hook_node_update().
 */
function my_custom_module_node_update($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

Using preprocess

You can do that by override template_preprocess_book_navigation which contain a call for book_children function. The aim of override is to provide custom version of book_children function which add the node date to the title before calling the render method.

/**
 * Processes variables for book-navigation.tpl.php.
 *
 * Override theme_preprocess_book_navigation
 */
function my_custom_module_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];
  if ($book_link['mlid']) {
    $variables['tree'] = custom_book_children($book_link);
  }
}

/**
 * Formats the menu links for the child pages of the current page.
 *
 * A custom version of book_children to add date suffix to link title.
 */
function custom_book_children($book_link) {
  $flat = book_get_flat_menu($book_link);

  $children = array();

  if ($book_link['has_children']) {
    // Walk through the array until we find the current page.
    do {
      $link = array_shift($flat);
    }
    while ($link && ($link['mlid'] != $book_link['mlid']));
    // Continue though the array and collect the links whose parent is this page.
    while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
      // Get node object.
      $node = menu_get_object('node', 1, $link['link_path']);
      // Add date to link title.
      $link['title'] = $link['title'] . ' - ' . format_date($node->changed, 'custom', 'M j, Y');
      $data['link'] = $link;
      $data['below'] = '';
      $children[] = $data;
    }
  }

  if ($children) {
    $elements = menu_tree_output($children);
    return drupal_render($elements);
  }
  return '';
}


Fieldgroup accordion does not open to first field of group

This is the solution I ended up using. I got it from I got it here: https://stackoverflow.com/questions/3621161/jquery-accordion-will-it-scroll-to-the-top-of-the-open-item.

I tested it at modules/contrib/field_group/field_group.js file at line 66. We then created a patch for it.

Not sure if this is the best solution, but it worked for us, so I thought I'd share the info.

activate: function( event, ui ) {
                    if(!$.isEmptyObject(ui.newHeader.offset())) {
                        $('html:not(:animated), body:not(:animated)').animate({ scrollTop: ui.newHeader.offset().top -150}, 'slow');
                    }
                }


Is it possible to migrate data into multiple translations of entities?

I'm missing some informations for all understand your problem but, to migrate an object which have many translation you need:
Create the initial entity in the source language of your choose and add translation to this entity. For example, for a taxonomy term:

$default_language = "en";
$other_languages = ["fi", "sv"];

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'my_vocabulary',
  'name' => $my_importer_object['name'][$default_language],
]);

$term->save();

foreach($other_languages as $language) {
  $term_object = [
    'vid' => 'my_vocabulary',
    'name' => $my_importer_object['name'][$language],
  ];
  $term->addTranslation($language, $term_object);

  $term->save();
}

Like it's a taxonomy term, it will be reference in your object like a entity references, with its tid. The link between translated version of the term and translated version of the node will be the language. If the term exist in the language of the node, Drupal 8 will used it automatically. If the term isn't translated in the language, Drupal will use the original language of the term, in which it had been initially created.


Simple way to add a class to the body when creating/editing an entity

You can use hook_preprocess_page and check the current route:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  // This would add a class based on the route.  You'd need the
  // pathauto module enabled.
  $vars['page_classes'][] = \Drupal::service('pathauto.alias_cleaner')->cleanString($route_name);

  // This would add the classes asked for in the question.
  if ($route_name == 'entity.node.edit_form') {
    $vars['page_classes'][] = 'entity-edit';
  }
  elseif ($route_name == 'node.add') {
    $vars['page_classes'][] = 'entity-create';
  }
}


well, i'm not totally sure what you mean, but according to the title of the post, you want a redirect function ?

something like the drupal_goto(); function?

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_goto/6


why views items per page set to specific values

To be brutally simple: Because someone thought it to be good UX, maintainers agreed, and no one convinced them other way since then. That's all to it.

There are many reasons for drop-down instead of text field. For example simplicity. User cannot enter bad values, so there is no need for bad value handling. Testing - you can programatically set other amounts, all right, but there you have ones they tested their module for, and take some responsibility that they work properly. Of course, maybe someone simply liked it that way. No way to know for sure what was the most important part in this decision.


How to add css and js file in custom module

To understand how to correctly define a library, see how Drupal core defines its library, for example the ones defined in core.libraries.yml.

jquery:
  remote: https://github.com/jquery/jquery
  version: "3.2.1"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/3.2.1/LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/jquery/jquery.min.js: { minified: true, weight: -20 }

jquery.cookie:
  remote: https://github.com/carhartl/jquery-cookie
  version: "v1.4.1"
  license:
    name: MIT
    url: https://github.com/carhartl/jquery-cookie/blob/v1.4.1/MIT-LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/jquery.cookie/jquery.cookie.min.js: { minified: true }
  dependencies:
    - core/jquery

jquery.farbtastic:
  remote: https://github.com/mattfarina/farbtastic
  # @todo Ping @robloach or @mattfarina to retroactively create this release.
  version: "1.2"
  license:
    name: GNU-GPL-2.0-or-later
    url: https://github.com/mattfarina/farbtastic/blob/master/LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/farbtastic/farbtastic.js: { minified: true }
  css:
    component:
      assets/vendor/farbtastic/farbtastic.css: {}
  dependencies:
    - core/jquery

The dependencies key is not a sub-key of js, nor css, but it is at the same level of the js and css keys.
Keep in mind that the dependencies key defines the dependencies of the library from other libraries.

I would rather use the following library declaration.

lrv:
  version: 1.x
  js:
    js/lrv.js: {}
  css:
    theme:
      css/lrv.css: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

A .libraries.yml file just defines the libraries, which aren't automatically loaded, since the definition doesn't say to Drupal when they should be loaded.
To load your library, for example in hook_page_attachments(), you use code similar to the following.

function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mymodule/lrv';
}

The name of the library is mymodule/lrv because it is defined as key lrv (the one I used in the code I shown) in the file mymodule.libraries.yml (the one you seem to use).

See Defining a library and Attaching a library to page(s).


Pathauto changing drupal_get_path file path

Are you accessing this link from a subpage? It would seem that it is not appropriately pulling from the Drupal root when you are making the call (from a page other than the homepage).

You can use the global variable $base_path to get the Drupal root. More information on this global variable: https://api.drupal.org/api/drupal/developer%21globals.php/global/base_path/7


"Page not found" when accessing a custom module

As stated, YAML has very specific spacing rules.

custom_form.register:
  path: '/custom_form/my_form'
  defaults:
    _form: '\Drupal\custom_form\Form\Formsettings'
    _title: 'Registration page'
  requirements:
    _permission: 'view user registration form'

Try that spacing, and Formsettings will need to be a form controller in custom_form/src/Form if it isn't already - you didn't link to it.

Both hook_permission() and hook_menu() are no longer used, so you'll want to remove them from the code base. (though I don't think they will stop it from loading properly.)


Cannot send drupal_http_request authorization header

You have the second param to drupal_http_request wrong; it should be an array of options, not an array of headers. Headers is just one of those options.

To fix:

$result = drupal_http_request($url, array('headers' => $headers), 'POST', json_encode($data));


PHPUnit with custom/contrib and submodules structure

The right thing to do is to not add it to the core phpunit.xml.dist file. You have your own code, so you want to test that. The idea that core also tests contrib / custom code is not the right thing to do, IMHO


Overriding Pathologic when it comes to img src

You could alternatively use the scanner module or export the DB and use a text editor to replace the domains. Therefore getting rid of pathologic.


Children links disappear when access to parent blocked

With the caveat you should be very careful adjusting any core menu item permissions, and I'm presuming you know what you're doing there, it is possible to adjust any menu with

hook_menu_alter

for example:

function mymodule_menu_alter(&$items) {
  // Enable open access for everyone to foo/bar
  $items['foo/bar']['access callback'] = TRUE;
}

You can also specify your own access callback there, e.g

function mymodule_menu_alter(&$items) {
  // Add custom access callback to foo/bar
  $items['foo/bar']['access callback'] = 'mymodule_special_access';
}

function mymodule_special_access(){
  global $user;
  if($some_condition_is_true){
    return TRUE;
  }
  return FALSE; // default deny
}


# Remove the current version of drush.
composer global remove drush/drush
# Install drush version 7.
composer global require drush/drush:7.*


#submit and #validate each need to be an array:

$form['actions']['submit_resend'] = array (
  '#value' => t('Resend Activation Email'),
  '#type' => 'submit',
  '#submit' => array('_mymodule_resend_activation'),
  '#validate' => array('_mymodule_form_validate'),
  '#attributes' => array('class' => array('btn-primary', 'btn'))
);

As far as I know there aren't any limits on the number of elements that can share the same validation callback.


Is there any module to create a set of field without creating new entity field for each one?

If the objective is to have one entity field that stores a primary key into a custom table schema, the answer is probably no. Location (and its associated Location CCK module) achieves this by its own widget form (via hook_field_widget_form) & element type (via hook_element_info). It creates various processing functions to store the data in its custom data schema. I think such a module you're describing would need to dynamically generate data schema and hook callbacks to achieve what you're wanting.


Add attributes to a template based on current node

In Drupal 8 you can get the node object from the routing system:

function [THEME]_preprocess_region(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
}


Try the Colorbox module, this offers this functionality.


How to stop drush displaying a Drupal error message?

Two options:

Hide the messages with ob_start() and ob_end().
Avoid the messages by moving the target file out of the way, and moving it back again after saving the entity.


How do you add validation (constraints?) on a paragraph? Compare two fields

You simply inherit from the the default EntityReferenceWidget and you will call it like MyParagraphEntityReference widget. You can here both change the way how the autocomplation works and also how you validate the entered data.

This is page may help you.


Why is libraries-override not removing assets?

This doesn't answer the original question, but turns out to be a better solution in my case.  You must clear your cache with each change to this function:

/**
 * Implements hook_library_info_alter().
 */
function example_library_info_alter(&$libraries, $extension) {

  // If you have 'stack' as your subtheme, you might have unwanted lightbox assets.
  if ('stack' === $extension) {

    if (isset($libraries['global-styling'])) {

      $current_path = \Drupal::service('path.current')->getPath();
      $path_args = explode('/', $current_path);

      // Your conditions may vary.
      if ('book' == $path_args[1] && isset($path_args[2]) && is_numeric($path_args[2])) {

        // Helper function below.
        if (example_array_key_exists_r('css/lightbox.min.css', $libraries)) {
            unset($libraries['global-styling']['css']['base']['css/lightbox.min.css']);
        }

        if (example_array_key_exists_r('js/lightbox.min.js', $libraries)) {
            unset($libraries['global-styling']['js']['js/lightbox.min.js']);
        }

      }
    }
  }

}

/**
 * Recursively search for an array key.
 *
 * @see https://stackoverflow.com/a/2948985/861826
 *
 */
function example_array_key_exists_r($needle, $haystack) {

  $result = array_key_exists($needle, $haystack);

  if ($result) return $result;

    foreach ($haystack as $v) {
      if (is_array($v)) {
        $result = example_array_key_exists_r($needle, $v);
      }
      if ($result) return $result;
    }

    return $result;
}


Candidate page template filename for particular custom content type entry

function mytheme_process_page(&$variables) {
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}

Assuming your machine-readable content type name is "work", page--work.tpl.php will work.

Refer to this thread for more info.


Found a solution the other way.

Created views for chart separately and inserted into my existing view through "Global view" Field.
It increased page load time a bit so for cached page from 2-3 seconds to 3-4 seconds but that is better than 30 seconds(sometimes even more based on content) without cache


How can you add a multiple value field to an entity?

How to attach a field to an entity programically solved this problem for me.  It's not an exact duplicate, but the answer and the comments pointed me to the right direction.

So this code creates the field and the instance and it attaches it to the entity very nicely:

function contacts_enable()
{
  if (!field_info_field('related_topics'))
  {
    $field = array(
      'field_name' => 'related_topics',
      'type' => 'list_text',
      'cardinality' => -1,
      'settings' => array(
        'allowed_values_function' => '_contacts_get_related_topics',
      ),
    );

    field_create_field($field);

    $instance = array(
      'field_name' => 'related_topics',
      'entity_type' => 'contacts',
      'label' => 'Related Topics',
      'bundle' => 'contacts',
      'default_value' => NULL,
      'settings' => array(
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(),
        'type' => 'options_buttons',
        'weight' => -1,
      ),
    );

    field_create_instance($instance);
  }
}


How do I make a block title output as a link?

You can simply edit your View, and set the title of your view to this:

My Link

Click on Apply and then Save your view.


multistep registration from in drupal 7 need to add a user and role

// Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function.
      'roles'        => array(array_search('campus_student', $roles) => 1),
      // the field_* values come from custom columns added through
      // thhe admin ui under manage fields for users.
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['last_name']))),
      'field_perm_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['campus_perm_number']))),
      'mail' => $get_ldap_details['mail'],
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);

EDIT: You can see how drupal itself typically creates in a user via drupal_external_login_register(). The above example uses some API calls to get all Roles and assigns very clearly X additional roles, it also sets up additional drupal Fields tied to the user entity.


How to create an entity-reference field programmatically?

Could I call field_create_instance() in hook_form_alter()?

field_create_instance() is normally called in hook_install(), or hook_enable() from a module, or an installation profile.

You don't call it in hook_form_alter(), especially if the hook is altering the node edit form: Fields are attached to bundles (content types), not to single nodes. When a node is created, its content type is already created, and any field that content type requires is created before its nodes are created.
If there is a setting form that allows users to decide which fields to attach to a content type, then field_create_instance() is called in its submission callback.

A call to field_create_instance() is normally coupled with a call to field_create_field(). To be sure the field doesn't exist, you should first call field_info_field(). It returns NULL when the field doesn't exists.


Alternatives to creating a large number of one-use, page-specific blocks?

You should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A rising star ...

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...


How do I check Organic Groups group permissions from a custom module?

if your group entity is a node which I'm guessing it should be change your code to:

$gid // your group's node id.
$allowed = og_user_access('node', $gid, 'create resource content');


CCK text field does not appear in views fields nor filters

The problem was that I had in Views -> Tools the option "Disable views data caching" unchecked. Fixed now, thanks for your help!


Custom form calls different form in modal, submit/ajax callback of second form not called

Since you're programmatically setting a modal with
$response->addCommand(new OpenModalDialogCommand($this->t('Test'), $modal_form, $dialog_options));

For the form that is in the modal, Drupal needs to know what URL it should post the AJAX to and be told that its an AJAX request because this only gets set automatically when the url key doesn't have a value.
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'event' => 'click',
    'url' = \Drupal\Core\Url::fromRoute('dms_gift_voucher.gift_voucher_cofirm_form'),
    'options' => [
      'query' => [
        FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ],
  ];

Side note: The above isn't needed with the HTML way of opening dialog boxes, had you done:
<a class="use-ajax"
   data-dialog-options="{&quot;width&quot;:600}"
   data-dialog-type="modal"
   href="/dms_gift_voucher/form/gift_voucher_cofirm_form">
   Should load Test webform in a Modal
</a>

because it has the URL of the form and knows its an AJAX request from the class name.