Why does the Node reference module search only for node titles?

You should  use tokens and autonodetitle modules.

After enabling tokens and automatic node title , go to Stucture->content types -> edit (type A) content type. If you scroll below you will see an option Automatic title generation . Click on 'automatic title generation' you will see an Pattern for the title and list of options containing token list
like curent user, current date, current page, node , random etc.
Click on node and find the token related to node Type A.Like for the field location and field zip there will be token similar to this [node:field-zip],[node:field-location]
add this into pattern for title field. Now you can check the Type B autocomplete entity reference field for type A . you will find that as title is changed the entity reference field has location and zip in the title.


Commerce - How do you setup conditional shipping options that relate to a specific taxonomy term?

Use the Commerce Extra Rules Condition module:

The module adds additional Rules conditions related to Drupal Commerce.

It currently adds:

  A condition for checking if a line item references a product with a
  specified Taxonomy term applied to it. A condition for checking if a
  line item references a product with specified Taxonomy terms applied
  to it. A condition for comparing the quantity of products in an order
  with a specified Taxonomy term applied to them against a specified
  value. A condition for comparing the quantity of products in an order
  of a specified product type or checking the quantity of products in an
  order excluding a specified product type.


This was cross-posted to the Drupal Sub-reddit.  Just posting here for any future googlers:

If you have more than one pager on a page (think a views block of recent content) you have to give it a unique Pager ID which you can do in the advanced settings for the pager in views.


Hide "Your name" field in comment form from everyone except admin

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

  if ($user->uid != 1) {
    unset($form['author']['name']);
  }

}

Another way is, if your theme has a comment.tpl.php file, putting a condition to restrict authenticated and anonymous user.

<?php print $author; ?>

To limit this to a particular content type, you can create a separate comment template file for that content type.


Fatal Error Running Drush 4.4 with Drupal 7.2

Ok, another one for the "learning experience" column:

I specified

DRUSH_PHP=/path/to/php

right before this line in drush wrapper script:

if [ ! -z "$DRUSH_PHP" ] ; then

Works now.

Thanks @kiamlaluno & @Berdir for your time and input. Hopefully this helps others.

KM


Display "uncaught exception" page as content-type text/html

Thanks @4k4, so it seems that this is a minor bug, but the obvious fix would revert the "Standardize handling" issue.

I have raised this issue and linked it to the other issue.  I don't really understand the code here and would welcome any help to improve the issue text.


How to customize message in maestro mail notification

I know this has been up for a while but thought I would answer. Up until recently, Maestro was removing any HTML from that textbox using Drupal's checkPlain.

I added a patch which was accepted into the development branch so it should be sorted in the next release of Maestro. If you wanted a fix in the meantime, use the patch file here: https://www.drupal.org/project/maestro/issues/3076536


Is it possible to turn off the auto-pathing for the Pathauto module?

I don't know if this is possible without implement the hook_form_alter() function but you can use a different approach to solve the issue.

You can use a custom field instead that the title of the node.
Set the field as "Required" and in /admin/config/search/path/patternsset the pattern of the node with the token of the field instead that the title (ie: [node:field-seotitle] ).

In other words:

Add a field in your content type, for example: seotitle;
Set the field as Required;
Go in /admin/config/search/path/patterns;
Set the pattern of the your content type where you have add the field with the token of the seotitle field (ie: your-content-type/[node:field_seotitle]);

In this way you can choose a title for the path alias and save the node only until you have a seo-title;

I hope I explained myself.


Possible to use OR in contextual filter?

I think there is a module for that, Views Contextual Filters OR.

  The module provides a views plugin which modify query to support OR
  conditions for contextual filters.

  How does it work?
  The handler is replaced in views which is used by
  default. A new option will appear in settings page query. If the
  option is enabled the query will be rewritten using operator OR.


How to troubleshoot errors after successful Drupal update?

According to this comment you should re-upload common.inc file in includes folder.

  I don't use Drupal Commons, but I got the same error when upgrading
  Drupal Crore from 7.20 to 7.34.

  This function was added in Drupal Core 7.33 so check your core version
  is later than that. https://www.drupal.org/node/2369141

  I then fixed it by reuploading common.inc in the includes folder. Must
  have not uploaded correctly the first time.


Complex View with Contextual Filter and Relationships

I have been able to completely solve it. Using a contextual filter, but somehow I had no the options listed in the first edit, so I needed to create the filter first, and then edit again, maybe because I was using a relationship (not very user intuitive, BTW). So here it is important to use the relationship and complete the values below (all outlined in red). Now it works perfectly, the taxonomy terms are listed with the grouped count of items, and filtered by a different taxonomy, with the content Producto joining both taxonomies.


Why I'm not able to delete all taxonomy terms tree?

The comment is correct, children are deleted automatically.

So what you can do is set the max_depth argument to 0, then you should only get the top-level terms and you can delete those.


AJAX calls in CTools Content Type Plugin?

Short answer: you should use #ajax['path'].

Long answer:

Having a ajax callback does not help as ctools creates it's forms differently afaik. The callback done by system/ajax cannot find the complete form definition thus cannot find an element to process the ajax request for. Using #ajax[path] just triggers a menu item.

You can check for yourself by dumping the form when using #ajax[callback]

function ajax_form_callback() {
  list($form, $form_state) = ajax_get_form();
  drupal_process_form($form['#form_id'], $form, $form_state);

I've modified the simplecontext_content_type_edit_form by adding the user autocomplete widget and your field which both work :)

function simplecontext_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];

  $form['owner_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#default_value' => 'admin',
    '#autocomplete_path' => 'user/autocomplete',
    '#size' => '6',
    '#maxlength' => '60',
    '#description' => '$description',
  );

  $form['link_type'] = array(
    '#type' => 'radios',
    '#title' => t('Link Type'),
    '#ajax' => array(
      'path' => 'my_module_set_target'
    ),
    '#default_value' => empty($conf['link_type']) ? '_blank' : $conf['link_type'],
    '#options' => array('none' => t('No Link'), 'internal' => t('Internal Link'), 'external' => t('External Link'), 'document' => t('Document Link')),
  );
...

As you now use #ajax path you need to add a menu item as I did like

<?php

function my_module_menu() {
  $items = array(
    'my_module_set_target' => array(
      'title' => 'AJAX Example',
      'page callback' => 'my_module_set_target',
      'access callback' => TRUE,
      'expanded' => TRUE,
    )
  );
  return $items;
}

function my_module_set_target() {
  drupal_json_output( array('data' => "ABC"));
}

A nittpick about #attached[js]: the inline js should be key => value like:

'#attached' => array(
  'js' => array(
    'alert("Yay.");' => 'inline',
  ),
),

I've used Firebug to check for the resulting value not the resulted effect. So I hope this helps to fix your problem.


Configuring Drupal 7 settings.php with both Memcache and Varnish

I got it a little bit later. It was just the array format being different in the two sources I copies and pasted from. The problem line was:

#$conf['cache_backends'][] = array('sites/all/modules/contrib/varnish/varnish.cache.inc');

It should be:

#$conf['cache_backends'][] = 'sites/all/modules/contrib/varnish/varnish.cache.inc';


It seems, I found some solution, may be not fully drupal-way.

Firstly, we need to load JS libraries, needed for working of ajax submit. This code helps us:

drupal_add_library('system', 'drupal.ajax');
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'jquery.form');
drupal_add_library('system', 'druapl.progress');
drupal_add_library('system', 'drupal.textarea');

Nextly, we need to fill JS class Drupal.settings.ajax with data about page elements, which provides ajax behavior. I have not an universal solution, I only stops JS code on breakpoint in misc/ajax.js when running it on page with correct working ajax form. You can see correct values in this part of code:

Drupal.behaviors.AJAX = {
  attach: function (context, settings) {
    // Load all Ajax behaviors specified in the settings.
    for (var base in settings.ajax) {
      if (!$('#' + base + '.ajax-processed').length) {
        var element_settings = settings.ajax[base];

        if (typeof element_settings.selector == 'undefined') {
          element_settings.selector = '#' + base;
        }
        $(element_settings.selector).each(function () {
          element_settings.element = this;
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        });

        $('#' + base).addClass('ajax-processed');
      }
    }

So, in my case resulting JS code, needed to be added into startup javascript, looks like this:

if(Drupal.settings.ajax == undefined){
    Drupal.settings.ajax = {
        'edit-submit': {
            callback: "faqform_ajaxsubmit",
            event: "mousedown",
            keypress: true,
            prevent: 'key',
            submit: {
                _triggering_element_name: "op",
                _triggering_element_value: "Send"
            },
            url: 'system/ajax',
            wrapper:'submit-message'
        }
    };
}

If all done correctly, you form, loaded by ajax, will have correct ajax behavior, in my case - ajax submit.

May be there are more graceful solutions, may be diving deeper into code will help you to find them.

So, here is much more graceful solution!

After some analyses of steps, maked above, I decided, that only thing we need to make ajax form, loaded by ajax, to work is fill javascript  Drupal.settings array with correct data, describing forb behavior.
In the above example we made it by hands, with hardcode, whitch is not true. Obviously, somewhere in drupal code it work does automatically.
I found this place. It is function ajax_pre_render_element in the ajax.inc. It gives array of any form element with ajax property and appends to it additional parameters, which will be converted to JS code and added to Drupal.settings array later. Exactly thing, that we need.

Here is my code now:

function anyform_block_info()
{
    //standart form for displaying to user
    $blocks['any_form'] = array(
        'info' => t('Any form'),
        'status' => true,
        'region' => 'content',
        'weight' => 99,
        'visibility' => 1
    );
    //hidden 'form' needed to generate and load ajax behavior settings before form loading
    $blocks['faq_form_hidden'] = array(
        'info' => t('Any fake form'),
        'status' => true,
        'region' => 'footer', //I thing, it will be better place it in footer^ in my case content is ajaxed
        'weight' => 99,
        'visibility' => 1
    );
    return $blocks;
}

function anyform_block_view($delta)
{
    switch ($delta) {
        case 'faq_form':
            $block['content'] = drupal_get_form('anyform'); //standart form
            return $block;
        case 'faq_form_hidden':
            $block['content'] = anyform_get_hidden_form(); //fake form
            return $block;
        break;
    }
}

function anyform_get_hidden_form()
{
    $form = drupal_get_form('faqform'); //give our original form
    $form = ajax_pre_render_element($form['submit']); //create settings for element with #ajax property (don't pass whole form as argument - not works)

    //makes fake form with hidden element in footer, but with correct array with settings for ajax behavior
    $fakeform['fakeform'] = array(
        '#type'=>'markup',
        '#markup'=>'

',
        '#attached'=>$form['#attached'], //our magical array
    );

    return $fakeform;
}

So, I hope, it will solve most of your problems with drupal ajax-loaded forms. For me this solution works without any problems, and I going sleep being happy =^_^=
Good luck!


taxonomy term path using two different vocabulary

For your content type, you could set a content path pattern (admin/config/search/path/patterns) that looked something like this:

[node:field_destination]/[node:field_category]/[node:title]

This would put the destination term in front of the category term for your content nodes.  However, there is no good way for you to put the destination term in the path to the category vocabulary, because there might be zero, one or many content type nodes for any given category, and you have no good way to relate these two terms.


You can use hook_theme_suggestions_HOOK_alter() like below:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $roles = \Drupal::currentUser()->getRoles();
  if (in_array('YOUR ROLE',$roles)) {
    $suggestions[] = 'user__'.ROLENAME;
  }
}

and you have to create

  user--YOURROLE.html.twig

in order to get a specific template for the user based on their role.


Display Suite layouts not available for field collections Edit\Add forms

If you are using 7.x.1, you need rel module to edit forms from other entites than node type, like field collection, user, comment, etc.
If you are using 7.x.2 you don't need that because this branch offers this feature out of the box.
For editing forms, you must go to Manage fields of your entity.

edit: just to note that rel will stop this from working on the 7.x.2 branch.


You define that through the config schema, not the form.

See https://www.drupal.org/node/1905070, use type: label (weird know but that's how it is called) not string and type: text for textareas.

If you have no config schema yet, look at other modules providing blocks with configuration, like aggregator.module to see how to define that.


Alter menu and set 'access callback' => 'user_access'
Or if you have custom profile tpl then render tabs like this:

global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
  //*******render tabs here*********/
}


There is now also this module:
https://www.drupal.org/project/exclude_node_title


How can I save multiple images to one image field programtically?

I changed the following code:

 $content->images = array(
        'und' => array(
            $i => array(
                'fid' => $file->fid,
            ),
        ),
    );

to

$content->images['und'][$i] = array(
  'fid' => $file->fid,
);

And it worked


How to add a class to menu items that are not expanded (or don't have children) in the navigation Twig template?

Since Twig builds out the menu recursively the only way (I've found) to do this is to first check if the current item has any active children, and add a class to it once that is determined. So, before the li is posted, check if it has any children. Something like:

{% for child in item.below %}
  {% set children = item.below ? '1': '0' %}

  {% if children %}
    {# the current item has expanded/active children #}
  {% else %}
    {# the current item has no children #}
    {% set classes = classes|merge(['no_active_children']) %}
  {% endif %}

  <li{{ item.attributes.addClass(classes) }}>{{ link(item.title, item.url) }}
    {% if item.below %}
        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}
  </li>
{% endfor %}

Hope that helps.


In using the rule "OG new content notification," (rules_og_new_content) how can I insert the group name in the outgoing email

Add Action >> Get group members from group audience >> node

Add Loop >> node:og-group-ref

Add Loop inside loop >> group-members >> rename list_item to list_item2

Add Action >> Fetch entity by property >> User >> Mail >> list-item2:mail
Add Action >> Fetch entity by property >> OG Memembership >> field_name >> list-item:title >> rename entity_fetched to entity_fetched2
Add Action >> Send Mail >> list-item2:mail >> list-item:title

End Result:

(click image to enlarge)


Impossible to enable modules in SimpleTest

You should make triple-sure that your module declares all of its dependencies properly. Even if it does, Simpletest struggles with dependencies and you may have luck if you enable them explicitly in setUp() before your module.

Also, not sure if it's the contributing your error, but instead of $this->privileged_user = new stdClass(); I would use DrupalWebTestCase::drupalCreateUser like so: $this->privileged_user = $this->drupalCreateUser(). I might also declare it after setup() but I'm not sure that's significant.


Commerce: How to save user data (in the order date) when delete it

Interesting question.

Though I have never worked with Magento or Prestashop(I have made a simple site with it), so I don't know how they deal with it.

At first I saw your question two days ago & I didn't give much thought about it but today I came again & thought, why do we expect a contributed module to do everything for us? We all have to set our own store & can have different requirement...

Commerce Guys are great & have worked so hard to keep it tight with drupal as well as followed the same way which drupal has done to leave hooks for extending it anywhere you want..

You will have to make your own module for this & will have to play around a bit. It would be very interesting I promise.

There is a hook as I remember hook_commerce_checkout_complete() to get all the info of a order when you are going through checkout.
You can pass $order variable as parameter here & it will have all the value related to current order.
You can check like --

function MYMODULE_commerce_checkout_complete(){
  dpm($order);
}

Now go for buying anything on your instance and see what you get.

So the next you will do is...you can retrieve more data if you want(like user data if it exists in case of authenticate user or what ever you want to save for next) and save it in your own table.
Once you get data...there are many things which you can do now...make your own listing page by executing query or...expose your table to views so you get to feel the power of it for your own data too...

And as this is your table...removing your user or in case he deletes his account will never have any effect on this..GOOD!!


as per the various articles, its not good to have too much templates in drupal.

With respect, and depending on exactly what you mean by "too much", that's pretty much nonsense. If we're talking about 10,000 template files on an uncached site, then yeah, you would probably have problems. But those problems would be with your application's design; in the real world, with a normal application, that statement is just untrue.

  which approach is good and loads fast ?

Both are 'good' (or 'bad'), depending on your point of view, and how well you write the code for them; differences in load times will be negligible, especially with caching. If you're really worried about micro-optimising, then you need to benchmark your site, while it's under load and sitting on production hardware; that's the only way you'll know which method is faster for your use case.

It's not possible to give a blanket "this way is quicker" statement, because it depends on what the rest of the site is doing, how you have it and the server configured, and how good your code is. Always test in the real world rather than ask for others' experiences - you have no way to know if their experiences actually apply to your scenario.


How to update user profile after submitting a webform?

You can use the 'Rules' module to trigger an event when your webform is submitted. Using rules pull out the fields, compare them and update the Profile information if they have changed.

Webform integration: - http://drupal.org/node/474644

Hope this helps.


Get title field from another content type in exposed filter

You need to create views of one content type ie Project and add a relationship to your views which should say something like this Task Content referenced from Project. Require this relationship to exclude those projects which don't have tasks.

Now come to your filters and add title. In the setting now you will see use relationship dropdown. Select the relationship you added and you will get the required results.


Views - Test if field is visible via PHP

Data that you are looking for is located at $field->handler->options['exclude']. But it is tricky to get to.

When you mark the field as excluded, its data becomes inaccessible at the field's level in your View's template.

$row object also does not have any indication that the field was excluded via Views UI. $row contains only the value data from each field. You can confirm that by doing dsm($row); in your View template file (if you have devel module installed).

If you are overriding you View's template on the "Row style output" level, than the only object you can use to reach options['exclude'] from already excluded fields is $views.

You could do something like this at the top of your .tpl file:

foreach ($view->field as $view_field)
    {
        //check if field is excluded
         if ($view_field->options['exclude'] == 1) {
             // field is exluded - do something
             print $view_field->field.' is excluded from this view'; // print name of excluded field
             print $row->field_field_yourfieldname[0]['raw']['safe_value'];
        }
    }

so, if the field is excluded - it is going to be excluded in each row, according to that you can assign some markup or text to a variable and then print it anywhere down the template.


Translate was disallowed for HTML input in a view- how to enable?

By default, Filtered HTML and Full HTML are not available for translation.  You can override this by enabling the i18n module and visiting:

/admin/config/regional/i18n/strings (on Drupal 7)
admin/settings/language/configure/strings (on Drupal 6)

Just check the boxes for the text formats which you wish to enable.

Depending on your situation, you may also need to enable the i18n Views module.


Translate an SQL update query into Drupal language

You need to add an expression():

db_update('MYTABLE')
  ->expression('field_temp', "UNIX_TIMESTAMP(field)")
  ->execute();


How to change taxonomy url in node view page?

the code below replaces term/{%term_id} by node/39?technologie={%term_id} with THEME_preprocess_field :

use Drupal\Core\Url;

function MYTHEME_preprocess_field__FIELD_TAXO_MACHINE_NAME(&$variables, $hook){

    foreach ($variables['items'] as $index => $item) {

      $route_name = 'entity.node.canonical';
      $params     = 39;
      $tid = $item['content']['#options']['entity']->id();

      $options = [
        'query' => ['technologie' => $tid],
      ];

     $url = Url::fromRoute($route_name, array('node' => $params), $options);
     $variables['items'][$index]['content']['#url'] = $url;
  }
}


Filtering referenced nodes where logged in user is a member

Ok Organic Groups. I got a long way with the following recipe. Unfortunately I could not set up an identical environment to yours.

1 Add a Contextual filter on "OG membership: Group ID".

2 When the filter is not available Provide default value "The OG groups of the logged in user ". Leave the concatenator as "+".

3 Under More check "Allow multiple values"


How do I programmatically remove one breadcrumb link?

Drupal 7 and Drupal 8 are more or less the same in some aspects.

If you use preprocess_breadcrumb in your theme, you would do

function my_theme_preprocess_breadcrumb(&$variables) {
  array_pop($variables['breadcrumb']);
  ...
}

You could also solve this in the template file, by skipping the first item in {{ breadcrumb }}

If you want module only solution, you could swap the breadcrumb service with your own thing.


Prevent clicking on view tab when editing a node

See the content lock module:

  Features

  Concurrent editing:The user gets notified when he tries to
  edit a node, which is edited by someone else. He cant enter the edit
  mode.
  By node type: Configure content_lock to lock only specific
  nodes.
  By format: Configure content_lock to lock only specific input
  formats.
  No losing content by accident: User gets notified, if he
  wants to leave a edit form by abnormal conditions (close
  browser/window/link click). If the user confirms to leave, the edit
  lock gets automatically removed by an ajax call. You can disable this
  behavior in the admin menu.
  No forgotten locks: The user gets notified
  when he forgets to unlock a node. He/she will be asked to click on a
  link to unlock this node.
  Views integration: Show all open locks using
  any filters, as you have a views integration.


Here's want you need to do to modified the image field thumbnail thats display after you upload an image.

You will need to overwrite the imagefield_widget_preview theme function. You can drop this theme overwrite in the template.php file of your theme.

function THEMENANE_imagefield_widget_preview($item = NULL) {
  //By default this returns  theme('imagefield_admin_thumbnail', $item);
  //But If you're going to change it I would recommend replacing it with image-cache.
  //Also you should keep the imagefield-preview div.
  return '
' . theme('imagecache', 'your_custom_preset', $item['filepath'], $item['alt'], $item['title']) . '
';
}

This will replace the thumbnail images uploaded using image field.

Hope this helps.

Also remember, to use the name of the theme thats being used when editing. In-case you're using different themes.


Add textfield to system branding block form to specify link URL

A different approach: You can override the system branding block template via the block--system-branding-block.html.twig file (instead of using a preprocess hook).

On a Bootstrap theme, block--system-branding-block.html.twig looks like this:

{% block content %}
  {% if site_logo %}
    <a class="logo navbar-btn pull-left" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">

  {% endif %}
  {% if site_name %}
    <a class="name navbar-brand" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}
  {% endif %}
  {% if site_slogan %}

{{ site_slogan }}

  {% endif %}
{% endblock %}

You can alter the href of those links to point anywhere you'd like, for example:

<src="{{ site_logo }}" alt="{{ 'Home'|t }}" />


Need to redirect Parent Taxonomy Term page to oldest child

So I figured this out, wasn't too complicated at all.  Use hook_menu. I didn't write my SQL using the Drupal DB API, but it works:

function ain_custom_menu() {

 $items = array();

  // Item1
  $items['taxonomy/term/218489'] = array(
    'title' => 'Title1',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218489"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  // Item2
  $items['taxonomy/term/218500'] = array(
    'title' => 'Title2',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218500"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;

}

function MYMODULE_find_newsletter($mytid) {
  $tid = db_query('SELECT max(tid) AS tid FROM taxonomy_term_hierarchy t1
    JOIN field_data_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid
    JOIN node t3 ON t2.entity_id = t3.nid
    WHERE t1.parent = '.$mytid.' AND t3.status = 1')->fetchField();
  $latest = is_numeric($tid) ? 'taxonomy/term/' . $tid : '<front>';
  drupal_goto($latest);
}


OAuth2 Server sending 'null' as the 'sub' parameter instead of User Id

The code invoking that hook is the following one, in the OAuth2Storage.php file, line 750 and forward.
    // Prepare the default claims.
    $claims = [
      'sub' => $account->{$sub_property}->value,
    ];

    if (in_array('email', $requested_scopes)) {
      $claims['email'] = $account->getEmail();
      $claims['email_verified'] = $this->configFactory->get('user.settings')
        ->get('verify_mail');
    }

    if (in_array('profile', $requested_scopes)) {
      if (!empty($account->label())) {
        $claims['name'] = $account->getDisplayName();
        $claims['preferred_username'] = $account->getAccountName();
      }
      if (!empty($account->timezone)) {
        $claims['zoneinfo'] = $account->getTimeZone();
      }
      $anonymous_user = new AnonymousUserSession();
      if ($anonymous_user->hasPermission('access user profiles')) {
        $claims['profile'] = $account->toUrl('canonical', ['absolute' => TRUE]);
      }
      if ($picture = $this->getUserPicture($account)) {
        $claims['picture'] = $picture;
      }
    }

    // Allow modules to supply additional claims.
    $claims += $this->moduleHandler->invokeAll('oauth2_server_user_claims', [
      'account' => $account,
      'requested_scopes' => $requested_scopes,
    ]);

    // Finally, allow modules to alter claims.
    $context = [
      'claims' => &$claims,
      'account' => $account,
      'requested_scopes' => $requested_scopes,
    ];
    $this->moduleHandler->alter('oauth2_server_user_claims', $context);
    return $claims;

Since the code first sets $claims to ['sub' => $account->{$sub_property}->value] and then adds any array key returned from that hook with $claims += $this->moduleHandler->invokeAll('oauth2_server_user_claims', ['account' => $account, 'requested_scopes' => $requested_scopes]); the hook cannot change the value for the sub key. You can verify how PHP behaves with the following simpler code.
$array = ['sub' => NULL];
$array += ['sub' => 10, 'id' => 10];
print_r($array);

To alter the sub key, the module should implement hook_oauth2_server_user_claims_alter().
function my_module_oauth_server_user_claims_alter(&$context) {
  if (in_array('profile', $context['requested_scopes'])) {
    $context['claims']['sub'] = $account->id();
    $context['claims']['user_id'] = $account->id();
  }
}


Serializer settings: force using field & json

Show: fields

Show settings: type an alias for each field

Above settings are shown in the images below


I would suggest doing as a Drupal module does: the Blog module. That is the correct code to use for a module that defines its own content type.

In the installation file, the code the Blog module uses is the following.

function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

In the module file, it implements the content type hooks, which are:

hook_form()
hook_node_info()
hook_view()

Another Drupal core module that implements its own content type is the Forum module. Differently from the Blog module, the Forum module adds a field to the nodes of its content type. The code it uses to set its content type is similar, though. (See forum_enable().)

  // Ensure the forum node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['forum']);

Notice that Drupal core modules don't remove the content type they define, when they are uninstalled; eventually, they remove any field they attached to their content type. (See forum_uninstall().)

As side note, the string passed to t() contains English words, not in other languages.


It is easy to expose taxonomy term as filter in views. Unfortunately, in Drupal 7, the content list is not built by views.

Administration Views is a module which can replace it with the views Administration: Nodes.

In the views, you can add Content: Has taxonomy term filter and expose it. But it only support ONE vocabulary.

How about having a term filter on more then vocabulary? It is quite tricky, but not impossible.

First, add a relationship Content: Taxonomy terms on node, and check the vocabularies. In example, they are tags and topics.

Then, now you can add filter Taxonomy term: Name, this filter only appear when you added the taxonomy term as relationship.

In Operator, there are many options, you can pick a suitable one for your case. I chose Contains in my example.

  Note:

  With this method, you will have a ordinary text field rather then autocomplete field. It is the only downside.


How do I limit the number of rows affected from the query?

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/class/Select/8.6.x

$query->range(0, 500);


How to delete message entities (message stack) of a special template depending on entity age

It's possible to override the cleanup/auto delete settings in the message template configuration (even via UI) per template. Just visit the template configuration form.


You get the delete option in the block configuration page for those blocks that have been created using Add Block option (in Admin >> Site Building >> Block). In your case the menu block in question might have been created programatically using hook_block or any other means that I'm not aware of and the Delete link might not appear due to the same. Suggest that you identify the code/module responsible for generating the block before you proceed on to anything. Also if you wish to replace this block with something more easily configurable I'd suggest using Nice Menus which I feel is a wonderful module


The default frontpage view provides what you need as long you print $feed_icons; in your page.tpl.php


Form submission with AJAX to override a block content

Remove the data table from the block

public function build() {
    $filterForm = \Drupal::formBuilder()->getForm('Drupal\smeno\Form\FilterForm');

    $renderArray['filterform'] = $filterForm;

    return [
       '#theme' => 'Remboursement-sur-compte',
       '#McRefund_build_data' => $renderArray,
    ];
}

and add it to the form (placed in a wrapper):

  $form['McRefund_data'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'table-wrapper'],
    'table' => $this->getMcRefund(),
  ];

Attach this ajax callback to a form element

          '#ajax' => [
            'event' => 'click',
            'callback' => '::updateTable',
            'wrapper' => 'table-wrapper',
            'progress' => [
              'type' => 'throbber',
              'message' => t('Verifying entry...'),
            ],
          ],

and replace the table in the ajax callback:

  public function updateTable(array $form, FormStateInterface $form_state) {
    return $form['McRefund_data'];
  }


Button on user profile page to send email

To get what you want, you need to modify the template user, to do this you need to follow the next steps:

Find the file called user-profile.tpl it is in the module user modules\user (NOT inside sites/all/modules).
Once you found it, open it, and you should see at the end of the file something like this:

  print render($user_profile);

Now copy and paste this line of code inside php tags:

  $usr = user_load(arg(1));

  echo 'mail.'?Subject=textyouwant"
  target="_blank">Send Mail';

That should work !


Deleting the "Language" module - a dangerous move?

The Drupal 8 language module is disabled by default.  Uninstalling it just sets it back to its default state.  This is not "dangerous".


you need to call the function YOURTHEME_form_alter(), where YOURTHEME  is the name of your theme. Eg, the Bartik theme would have such a function called bartik_form_alter() ... you must also clear your drupal cache for the changes to take affect.

EDIT

you make your code like this:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
        case 'user_register_form':
            $form['account']['mail']['#description'] = t('E-mail Address');
    }
}

if you call your theme "sky" it would be sky_form_alter.


Based on the comment of the OP (Niels) I changed my answer:

Each content type page will have a different class (node-type-CONTENTTYPE) associated to the BODY element of your HTML.

So you can add to your CSS file:

body.node-type-mycontenttype1 img { border-color: red; }
body.node-type-mycontenttype2 img { border-color: yellow; }

Original answer:

Wich version of Drupal do you use?

For Drupal 7:

You can use a different template for each node of different content type by creating a template:

/site/all/themes/YOUR THEME/templates/node--CONTENTYPE.tpl.php

You can read on Template Suggestions to know which template you can create.

For the CSS, I suggest you to put everything in your main CSS file and not use a different CSS for each content type.


How do I programmatically set contextual filters?

Contextual filters use query string params.  You could hard code these into the URL.  If using a Url object, you can pass a third argument ['query' => ['param1 => 'param1_value',...]].  Try setting a filter and seeing what the URL param name & value is after doing so.

In hook_views_pre_build(), you can also set the filter value directly:

$view->filter['filter_name']->value = 'filter_value';

It's helpful to have Xdebug so you can see the names of existing filters.  If you don't have xdebug, try finding the correct filter name in the ->filter property, then find the desired filter value, and put 2 and 2 together.


As far as I know you can not reference a webform submission from another webform. The functionality you describe is needed here is something I recommend using standard Drupal content types for.

Create a content type called Vendor and another one called Sponsor. Use the module Entity reference to create a field that describes the reference between the content types.

Webforms are great for simple forms, surveys etc but not in this use case.


Management of priorities with node_access

If you install the Devel module, there is a sub-module called Devel Node Access (DNA) that you can also enabled.

When you do this, two new blocks will become available.  One shows node access by users.  The other shows the access records for the node you are viewing (or the nodes that happen to be on that page), both hook_node_access() and grants.

Typically, I will install both blocks at he bottom of the Content region, as they can be big/wide, and only give their view permission to a few users.  If I am having grant weirdness, then I give the permission to all on a test site, and use user masquerading to see what is happening.

And as for priorities, this is described fairly well in the documentation on node access rights.  In short:

Deny by default
Check for bypass access permission
Call hook_node_access() per Drupal module ordering.  First denier wins, then first allower wins.
If there isn't a winner, hook_node_grants() is run per Drupal module ordering to build the list of grants.  Then tirst denier wins, then first allower wins.
Otherwise deny.

Try to read through node_access(), after the node access rights page, for the finer details.


Migrate_d2d: Excluding node import based on a date comparison

You have to do this in prepareRow. Whatever value is mapped to field_job_start, check its value there and return FALSE.


In the Views module you can add this field:

Content: Updated date, The date the content was last updated.


Views pager uses wrong URL when using views_embed_view()

Manually set $_GET['q'] to the appropriate value before calling views_get_view().

Views' pager uses the standard Drupal pager from includes/pager.inc which uses this request variable:

function theme_pager_link($variables) {
  // (... code omitted here ...)

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}


First, You need to find out the correct form id for this form and then you can use,

hook_form_FORM_ID_alter there.

Thanks


How to install a distribution on Docker using ddev composer command?

Note difference. First the official command.

ddev composer create ...

And now the command you executed.

ddev composer create-project ...

See? DDEV provides its own command to create a project. So just adding ddev in front of any composer command doesn't always work. Instead it's ddev composer create ....


Changing a dropdown based on another one

If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '
',
  '#suffix' => '
',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

In your case you will have to do it in a hook_form_alter and add the #ajax property to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :


Outputting different class other than default for status messages

This is just some good old PHP logic, is this what you're after?

function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );

  // Map our drupal statuses to bootstrap classes
  $bootstrap_statuses = array(
    'status' => 'alert-success',
    'error' => 'alert-error',
    'warning' => 'alert-warning',
  );

  foreach (drupal_get_messages($display) as $type => $messages) {
    // Grab the bootstrap class that corresponds to $type
    $bootstrap_class = $bootstrap_statuses[$type];
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

You could even put the $bootstrap_classes and $status_heading arrays together. But I separated them for simplicity


after adding the custom field to the user profile, i added a hook_form_alter() in seven theme template. (it should be added in administrative theme).

in this hook i read the user custom field using $user_full = user_load($user->uid)

setting global $user; is required to use $user in template.php

now i can modify other forms according to user custom field content

that's all


How to display the selected value from the drop-down box?

form_test_form_submit is called in php that's not displayed to user. Form is processed, it's values saved, and user is taken to desired page. Now you have 2 options:

In submit handler set$form_state['redirect'] to a page you like. Save values to a database. On target page read them and display.
In validation handler add markup elements with selected values, if you want to emphasize selection but leave user on a form.


Why is Views ignoring nid as second argument?

It seems that views ignores the second argument in case the first argument is not present, although the first argument is configured to show all values if it is not present. Setting the following PHP code as default argument for the taxonomy term solves my problem:

if (arg(0) != 'taxonomy') {
  return 'all';
} else {
  return arg(2);
}


user login form: name and password default values

Usually, it's the browser that remembers login names and passwords, allthough some sites place a cookie upon successful login that they use to populate the username field on your next visit.

I don't think Drupal does this by default so I think in your case, it's the browser that remembers the login name and password.

There is one way to avoid this and that's by changing the name of the form fields. Browsers 'know' to remember usernames because the name of those fields is usually something like 'user', 'username' or 'login'.

If you change the name attrribute of the login input field to, say, 'bycicle', browsers will stop remembering those values automatically.


If a comment is 'auto approved' as you call it, depends on the user's permissions. To change it, log in as administrator, go to /admin/user/permissions#module-comment and make sure that the 'post comments without approval' permission is not set for roles that are not allowed to post comments without approval.


Yes, db_query() does support UNION. I had a problem with my query:

WHERE agent_number IN (':agent_numbers')

Should be:

WHERE agent_number IN (:agent_numbers)


How to change error-message displayed @ failed form-element validation to be different than the element's '#title" text?

Using a basic form in a custom module:

    function customform_demo($form, $form_state) {
    $form['test'] = array(
        '#type' => 'checkbox',
        '#title'    => t('This is the text that gets displayed next to the checkbox'),
        '#required' => TRUE,
    );

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

    return $form;

}

You can set a custom error message in the form validation function. Here is a basic example with some comments:

    function customform_demo_validate($form, &$form_state) {

    // Test for existing form errors
    if (form_get_errors()) {

        // Save errors
        $form_errors = form_get_errors();
        $drupal_errors = drupal_get_messages('error');

        // Clear form errors
        form_clear_error();

        foreach($drupal_errors['error'] as $key => $error) {
            if (in_array($error, $form_errors)) {
                // Unset form errors
                unset($drupal_errors['error'][$key]);
            }
        }

        // Rebuild drupal errors
        foreach($drupal_errors['error'] as $key => $message) {
            drupal_set_message($message, 'error');
        }

        // Validate form field and set error message
        if ( $form_state['values']['test'] === 0 ) {
            form_set_error('test', t('You forgot to check the required checkbox. Please try again.'));
        }

                // Add more validation tests and error messages

    }
}


Drupal 8: make Taxonomy terms translatable

To translate terms of taxonomies, you need to activate the Content Translation module.


OK I've got drush working:) For other people who might have a similar problem (hope I use the right terms):

I had to install "php5-mysql" (and dependencies) in Linux (for example through "synaptic package manager"), php5-mysql is a MYSQL module for PHP5 which contains mysql PDO support. With this I was able to enable modules and use the omega commands. Drush uses the PHP installed in Linux and not in Xammp, I had this module in Xampp but not in Linux.

You can see which php.ini file drush uses by typing "drush status" in your terminal.

You can see which php.ini file is used by your web server by navigating to admin/reports/status of your drupal site. Next click the "more information" link on Drupal's status page's PHP section. This shows the phpinfo() page. Locate the Configuration File (php.ini).

To check that the mysql PDO support is installed (part of "php5-mysql"), type the following in a terminal:
php -i|grep PDO
If support is installed you should see something like this:
PDO
PDO support => enabled
PDO drivers => mysql
PDO Driver for MySQL => enabled


Alter dynamically line item price on cart (drupal commerce)

Have you read any of the product pricing rules documentation or watched the tutorials on DrupalCommerce.org? It's all in there: http://www.drupalcommerce.org/user-guide/product-pricing-rules-screencasts

In other words, you shouldn't be hooking into anything, you should be using Drupal Commerce's core product pricing rules system. This is the only supported way to make consistent line item unit price alterations that are reflected in the final order total.


Is it possible to get a clean url to be used in Views comment counts?

I'm not sure this can be done through rewriting, it's quite limited and never has given me what I want. At any rate you could be better off if you used the row-theming technique, which is in turn powerful. Then you could build your own links the way you want, wrapping the URLs in drupal_get_path_alias to get nice-looking addresses.


Add intro text before profile 2 form in the registration page

You can use the markup module to display text. It is available as a field element.


The code in the question is mixing three different types of templates:

Custom twig template in a controller
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/create-custom-twig-templates-for-custom-module

Overriding form.html.twig
How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?

Adding a custom form template
How to render specific form elements from the *.theme file

The confusing part of your question is that you are using the same template reset-pasword.html.twig for 1. and 3.
The issue discussed in the comments about the special form elements applies only to 2.
You can use all three template levels at the same time. Then they are nested inside of each other which you see when you enable twig debugging.
More info Custom registration twig template.


Editing content redirects to apache test page?

This was an issue with mod_security.  Disabling it fixes the problem...but is not advised.


How do I disable a module for the First Sidebar?

On the Captcha configuration page (admin/config/people/captcha) you can set which forms should display a Captcha.

By default, all user forms get a Captcha challenge. Set them to "No challenge", add the form ID of your comment form to the list and choose the challenge you want.


This line says it all:
    Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

Probably not a problem you or Aegir could do anything about. Just an Internet hickup.


Drupal 7: LDAP: How to fetch user information on a webform

Figure out the raw ldap queries you need. Outside of php or drupal.
Write them down.
Use ldap views module to make reusable drupal ldap queries. ldap views can use tokens and I think parameters in queries ... parameterize as needed.

Then wherever you want your custom message embed the view results onto the page using Context, Panels, hook_page_build .... whatever.


Why using of custom date format makes my Drupal date outdated and does not change at all?

Instead of manually inserting stuff in the database, make use of the Drupal API. The blog post Exporting and maintaining custom date formats in Drupal 7 is a great tutorial. It's geared towards modules but I'm pretty sure you can do this in an install profile too.

I think this will solve your problem, and even though I'm not 100% sure, I would always recommend to use the API.

Here's a quick copy-paste of the most important code from that blog post, just in case the link would break in the future:

/**
 * Define and export date formats.
 */

// Give the date format type a machine name.
define('MODULENAME_DATE_TYPE', 'MODULENAME_date_type');

// Define the string to be passed to date().
define('MODULENAME_DATE_FORMAT', 'l, jS M Y ');

/**
 * Implements hook_date_formats().
 */
function MODULENAME_date_formats() {
  $formats = array();
  $formats[] = array(
    'type' => MODULENAME_DATE_TYPE,
    'format' => MODULENAME_DATE_FORMAT,
    'locales' => array(),
  );
  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function MODULENAME_date_format_types() {
  $types = array();
  $types[MODULENAME_DATE_TYPE] = t('Default date for MODULENAME');
  return $types;
}

The blog post also provides a utility function to clean up old, unused date formats:

/**
 * Delete cruft date formats from the database and resync date formats/types.
 *
 * Call this as often as required to ensure date configuration stays in-sync.
 * Don't call this on every page load. hook_flush_caches() or hook_update_N
 * are good candidates.
 */
function _MODULENAME_purge_date_formats() {
  $formats = system_get_date_formats(MODULENAME_DATE_TYPE);
  variable_set('date_format_' . MODULENAME_DATE_TYPE, MODULENAME_DATE_FORMAT);

  // Date formats without a dfid are being read directly from code. We can use
  // the existence of this value to detect "ghost" formats that are not managed
  // in this file.
  if (!empty($format['dfid'])) {
    system_date_format_delete($format['dfid']);
  }
}


Placing result count below Views exposed filters?

Ad summary of the result in the head of the vieuw and reposition this div with css to the place where you want to put it.


On Cron run Open and save all Profile2 based user profiles

profile2_load_by_user returns either a single profile or an array of profiles keyed by profile type. profile2_save expects a single profile.

It looks like in your particular case array is returned, so you need to:

Test what you got from profile2_load_by_user
If it's a single profile, use profile2_save directly.
If it's an array, either select the array element you need, or foreach over that array, calling profile2_save on each element.


CKEditor generates  when leaving a textarea field empty

There is an issue tracking this problem on drupal.org - http://drupal.org/node/550428. There is a patch in comment number 49 for it, hope it helps.


How to find an article title for specific post

As with everything there are a few ways to do this. Here are a couple, if you know the node id.

Do a query on the node table:select title from node where nid = KNOWN_NODE_ID

Use a Drupal function:
$node = node_load(KNOWN_NODE_ID);
$nodeTitle = $node->title;


Override field module function in custom module?

You could try hook_field_storage_info_alter

Other candidates are

hook_field_insert
hook_field_update


How to check if a term has a published content associated with it?

There is an existing Question that handles this for views 2 and views 3: https://stackoverflow.com/questions/421972/how-to-display-only-taxonomy-terms-with-nodes-associated-to-in-views-2


There is no module you can use with your situation.
Possible way.

Create separate menu and place them in each block.

Please describe your scenario so that we can discuss more.


You should not be wrapping your keywords in p tags. P is a block-level element, and that is why it stretches 100% width of your container.

Use mark, span or any other inline-level element instead.


How to display a customized button on a single form only?

Find the form id first.

Assume your form id is 50 than,

function <module>_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_50') === 0) {
    $form['actions']['reset'] = array(
      '#type' => 'button',
      '#value' => t('Reset'),
      '#weight' => 100,
      '#validate' => array(),
      '#attributes' => array('onclick' => 'this.form.reset(); return false;'),
    );
  }
}

OR

 if ($form_id == 'my_webform_client_form_id') {

Your code

}

Another method :-

In Drupal 7, you can either use hook_form_alter() or hook_form__alter(), which ever you prefer. Just make sure you get the naming and parameters right. Drupal 6 only supports hook_form_alter() however.

When you create these functions, also remember that Drupal may not always pick up on them until you've flushed the cache.

function mymodule_form_webform_client_form_44_alter(&$form, &$form_state) {
// code here;
}

Please remember to clear your cache also and try to disable/enable your module also


Drupal 7 CKEditor while replacing from textarea media files are not rendering

After a long research I found one solution from here.

The patch they provided works for me.

https://www.drupal.org/files/issues/interdiff_8413.txt

I will leave this question open, so that others can get some help from this.


Taxonomy: Show select options as a dropdown, not multiple

To get a taxonomy entity reference to show as a dropdown, there are two things you need to do.

Go to the "manage form display" (admin/structure/types/manage/MY_CONTENT_TYPE/form-display) for your content type and make sure the Widget for the term field is set to Select list.
Go to the "manage fields" for your content type and click "edit" for the entity reference for your terms.  Go to the "Field settings" tab and make sure the Allowed number of values is 1.  If this is set to 2 or more, Drupal will give you a multiple select, not a dropdown.


How do I put registration form in panel in Drupal 7

fucntion YOURMODULE_block_view($delta = ''){
  switch($delta){
    case 'YOURBLOCKNAME':
    $block['content'] = drupal_get_form('user_registration_form');
    break;
  }
}

Or if you want to theme the block first, then register a theme hook in YOURMODULE_theme().

function YOURMODULE_theme(){
  $return['custom_user_reg']= array(
    'render element' => 'form',
    'arguments'=> array('form'=> null),
    'template' => 'templates/form--user-registration',
  );
  return $return;
}

function YOURMODULE_block_view($delta = ''){
  switch($delta){
    case 'YOURBLOCKNAME':
    $form = drupal_get_form('user_registration_form');
    $block['content'] = theme('custom_user_reg', array('form'=>$form));
 }

Then in form--user-registration.tpl.php:

print render($form['email']);
print render($form['name']);
print drupal_render_children($form);

Of course you can add as much html in your tpl file as you want/need.


Normally you would configure the formatted output of an image field in the content type and then render it in the node template:

{{ content.field_image }}
{{ content|without('field_image') }}

If you want to access the path of a private file directly then use the file scheme private://:

{{ file_url('private://foo.jpg') }}


Installed Drupal 8 in English, added Hebrew, deleted English and now site is malfunctioning

My solution is comprised of part1, and part 2:

Part 1

For some reason, from the moment I deleted the English, each time I went to the pages in the site, including the one I could it bring it back in (admin/config/regional/language/add) all of these urls included an "he" (Hebrew) part. For example the add language page was:

he/admin/config/regional/language

But when I changed the he to en (English) than for some reason I could re-add the English language!

But, even thought it seemed I finished with the problem, another one came in, which I also had to solve:

URL's in the site still redirected with "he" parts even after I deleted the Hebrew language from the language lists, and thus I couldn't even flush all caches from the ui because the URL that instructs cache flushing started with an "he" part.. in the following part 2 I will describe how I solved that:

Part 2

After I re-added English, and deleted the Hebrew language from the list, I went to the "Detection and selection" tab under "Languaes" at admin/config/regional/language/detection, and unchecked there the option URL: `Language from the URL (Path prefix or domain), and than I flushed all caches with Drush (the Drupal CLI) and the problem was solved.

I than re-added Hebrew and setted it default language without any problem; Since I changed it's influence on URL's under the "Detection and selection" tab at the Languages page, I didn't have the "he"\"en" parts problem after that.


default_content import error field content_translation_source is unknown

Content translation module was enabled but content translation was not enabled for custom block. Enabling it fixed the error.


ok add hook_menu that call this function

if you have module called wow

function wow_menu() {
  $items = array();
  $items['home'] = array(
    'title' => '',
    'page callback' => 'wow_page',
    'access callback' => TRUE,
  );
  return $items;
}


There is a guide on drupal.org with multiple troubleshooting methods to resolve white screens with no ouputs: https://www.drupal.org/node/482956


How to change the user registration form markup

You can do that by implementing hook_form_alter() in your custom module:

For ex:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    //dpm($form);
    $form['account']['name']['#description'] = t('Your Custom Text');
  }
}

To add Markup you should look into theme_form_element.


Attempt to create an instance of field that already has an instance of that field

The function you are looking for is field_info_instance($entity_type, $field_name, $bundle);

for example:

field_info_instance('node', 'field_tags', 'article');

will return the field instance if a field 'field_tags' exists on nodes of the content type 'article', NULL otherwise.


I think you may be able to do this by using the global $user variable.

1 create the hooks block_info and block_view
create hook_theme()
define a theme to be able to pass variables to template.
create the template

in your block_view do something along the lines of this:

switch($delta){
    case 'myvideoblock':
            global $user;
            $view = views_get_view('YOURVIEW');
            $view->set_display('YOURDISPLAY');
            $view->set_arguments($user->uid);
            $result = $view->execute;
            $your_variable = $result->result;
            $block['content'] = theme('videoblock', array('your_variable' => $your_variable));
}

You should poke around in the $result->result object to get to your content though.

Hope this helps


You need to:

Add Condition >> Content is of Type >> [your content type]

OR

Add Condition >> Entity Has Field >> node:field-telefon

Add Condition >> Entity Has Field >> node:field-signatur

OR

Add Action >> Fetch Entity by Property >> Node >> telefon >> node:field-telefon

Add Action >> Fetch Entity by Property >> Node >> signatur >> node:field-signatur


How to display comments of current node in a view

You need a contextual filter.  In your view, remove comment:nid from the Filter Criteria.

Next, on the far right, under "Advanced", add a "Contextual Filters" and select comment: nid there.

In the configuration options, under WHEN THE FILTER IS NOT AVAILABLE, select "Provide Default Value".  From the Type dropdown, select "Content ID from URL".

Click Apply, save your view, and add the block as normal.


The solution above is for Drupal 7. In Drupal 8, hook_views_ajax_data_alter is deprecated and was replaced by hook_ajax_render_alter.

For those of you looking for it, here is how to do it in Drupal 8 (source here).

function YOURMODULE_ajax_render_alter(array &$data) {
  foreach ($data as $key => $command) {
    if ($command['command'] === 'viewsScrollTop') {
      unset($data[$key]);
      break;
    }
  }
}


Starting a views list from the nth element

Yes you can, Under pager settings, offset first four items. Click on the number of items to get this option

and on the page option settings change the offset.


Can a pager item point to an anchor on the page?

Have you looked at theme_pager_link in Drupal 7. Your site's theme can customize any pager link by implementing YOURTHEME_pager_link and then add additional logic into a copied version of that function to embed anchors as needed.

You can probably embed the anchor as a parameter to the link to be inserted into the querystring:

  parameters: An associative array of query string parameters to append
  to the pager link.


How can I force changes to go to settings.local.php?

I think it's possible, but you'll need a custom installation profile to do it.

drupal_rewrite_settings() takes a 2nd parameter for a custom path to settings.php, but none of the default core methods make use of it, they let it fallback to sites/default/settings.php. It's used in three key places:

Drupal\Core\Installer\Form\SiteSettingsForm::submitForm()
drupal_install_config_directories()
install_write_profile() (deprecated)

The form and install_write_profile() are invoked from an install task, so those can be altered with hook_install_tasks_alter(). drupal_install_config_directories() is invoked from the form submit method, which you'll be overriding anyway, so you can replace it with your own method.

A completely untested example:

profiles/foo/foo.profile

function foo_install_tasks_alter(&$tasks, $install_state) {
    $tasks['install_write_profile']['function'] = 'foo_install_write_profile';
    $tasks['install_settings_form']['function'] = 'Drupal\foo\Form\SiteSettingsForm';
}

function foo_install_write_profile($install_state) {
    // Only need to write to settings.php if it is possible. The primary storage
    // for the install profile is the core.extension configuration.
    $settings_path = \Drupal::service('site.path') . '/local.settings.php';

    // Make sure the file exists.
    touch($settings_path);

    if (is_writable($settings_path)) {
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];
        drupal_rewrite_settings($settings, $settings_path);
    }
    elseif (($settings_profile = Settings::get('install_profile')) && $settings_profile !== $install_state['parameters']['profile']) {
        throw new InstallProfileMismatchException($install_state['parameters']['profile'], $settings_profile, $settings_path, \Drupal::translation());
    }
}

profiles/foo/src/Form/SiteSettingsForm.php

namespace Drupal\foo\Form;

use Drupal\Core\Installer\Form\SiteSettingsForm as BaseForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Crypt;

class SiteSettingsForm extends BaseForm {

    public function submitForm(array &$form, FormStateInterface $form_state) {
        global $install_state;

        // Update global settings array and save.
        $settings = [];
        $database = $form_state->get('database');
        $settings['databases']['default']['default'] = (object) [
            'value'    => $database,
            'required' => TRUE,
        ];
        $settings['settings']['hash_salt'] = (object) [
            'value'    => Crypt::randomBytesBase64(55),
            'required' => TRUE,
        ];
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];

        $settings_path = \Drupal::service('site.path') . '/local.settings.php';
        drupal_rewrite_settings($settings, $settings_path);

        // Add the config directories to settings.php.
        $this->installConfigDirectories();

        // Indicate that the settings file has been verified, and check the database
        // for the last completed task, now that we have a valid connection. This
        // last step is important since we want to trigger an error if the new
        // database already has Drupal installed.
        $install_state['settings_verified'] = TRUE;
        $install_state['config_verified'] = TRUE;
        $install_state['database_verified'] = TRUE;
        $install_state['completed_task'] = install_verify_completed_task();
    }

    protected function installConfigDirectories() {
        global $config_directories;

        // Add a randomized config directory name to settings.php, unless it was
        // manually defined in the existing already.
        if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
            $config_directories[CONFIG_SYNC_DIRECTORY] = \Drupal::service('site.path') . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
            $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) [
                'value' => $config_directories[CONFIG_SYNC_DIRECTORY],
                'required' => TRUE,
            ];
            // Rewrite settings.php, which also sets the value as global variable.
            $settings_path = \Drupal::service('site.path') . '/local.settings.php';
            drupal_rewrite_settings($settings, $settings_path);
        }

        // This should never fail, since if the config directory was specified in
        // settings.php it will have already been created and verified earlier, and
        // if it wasn't specified in settings.php, it is created here inside the
        // public files directory, which has already been verified to be writable
        // itself. But if it somehow fails anyway, the installation cannot proceed.
        // Bail out using a similar error message as in system_requirements().
        if (!file_prepare_directory($config_directories[CONFIG_SYNC_DIRECTORY], FILE_CREATE_DIRECTORY)
            && !file_exists($config_directories[CONFIG_SYNC_DIRECTORY])) {
            throw new Exception(t('The directory %directory could not be created. To proceed with the installation, either create the directory or ensure that the installer has the permissions to create it automatically. For more information, see the online handbook.', [
                '%directory' => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
                ':handbook_url' => 'https://www.drupal.org/server-permissions',
            ]));
        }
        elseif (is_writable($config_directories[CONFIG_SYNC_DIRECTORY])) {
            // Put a README.txt into the sync config directory. This is required so that
            // they can later be added to git. Since this directory is auto-created, we
            // have to write out the README rather than just adding it to the drupal core
            // repo.
            $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
            file_put_contents(config_get_config_directory(CONFIG_SYNC_DIRECTORY) . '/README.txt', $text);
        }
    }

}

The last step, if you want this to be fully automated and possibly avoid errors during installation, is an awkward one. You need to programatically uncomment the include for local.settings.php at the bottom of settings.php.

I'm not aware of any Drupal helpers for that (might be wrong though), so you can probably approach that as a general PHP/other task.

I think the top of the foo_install_write_profile() function would be as good a place as any to do it, unless of course your dev workflow means you can do it before you even carry out the installation (probably best if possible).


Try this:

$menu = menu_navigation_links('menu-your-custom-menu-name');
print_r (theme('links__menu_your_custom_menu_name', array('links' => $menu)));

Source: How to print a menu in Drupal 7 ? and the next comment is also useful: printing custom secondary menu when the user is logged out.

Changelog for Drupal 7: Use #theme='links_MODULE' or #theme='links_MODULE_EXTRA_CONTEXT' when adding links to a render array.

Edit: new version using menu_tree()

$menu = menu_tree('main-menu');
$menuhtml = drupal_render($menu);
print_r($menuhtml);


Display suite's adding custom fields loads eternally

all these are the view modes like teaser,full content etc.whenever you create any panel ,there will be tabs of full-content etc...then u can edit the settings displayed below these tabs..here these buttons would be visible...


Since you don't want to use the user interface, the only way to provide a translation of the string used from modules is to set them in the settings.php file.

$conf['locale_custom_strings_it'][''] = array(
  'forum' => 'Tavola di discussione',
  '@count min' => '@count minuti',
);

Replace "it" with language code for which you want to provide the translation. The array index is the string in English, while the array value is the translated string.

Using this method is pretty hard: Each times a new string is translated, the settings.php needs to be edited. There could be also some performance issues, as you are defining a new array row for every new translation; I let you imagine what happens when you have 1000 strings to translate in 5 languages.

When those values are provided, the database is not anymore looked up, as t() contains the following code. (See the first comment.)

  // First, check for an array of customized strings. If present, use the array
  // *instead of* database lookups. This is a high performance way to provide a
  // handful of string replacements. See settings.php for examples.
  // Cache the $custom_strings variable to improve performance.
  if (!isset($custom_strings[$options['langcode']])) {
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
  }
  // Custom strings work for English too, even if locale module is disabled.
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
  }
  // Translate with locale module if enabled.
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
    $string = locale($string, $options['context'], $options['langcode']);
  }
  if (empty($args)) {
    return $string;
  }
  else {
    return format_string($string, $args);
  }


entityform view filtered by current user field (term reference)

Since you want to list entities that use the same term reference as the user account, its best to create a view of terms and add relationships to the user and entityform.

Add the entityform fields that you want, using the entityform submission relationship.

Then add the term reference field two times, one with the user relationship and one with the entityform submission relationship. You may hide these fields.

Then add filter 'field comparison', selecting both term reference fields, and choose 'is equal to'.
Also add the filter User (using relationship) is 'currently logged in user'

The result is a view showing entityform submissions that have the same term reference value (department) as the currently logged in user.


How can I get additional fields from Search API query?

Unfortunately, it looks like this is impossible.

Looking at \Drupal\search_api_db\Plugin\search_api\backend\Database::search:

  $result = $db_query->execute();

  foreach ($result as $row) {
    $item = $this->getFieldsHelper()->createItem($index, $row->item_id);
    $item->setScore($row->score / self::SCORE_MULTIPLIER);
    $results->addResultItem($item);
  }

The $item will receive only the item_id from the fetched row, so all added fields are lost :(


How to get "empty line items" in Commerce, similar to Ubercart?

In Drupal Commerce, we made the decision to add line item type dependent callbacks to the line item API. A product line item will function differently from a shipping line item will function ... etc. As a side effect, this means there is no such thing as a "generic" line item, just like there is no such thing as a typeless node.

What needs to happen, if it doesn't already exist, is a small contrib module could be made that adds a basic line item type whose "line item add form" in the order edit page lets you specify all the information needed to manage and display that line item. Where it's gonna break down are things like pricing rules - should these line items have taxes? Should other discounts apply? Or display rules - should these show up on customer order pages?

There is no such feature in core (as you can see, it'd be a small contrib, but it wouldn't be trivial to make), but if it were tested and proved as a concept in contrib, I don't see why we couldn't consider it for inclusion in Commerce 2.x.


How to open quicktab tab from external page (after clicking link url)

right click with mouse on the Quicktab in question, and copy url. Then use that url on your slider.


How do I assign a view to a panel node in drupal

If you are display the panel on a node then you need to add a variant of the node/%node page. In Drupal 7 you would

Edit the node_view (node/%node) page.
Press Clone to create a variant of your current page.
Under Selection rules add Node:type and select your new content type.
Ensure that the new variant is above your current variant, or add Selection rules to your current variant too.
In your new variant under Content replace the old View with the new View.

Note: If the only change to the View (and Page) is the Content type then you could have used the Content type of the node being viewed as a Contextual filter on the View. Then there would be no need for a Panel variant or another View.


How to display cck node fields' values at the search result page?

In your theme, you can use template_preprocess_search_result()

function YOURTHEME_preprocess_search_result(&$variables) {
  if ($variables['type'] == 'node') {
    $node =& $variables['result']['node'];
    //Do something here
  }
}

Or, you can also implement hook_nodeapi() in a custom module for $op = 'search result'. The result of hook_nodeapi($node, 'search result') is available in $info_split in the search-result.tpl.php template.


It's really simple.

On Drupal 6/7, set the "#access" property of the fieldset to FALSE, or use logic to determine visibility.
This will also hide all the content of the fieldset, and yet keep the values intact so that when the form is submitted they are not cleared, but retained.


how to map comments in drupal migrate module

I got it, you need to add another class for the mapping of the body of the comment

and the destination should be 'comment_node_forum'


Displaying Database Data Within the Flow the Site

Drupal splits functionality (modules) and layout (themes) to keep everything maintainable.

Instead of echoing everything, you need to pass your output from your module to the theme.

First step is making a menu item. This will give you an url to work with: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7

Basic example:

function pathfindertool_hook_menu() {
    $items['pathfinderurl'] = array(
      'page callback' => 'pathfindertool_page',
    );
    return $items;
}

The page callback point to a function that contains your logic. You can choose the function name, but it's advised to start with your module name.

function pathfindertool_page() {
  $output = '';
  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  $title = $row['title'];

  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  // Do whatever you did to fill result.
  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $title = $row['title'];
      $output.= '<p>' . $title. '</p>';

    }
  }
  return $output;
}

Returning the output will make sure it will show in the right place. Never use echo or print, it will show up at the top.

You must always return something, even an empty string is ok, return NULL will result in a WSOD. That's why I always start my function with $output = '';


Different blocks on the same page, dependent on source link?

If you do it programmatically you can always parse url and display different content for different anchor or other param. You can always use one block for display content according to conditions.

Take a look to Context or Rules modules, maybe you find easier solution


Register form breaks after changing submit button value with jQuery

Based on what Clive said and your response regarding the Ajax stuff, I edited your code. I am assuming you only want to change the text of the button for display purposes.

(function ($) {
  $(function() {

    // Create a copy of the button
    $('#registersubmit').after('<input id="new-submit" class="form-submit" value="Jetzt registrieren">');
    // Hide original
    $('#registersubmit').hide();
    // When copy  is clicked, "click" the original
    $('#new-submit').click(function(){
      $('#registersubmit').click();
    });
    // Your code with changed IDs
    $("#edit-field-registrierung-als-und").change(function() {
      if ( this.value == "2") {
        $("#new-submit").val("Kostenpflichtig registrieren");
      }
      else {
        $("#new-submit").val("Jetzt registrieren");
      }
    });
  });
}(jQuery));

Can't test it as you appear to have the code active right now, but it should work fine in this scenario.


Text comparison rules on node:body:value with input filters

In my case a custom input format was replacing youtube links with an iframe embedded video. Everything inside the iframe wasn't matching. My solution was to add the original youtube link outside of the iframe tag replacement pattern.

But why? Hypothesis is that one of the filters ends up running the body through htmlspecialchars.


Search API / Facet API hierarchy based on taxonomy term reference across vocabularies

One alternative, which is not quite the same, is to use dependencies between facets.

So, the product families facet is shown only if a supplier is chosen. And the product series facet is shown only if a product family is chosen.

With hook_block_view_alter() one can rewrite the block title, so that the product family facet block says e.g. "Acme product family", if "Acme" is chosen as a supplier.

Again, this is not quite the same. But it provides an acceptable user experience, I would say. And it might be a suitable solution for some visitors of this question.


In the $form structure you have to add/override the submit (and maybe the validate) handler.


How do I programmatically update or delete menu items?

First you will have to load the entity. Either way works:

$menu_link = MenuLinkContent::load($menu_link_id);

or ...

$menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($menu_link_id);

Next you can update value using set() method or through the magic method __set...

$menu_link->expanded = TRUE;

To save, simply call the save() method.
To delete, simply call the delete() method.


How can I tell if module_load_include() is working?

module_load_include() returns FALSE if it can't find the file, and the full path to the file included if it can find the file, and it was successfully included. In addition to that, it uses require_once which will throw a fatal E_COMPILE_ERROR error if the file is not found.

An easy way to debug would be to use code like this in your loop:

$file_path = module_load_include($type, $module, $filename);

if ($file_path === FALSE) {
  dpm('Failed to include: ' . $filename);
}
else {
  dpm('Successfully included: ' . $file_path);
}

That will give you a pretty solid answer as to whether or not the files are being included. If you get no debug messages, you know that the glob() isn't returning the list of files that it should be.


How to make a node reference field that can also behave as a text field if no reference exists

instead of node references you could use term references and then use the Autocomplete Deluxe module to have the user select existing terms or add new terms.

Actually, they there is support for references with Autocomplete Deluxe for References.


Convert former embedded PHP code into a custom block module?

I don't really think embedding a node form in a node view is good in terms of performance because the entire node form needs to be rebuilt, and it can interferer caching mechanisms as well. Probably a ctools madal form with Ajax will do the job better.

You can define blocks in your site using a custom module. Panels will pick them up without any further integration.

function MYMODULE_block_info() {
  $blocks['MYMODULE_post_node_form'] = array(
    'info' => t('Add new'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

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

  switch ($delta) {
    case 'MYMODULE_post_node_form':
      module_load_include('inc', 'node', 'node.pages');
      $node_form = node_add('post');
      $node_form['buttons']['submit']['#value'] = t('Save and add new');
      $block['content'] = $node_form; // No need to render() here. Will happen automatically.
      break;
  }

  return $block;
}

I'm assuming you know how to create a basic module with an .info file, change "MYMODULE" to the module name of your choice and how to install them.
If everything went OK, you will see the "Add new" block in admin/structure/blocks page and in "Add content" form in panels.


How to override configuration variables in settings.php

You can't overwrite the variables in settings.php.


Ajax could actually complicate your situation further, since you'd be asking your site to bootstrap once again asynchronously in order to serve the node. Not to say it isn't an option, you can write your own method to retrieve only the information you need via ajax.

I would personally look into caching methods. If your site gets anonymous traffic, try boost. Easily the best improvement for Drupal performance (in my opinion) is APC cache. Hopefully you have root access and can install the APC extension for PHP and then the APC module, the site starts flying after that, for both auth and anon traffic. I'm afraid you might already know this so I'll stop there.

If you still wanna do AJAX stuff, you could install views datasource to output JSON, and add a jquery call the page with $.get and push the content into the DOM. Using views gives you some native caching options as well.

Hope it helps.


How to automatically post a message with the discount on the site?

There is no tool for general messages like this, because every site will construct its front-end differently. If this is only an occasional matter, you'd be best just creating the content manually. If it's going to happen with some regularity, you may just be best using custom code to define a template that can load a promotion entity and fill in the offer details from its fields.


Paypal Instant Payment Notifications - Add a role but not as a subscription upon purchase

I'm not sure the PayPal button is the way forward - you're probably better off using one of the cart modules (Ubercart, Drupal Commerce) so that when the IPN comes in the order status will be updated.

Then using Rules or Conditional Actions you can set up an event (triggered by the status update) to fire off an action that will add the role to the user.

Make sure to add conditions so that this only happens if the order balance is <= 0 (fully paid for) and if a certain product is in the cart. Also to make sure that it only occurs on updates between the two particular statuses (In Checkout -> Payment Received).

If there is no built-in action to actually add the role then you can use the "Custom PHP" action (or similar).
If you find the idea of writing that chunk of php yourself, don't fret. Just search for "drupal add user role programmatically" (without quotes) and you'll be on your way.
I don't know it off the top of my head, but I know that it isn't long.

One thing I have found very useful is to add an "email" action to my conditional actions, with myself as the recipient. Set the input format to PHP and put this in the body:

<?php print_r($order); ?>

This gives you the $order array from which you can extract values such as the user ID to use in your PHP action.


504 Gateway Time-out error in batch process

I have find the answer...

Please increase memory limit, excution time and max input time.

1. File php.ini

memory_limit = 768M
max_execution_time = 3600
max_input_time = 3600

OR

Define in settings.php

<?php
    ini_set('memory_limit ', '768M');
    ini_set('max_execution_time', 3600);
    ini_set('max_input_time', 3600);
?>

My problem is solve. :)


Ok, I resolved the issue with the hook_views_query_alter using add_where_expression method. It allows you to create complex where conditions. Below is example

// Delete current where conditions created by view and replace it by custom ones.
unset($query->where);
$query->add_where_expression(0,'node.type = :node_type', array(':node_type' => $node_type));
$query->add_where_expression(0,'node.status = :node_status', array(':node_status' => $node_status));
$query->add_where_expression(0,"(CASE node.type WHEN 'event' THEN field_data_field_date_and_time.field_date_and_time_value WHEN 'training_course' THEN field_data_field_date_and_time.field_date_and_time_value ELSE NOW() END) >= NOW()");

$or_conditions = array();

$or_conditions[] = '(og_membership.gid = :public_by_gid)';
$or_conditions[] = '(field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid)';
$or_conditions[] = '((field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid) AND (og_membership.gid IS NULL))';

$or_condition = implode(' OR ', $or_conditions);

$query->add_where_expression(0, $or_condition, array(':public_by_gid' => $public_by_gid, ':public_to_gid' => $public_to_gid));

I hope it was useful for someone.


Displaying multiple nodes inside a single view block

Create a new View (rather than trying to alter an existing one like Archive).
Add a Block display.
Set the "Number of items to display" to 5
Add filter(s) so that only the nodes you want are displayed
Add a sort by the created date of the node, descending, so the ones at the top of the list are the most recent.


How to change the user-facing label for a Commerce payment option?

I wasn't expecting something so basic to require an entire extra module, but apparently it does:

Download and install Commerce Payment Alter
Set new labels at the admin page admin/commerce/config/payment-methods/alter

Don't forget to document for administrators that they need to go to a whole different page if they want to rename a payment method's user facing label.


How do I print a link only if it doesn't lead to access denied

Now I feel silly, found an answer myself straight away, although it does only work for this specific example, I'd still be interested to see something more general.

<?php if (node_access('update', $node)):
    print l('edit', 'node/' . $nid . '/edit');
endif; ?>


url alias not working in block page restrictions

Looks like this has to do with having multiple URL Alias set up for the same page. To fix the issue I had to remove all URL Alias' that were not being used. The blocks then reappeared on the page.

If some else has an answer to this please post and if it fits better than my conclusion I'll mark it as the answer instead of this.


If you dont mind installing a new module you should check the double field module.

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts.

By using this module you can actually tie two fields together, and by clicking on add more you will have an image and its description tied together


Event Response not firing anonymous user

You can't do this when the redirect is already stored in the internal page cache. Because anonymous traffic is served from this cache before any event is fired.

You have to use this kill switch:

\Drupal::service('page_cache_kill_switch')->trigger();

If you put this in your event subscriber and clear the cache, then you prevent, that the response is cached in the internal page cache.


Is there advanced configuration for CKEditor in Drupal 8?

In regards to "allowedContent", this is set to true if you don't check "Limit allowed HTML tags and correct faulty HTML"( or another filter of type of FilterInterface::TYPE_HTML_RESTRICTOR) on your text format, otherwise it outputs the tags you have added there.

For more info on this, you can view:

ckeditor/src/Plugin/CKEditorPlugin/Internal:getConfig()

and

ckeditor/src/Plugin/CKEditorPlugin/Internal:generateACFSettings()

If wanted to override the Internal:getConfig method, you could create a new class that extends it and then replace the class using hook_ckeditor_plugin_info_alter().

function mymodule_ckeditor_plugin_info_alter(array &$plugins) {
  $plugins['internal']['class'] = 'Drupal\mymodule\Plugins\CKEditorPlugin\CustomInternal';
}

And then your custom override class:

<?php

namespace Drupal\mymodule\Plugins\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Allow custom config settings.
 *
 * @CKEditorPlugin(
 *   id = "custom_internal",
 *   label = @Translation("Custom CKEditor core")
 * )
 */
class CustomInternal extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {

    $config = parent::getConfig($editor);

    // Put your custom configs here.
    $config['allowedContent'] = TRUE;

    return $config;
  }

}


How can i reload jQuery scripts after form submit in views using ajax?

If you wrote your JS code like this.

(function ($) {
  Drupal.behaviors.tableStickHeaders = {
    attach: function(context, settings) {
      $("table").stickyTableHeaders();
    }
  };
})(jQuery);

It should automatically be reapplied when needed. This is the recommended way if writing JavaScript for Drupal.


How to append classes for dynamic terms in jquery?

I hope below code works for you.

if ($('.rate-widget-fivestar').hasClass('rate-widget-1')) {
  $(this).addClass('class1');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-2')) {
  $(this).addClass('class2');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-3')) {
  $(this).addClass('class3');
}


Webform Custom-Field Module and validation

It looks like the hook _webform_action_set_component might be used for validation: "Setting the form element allows form validation functions to see the value that webform has set for the given component."

http://www.rit.edu/drupal/api/drupal/sites!all!modules!webform!webform.api.php/function/_webform_action_set_component/7.41


How to solve these errors after running update.php?

My approach when this happens is to look at the table structure in a clean install of D6 to figure out what fields should be there, and compare that to the table structure in the current site. The issue is occurring because the update script has found something unexpected, so you need to figure out what that is.

In some cases, I've renamed the problematic table in the current database so I've got a copy, created a new table with the correct structure, and then copied the data from the backup table into the new table. I'm on a Mac, and Sequel Pro lets you do this via a handy GUI very easily.

In others, I've looked at the specific update script noted in the error to see what changes to the database it's trying to make - comparing that to the current version of the table can help identify why it's not allowing the update to occur.

This approach usually allows me to most database issues I encounter during upgrades.


If the module has been properly written en utilises the full Entity CRUD API there should not be a problem. In most modules this should be the case.

However the Entity module does more (like exposing entities to Views). If the dependency was only used for such a specific case, it might be possible that the module comes with un-exportable entities.

If you want to narrow this down you could search the module for HOOK_entity_info() (change hook to module name) and see what controller class is used. If it is EntityAPIController it is likely to utilise the CRUD API.


How can I save 30,000 nodes in less than a day?

I think you should have a look at the migrate module. I have used it to create 60k plus nodes via xml in less than an hr. It has a learning curve attached to it but the examples are good and it will import in a clean and proper manner.

Also it has command line integration with drush so you do not run into timeout issues.


Ubercart for D7 has a built in free order payment method so the UC Free Order module isn't needed here. You can configure the conditions under which the payment method is available under the payment method configuration page (Store > Configuration > Payment method).

If you need to limit available purchases, the included UC stock module enables restricting products to a limited quantity of available purchases.


Drupal 6 Image Resize Thumbnail Maintain Aspect Ratio

You want the ImageCache module https://drupal.org/project/imagecache there are also additional actions if you require them https://drupal.org/project/imagecache_actions


Drupal 7 hook_theme() not loading template file

Try implementing hook_theme_registry_alter() in your module

function sectionheader_theme_registry_alter(&$theme_registry) {

  //register a template
  $theme_registry['sectionheader'] = array(
    'template' => drupal_get_path('module', 'sectionheader').'/sectionheader',
    'type' => 'module',
  );
}

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_theme_registry_alter/7


this could be done two ways that come to mind:

1) Create the view as a block, then under the block configuration set it to show at the top of the content region and only on node/add/article page

2) Create the view as a page, and then using Advanced Form Block create a block for the node/add/article form to show in the content region above the View, only on the page url for the view

  Welcome to Advanced Form Block Module. With this module you can do the
  following:

  1) Create any number of blocks with a particular node edit form.

  2) create any number of blocks with a particular node add form of a
  content type.

  3) Create as many blocks as you like of each kind.

  4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.

  5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.