Irreversible error when trying to upload image (too big) in a clone In all of my node types I have several image fields. If I delete one image and then uploads a new one and then repeats this for a second and third image field, all works as expected.

BUT if I do this same thing in a clone of the node, WITHOUT saving the new node first, I get this message:

  Irreversible error, Uploaded file probably exceeds the maximum file
  size limit (2 mb), supported by this server

(something like that, translated from my language), directly when I hit the delete button for the second image. Before I even try to upload this second image.

The workaround for the time being is to save the clone first and then delete the old images and upload the new ones.

But what is this? I have never seen this behaviour before. My Drupal version is 7.52 and I use the Node clone module, version 7.x-1.0, together with the Node clone tab module, version 7.x-1.1.

What module are you using to clone a node? I recommend the Replicate module A workaround on your case now would be to alter the replicate functionality for the replication of image fields. You can clear the images field in code or copy the files yourself.

Here is an example for the replicate module to copy the images so your nodes don't use the same images because then you have unwanted behaviour on delete of one of the nodes (deletes the images):

/*
 * Implements hook_replicate_field_FIELD_TYPE().
 */
function replicate_custom_replicate_field_image(&$replica, $entity_type, $field_name) {
   // List of affected fields.
   $fields_list = array(
     'field_xxxx' => 'contenttype1',
     'field_xxxxx' => 'contenttype2',
     'field_xxxxxx' => 'contenttype3',
     'field_xxxxxxx' => 'contenttype4',
     'field_xxxxxxxx' => 'contenttype5',
   );

   if (in_array($field_name,  array_keys($fields_list))) {
     // Fetch field instance info.
     $field_instance = field_info_instance($entity_type, $field_name,           $fields_list[$field_name]);
     // Build destination path.
     $destination_path = 'public://' . $field_instance['settings']['file_directory'];
     foreach ($replica->{$field_name} as $language => $field) {
       foreach ($field as $key => $value) {
         // Fid can't be empty.
         if (!empty($value['fid'])) {
           $new_file = file_copy((object) $value, $destination_path);
           $replica->{$field_name}[$language][$key] = (array) $new_file;
         }
       }
     }
   }
 }


How to remove the core stylesheets from a theme I am developing a Drupal theme and noticed the following CSS files are added automatically by Drupal. I would like to them to be removed.

<link rel="stylesheet" href="/core/themes/stable/css/system/components/ajax-progress.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/align.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/autocomplete-loading.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/fieldgroup.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/container-inline.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/clearfix.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/details.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/hidden.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/item-list.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/js.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/nowrap.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/position-container.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/progress.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/reset-appearance.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/resize.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/sticky-header.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-counter.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-report-counters.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-report-general-info.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tabledrag.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tablesort.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tree-child.module.css?owah24" media="all" />

I have tried two ways to remove it. First one is using libraries-override

libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false

The next one is using hook_alter_css

function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  unset($css[drupal_get_path('module', 'system') . 'css/components/align.module.css']);
}

Also, you can exclude a whole library at all by adding:

libraries-override:
  system/base: false


'Text format field is required' error when saving Better Exposed filters (BEF) For one of the views exposed filters I'm using BEF but when I'm trying to save one of the filters as checkboxes/radio buttons it give me below error. I've no clue to what I'm doing wrong.

Any help would be much appreciated.

I found the problem.

Navigate to the BEF settings under the view in question (like the screenshot above).

Scroll down to  Require input before results are shown, select the checkbox, there should be a "Text on demand" field.

Set the Text format field to one a valid text format.

Then apply the changes.

I created a video tutorial for you to follow: http://recordit.co/V75Zl4gAAl


Way to Configure IP Geolocation Views & Maps Module via Script The module IP Geolocation Views & Maps has a ton of great features. By default, the data collection option: Employ the Google Maps API to reverse-geocode HTML5 visitor locations to street addresses is turned on.

Is there a way to turn off this option via a drush command, or through some code? I have automated our site setup process, and would like to ensure this option is turned off without requiring admins to click off the option in the admin UI.

You can use the drush variable-set command for this:

~$ drush help variable-set
Set a variable.

Examples:
 drush vset --yes preprocess_css TRUE      Set the preprocess_css variable to
                                           true. Skip confirmation if variable
                                           already exists.
 drush vset --exact maintenance_mode 1     Take the site offline; skips
                                           confirmation even if
                                           maintenance_mode variable does not
                                           exist. Variable is rewritten to
                                           site_offline for Drupal 6.
 drush vset pr TRUE                        Choose from a list of variables
                                           beginning with "pr" to set to
                                           (bool)true.
 php -r "print                             Set a variable to a complex value
 json_encode(array('drupal',               (e.g. array)
 'simpletest'));"  | drush vset
 --format=json
 project_dependency_excluded_dependencies
 -

Arguments:
 name                                      The name of a variable or the first
                                           few letters of its name.
 value                                     The value to assign to the variable.
                                           Use '-' to read the object from
                                           STDIN.

Options:
 --exact                                   The exact name of the variable to
                                           set has been provided; do not prompt
                                           for similarly-named variables.
 --format=<boolean>                        Format to parse the object. Use
                                           "auto" to detect format from value
                                           (default), "string", "integer" or
                                           "boolean" for corresponding
                                           primitive type, and "json" for JSON.
 --yes                                     Skip confirmation if only one
                                           variable name matches.

To use this, you need to figure out the machine name for the variable.  On system settings forms, this will be the $form key in the builder function.  You can also poke through the variable list from the Devel module, and look for the variable name there.  If you use Inspect Element (or whatever it is called in your browser), it will be the name attribute on the input or select element.


How to create a block with CCK dropdown lists and some values in it? As the question is clear, I want to create a block in the left sidebar and which contains sample values in it. How to do this? I am very new to Drupal

This is something you can do in Drupal 7 easily as they now use enititys. However in Drupal 6 you will need to use a custom module like Node Blocks


Calling theme_hook_suggestions inside template.php I am using template_preprocess_block() to introduce a theme function like this:

$variables['theme_hook_suggestions'][] = 'block_system_main_front';

but adding MY_THEME_block_system_main_front() to my template.php file does not change anything, MY_THEME_block_system_main_front() is not being called.

How can I introduce a custom theme function using theme_hook_suggestions and then use it like I use theme_image_formatter() ?

theme_hook_suggestions is not for function suggestion, it is for template suggestion.

In your case:

$variables['theme_hook_suggestions'][] = 'block_system_main_front';

Drupal will try to load the file:

your_theme/templates/block-system-main-front.tpl.php


Display selected menu parent with children in sidebar I have a menu  build with taxonomy menu structured like this :
Agenda

agenda1
agenda2

News

News1
News2

Access

Access1
Access2

My main navigation is like this (no children): Agenda | News | Access
What i want to do is , when i click Agenda for example ,i would like to dispay in agenda page in the side bar the block menu corresponding with children
Agenda

Agenda1

Agenda2
I have read many forum on this but not able to get it working :

Show Parent Menu children in sidebar
Get menu link siblings
How to display a block with menu child items programmatically?
I try Menu bloc module to do this but when i set Initial visibility level = 1 , all the menu with children is displaying , but i would like just display the selected menu with his children
When i set Initial visibility level > 1 nothing is display
Any help is welcome

I get it working by using this module : Hierarchical Taxonomy Menu https://www.drupal.org/project/hierarchical_taxonomy_menu

Thanks


Constructor in a custom entity isn't prior to baseFieldDefinitions I have a custom entity with a constructor that calls a custom method (generateCharacteristics()) to generate random values for certain fields of my entity :

    public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = array()) {

    parent::__construct($values, $entity_type, $bundle = FALSE, $translations = array());

    $values += $this->generateCharacteristics();

    foreach ($values as $key => $value)
    {

        $method = 'set'.ucfirst($key);

        // For two-words attributes
        if( strstr($method, '_') ) {
            $method = explode('_', $method);
            $method[1] = ucfirst($method[1]);
            $method = implode('', $method);
        }

        if (method_exists($this, $method))
        {
          $this->$method($value);
        }
    }

}

When I log what occurs in this __construct method when I create a new entity, all works fine, attributes are well setted, but in my database I have NULL or default values (the ones I declared in baseFieldDefinitions()). That's a shame because I think that baseFieldDefinitions() is put in cache (not good for random values) and that my method using constructor is cleaner.

Maybe my error is to think that $values array is the array we send during the call of Entity::create() method because this $values array seems always empty before I add my own array to $values... Nevertheless I set my attributes correctly in the constructor. The use of a postCreate() method should be more appropriate ?

thanks !

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

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

class CustomEntity extends ContentEntityBase {

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

}


How to sync content title with "synchronize translations" module? The synchronize translations module, part of the Internationalization module (i18n), allows us to sync content between two languages.

It works very well with node configurable and standard fields. But I can't configure it to sync also the node title.

Is there a way to force it to sync also the title, or any alternative to do this work?

Possibly this is because titles do not get translated in a site using the i18n module. And that is most often because of the Title module that has not been enabled. From the module's project page (bold markup added here):

  After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.


Are there any contributed/commercial themes available for Open Atrium? Googling "Open Atrium Theme" doesn't yield very many results. I have a sinking feeling that most people who install Open Atrium stick with Ginko for the theme.

Are there any contributed themes out there for Open Atrium or Commercial Themes?

Here's a bunch of them (scraped from Google cache, it seems the original page is no longer available):

Miro
Trapeze
Sandy
Scene
Mobile Gingko
Atrium Simple
UNL
Crystal

If memory serves I've had Miro installed before with good results.


How to allow all commerce customers to use their billing address as their shipping address, in Commerce Shipping 2.X? Almost all shopping sites have a feature to allow customers to use their billing address as their shipping address, to save them typing it in twice in the very common case of a customer having the same shipping address as their billing address. This should be possible both for customers with accounts, and for anonymous customers.

Looking for this feature in Drupal Commerce, I find some hacks suggeested in 2012, and a long issue report that seems to suggest this feature has been implemented.

However, the steps listed in that issue seem to be for the 1.X branch only, not the 2.X branch, and seem to no longer apply:

  For people who are a little lost like me, this is where you will find the settings:

  store/customer-profiles/types/billing
  store/customer-profiles/types/shipping

  Halfway down the page, under Format Handlers, you'll see a checkbox with the following text:

  "Copy billing address (required to be activated on billing profile along with the profile you want to copy the address on to. In order to work properly, the two addresses need to be on the same page.)."

  Check this on for both the billing and shipping profile types. Save both. I'd imagine you also need to make sure the other format handlers are identical between the two profile types--though I haven't tested it.

Those pages have moved, and I can't find any such checkbox in their new equivalent. Likewise this related question is 1.X only.

How do we enable this common feature in the 2.X branch of Commerce Shipping?

Go to Checkout Settings (admin/commerce/config/checkout). Find Shipping Information pane and click configure.

You'll see setting for copying billing address right there (screen below)


Why submit button is losing disabled attribute after deletion of uploaded file? The task is simple: submit button must be enabled only if file is attached to file input.

The form code:

function custom_module_form($form, &$form_state) {

    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['xml_file'] = array(
        '#field_prefix'      => ''.t('Only XML files are allowed').'',
        '#type'              => 'managed_file',
        '#title'             => '',
        '#default_value'     => '',
        '#upload_location'   => CUSTOM_MODULE_UPLOAD_DIR,
        '#upload_validators' => array('file_validate_extensions' => array('xml')),
        '#required'          => TRUE,
    );

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

    return $form;
}

The form alter code:

function custom_module_FORM_ID_form_alter(&$form, &$form_state, $form_id) {
    if (! isset($form_state['clicked_button'])
        || $form_state['clicked_button']['#name'] == 'xml_file_remove_button') {
        $form['submit']['#disabled'] = TRUE;
    }
}

It works, but when I removed uploaded file by Remove button, refreshed form has enabled submit button, even if I am sure that above code was executed. What am I doing wrong?

Use case:

Go to page with a form, submit button is disabled - ok
Uploaded sample xml file:

Click the Remove button, form is refreshed but submit button is enabled instead of disabled

You can't do it, because on remove event, only HTML for file input field is reloaded. There is a need of using custom AJAX callback for this (such as ajaxSuccess). I don't know nothing about Drupal Ajax callbacks for this type of event too.


How do I get the taxonomy term's path alias? I have come up with a need to show a node term's URL alias using plain php in drupal 8 but I can't figure out how to do it.
In my custom module, I want to get /fruits/apples in a variable upon loading a node which is linked with Fruits term.

Here you can see the Edit Term settings page in which I have set the URL alias of the term Fruits to /fruits/apples. I want to get this URL alias whenever a user loads a page linked to this term.

You can get it by this way as well (assuming you know $id in advance in code) as of Drupal 8.5.x:
1. For taxonomy term:
Term::load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/taxonomy/term/'.$id);

2. For node:
$node = \Drupal::entityManager()->getStorage('node')->load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/node/'.$id);

OUTPUT:
$alias = /fruits/apples
EDIT:
As of Drupal 8.8.x, path.alias_manager has been deprecated, use path_alias.manager in future versions of Drupal.


Hierarchy and taxonomies (like in the animal taxonomies) Trying to figure out how to implement hierarchical taxonomies. For example, take animals. Animals belong to a family, a genus and a species. family being the least specific, and species being the most specific. It's easy enough to create three taxonomy vocabularies, but in this case, a species belongs to a genus and a genus belongs to a family, there should be some way to infer the family and genus from the species. Please let me know if this makes sense, and there is a way to do this.

You could try Taxonomy Manager module to quickly create tree of taxonomy nodes where each of taxonomy levels can be your family, genus, species and at the end animals. My suggestion is do not try to create separate taxonomy dictionaries , ie separate taxonomies for family, genus, species. Let's keep them all in one common taxonomy.


How do I set a stored procedure? How can I process following query structure in drupal 7.

set @num := 0, @termid := 0;

SELECT  * FROM (SELECT tid,nid,created,
           @num:=IF(@termid = tid, @num + 1, 1) AS row_number,
           @termid:=tid AS termid .......

It has been solved using.

function  hook_install(){

db_query("CREATE PROCEDURE xyz()

BEGIN
    set @num := 0, @termid := 0;
    ......................................");


Is it possible to synchronize publish status between translations? Having 'Enable Translation' checked for a content type, is it possible to synchronize the publish status between all the translations in Drupal 8?

You can't control the translation configuration of base fields such as the publish status field from the content type configuraton, so go to

  Administration >> Configuration >> Regional and language >> Content
  language

and uncheck the publish status field for your content type:

  [ - ]  Published

Now the publish option will be available only in the original language of the node and is then applied to all translations.


Print filename from url Im using Drupal 6 with Audio.

I have created a view that shows a list of files to download and play. There are two fields which both show the download link. I would like to change the second download link field so that it strips all the info and only prints the filename from the url contained in its content. So instead of

<*a href-"file/path/music20.mp3">Download <a*>

I would like to see

music20.mp3

or

music20

Thanks in advance

In drupal 7, views 3 if you add a relationship File Usage: File you get some new fields you can add to your view, including the filename. The filename includes the extension (.doc, .pdf etc). But even with that you could theme the specific field with a template where you could easily use php to cut the .mp3 part.


How do I get the path for public:// I need to get the path for public:// at runtime. Is there a function I can use to get it?

You can use the file_create_url function.

$uri = 'public://';
$path= file_create_url($uri)


Printing Region With Content in Custom HTML I am creating a custom first page that is blank and built up from scratch. However I want to print certain regions (e.g. the footer) on this page. How can I grab the region information/content and print it in the html in the welcomegeneratepage function.

<?php

//Create the redirect page
function module_name_menu() {
    $items['welcometest'] = array(
        'title' => 'Redirecting',
        'access callback' => TRUE,
        'delivery callback' => 'welcome_blank_page'
    );
    return $items;
}

//Function generate the redirect page
function welcome_blank_page() {
    //Get the redirect URL
    //Generate the HTML for the page
    $html = welcomegeneratepage();
    print $html;
}

//Generates the page html
function welcomegeneratepage() {
    print $footer;
    $html = "

                    <link rel=\"stylesheet\" type=\"text/css\" href=\"".drupal_get_path('module', 'module_name')."/css/module_name.css\">
                    <link rel=\"shortcut icon\" href=\"".variable_get('file_'.file_default_scheme().'_path',conf_path().'/files')."/favicon.ico\" type=\"image/vnd.microsoft.icon\" />

                <title>
                        Welcome to ".variable_get('site_name')."
                </title>

Welcome

             ";
    return $html;
}

I haven't had any need for a blank page before, but couldn't you just create a new .tpl.php for the front?

Under site configuration, set a node as your front page, then create a copy of page.tpl.php and name it page--node--1.tpl.php (or whatever node ID you have) .

Delete all the divs and containers to make the page blank, and then render regions in php like normal.

  print render($page['your_region']);


Why are foreign language registrants redirected to home page after registration? When someone registers an account in English (default language) the registrant is redirected to the Login page with a message: "A welcome message with further instructions has been sent to your e-mail address."

So far, so good.

But when a registrant select a foreign language on the registration page (like es for Spanish,) he is redirected to his profile page after submitting his registration.

Anyone knows how to fix this bug so that it behaves like the English registration? Or a workaround?

I wonder if your issue could be related to the language specific homepage (frontpage).

The relative URL to display as the front page is specified within admin/config/system/site-information. Make sure you specify a value for it that is different for each of the site's languages. To do so, you have to make it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

For more details about this, refer to my answer at How to make content translation available for front page?


How to customize the user profile page with views I've got a view I want to embed in a user profile page (A list of nodes that are associated with the user). The view is already working correctly.

Is the best way to do this to simply make a region in the theme that shows up only on the user profile page and then add the block view to that region?

To complicate this more, I have some pagination that should work with the view that is in date form (they could click "january 2012" or "february 2012" or just "2012" and is separated from the main view by some other content/markup. Do I somehow make two views? One for the content and the other to manage the links back to the page for which the main view can determine which content to show?

Create a view and add a "page" display.
Use "user/%" as the page path.
Add a contextual filter "user uid" and select "provide default value" user ID from URL.

You are done. This view overrides each user's profile page.

You can also add another display "attachment" to this view. Or add another views block as a view area into the footer of that view.


Change field access per user I am trying to customize the access of user fields. We have an internal list of all users, which all members can access (for things like mail/address/phone number). However, due to privacy, each user should be able to manage these field, and can hide certains fields from showing to particular members or groups.
For this, I created a database table which stores all preferences, and fetch them using dynamic query. For the field access, I use
function MY_MODULE_has_access($operation, $field_machine_name, $uid){
  Code for determining access here
  return if $uid has access
}
function MY_MODULE_entity_field_access($operation, $field_definition, $account, $items = NULL) {
  if ($field_definition->getName() == "field_address") {
    $user = \Drupal::currentUser();
    $result = AccessResult::forbiddenIf(!MY_MODULE_has_access($operation, "field_address", $user->id()));
    $result->addCacheableDependency($user);
    return $result;
  }
  return AccessResult::neutral();
}

However, due to caching, this only works one time. If the user changes its preferences, the field access still remains unchanged. How can I fix this?

The variable $user should probably be the parent entity of the field:
$user = $items->getEntity();

Which then when used as cache dependency should solve the caching issue:
$result->addCacheableDependency($user);

BTW you find the current user already in $account. If your access check depends on it then don't add it as object but use this predefined method for caching:
$result->cachePerUser();

But most times access code depends only on the current user roles and the resulting permissions, then you could use instead
$result->cachePerPermissions();

which is much better for cache performance.


index.php is added in front of paths for anonymous users I have a new Drupal 8.0.4 site running on Nginx, and I just noticed that the paths for anonymous users have a superfluous index.php in front of them.

So instead of

mysite.com/node/123

I get the following when not logged in

mysite.com/index.php/node/123

I'm not entirely sure if it was this way since I started building the site, because I was usually logged in I might not have noticed it. But it could also have happened only since I upgraded Drupal core to the latest minor version.

My Nginx configuration is based on the official Nginx recipe for Drupal, with some small differences in the php-fpm configuration for PHP 7.

As mentioned in the comment by Sachbearbeiter, this seems to be an intermittent issue. I don't see it anymore now on my site, some days later.

Any idea what is causing the index.php to be inserted and how I can get rid of it at all times?

This is mainly an SEO issue. Search engines seem to like unclean URLs with index.php. Once they found one all internal links on your site also contain index.php and so they sometimes crawl the entire site in this namespace.

You have to return a 301 redirect for any unclean URL to stop this. Install the module Redirect and go to the module settings /admin/config/search/redirect/settings:

  GLOBAL REDIRECTS

  [x] Enforce clean and canonical URLs.

  Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing
  trailing slashes, ensure the language prefix is set and similar
  clean-up.


How to remove extra white spaces and line breaks from HTML in drupal 7 I am using drupal 7 and created my custom theme. Now I am facing problem that page is containing extra line breaks and while spaces when I open view source.

Can some one suggest any module/code snippet which minimize my html so that page render fast.

Else tell me where I can minimize it in my template.php file or any .tpl file.

Agree with rooby, whitespace in html does not slow down the site performance.

You can use the Minify module to remove extra line breaks and whitespace before and after HTML tag.

Minify also minimize the JavaScript files. Minimized JavaScript files are smaller in size as compare to regular JavaScript files. Smaller size will helps you to load site faster.

To use Minify

Download and install minify module
Go to performace
Select minify HTML
To minify JavaScript files select Minify JavaScript files in upper right corner


Get list of canonical urls? I have a list of ~2500 pages that I need to get canonical urls for from an old D6 site.  The site uses Path_Redirect.

Using mysql queries I can get a list of nids for the pages I want, but I'm having trouble connecting the nids to the most current path alias.  Little help?

I'm running into this problem, though I'm not sure we're using Path Redirect. For me, Migrate is bringing in URLs that are non-canonical, and I need to override the query to get the URLs that D6 has decided are canonical.

In D6 the code that does this is drupal_lookup_path('alias', $path);

By examining this I determined that if you don't care about language, the bare query is (for node/121):

SELECT dst FROM url_alias WHERE src = 'node/121'  ORDER BY pid DESC;

The ORDER BY pid DESC is the key part here.


Getting 'bool(false)' output before normal page HTML I've seen this happen once or twice before, but can't remember where or why.

Basically, in one of my page's HTML output, the first line of HTML is returned as 'bool(false)' - On that particular page, I have a function in hook_init() that logs in a user using user_login_finalize(). Here's the HTML from the

page:bool(false)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">
<html lang="en" dir="ltr" version="HTML+RDFa 1.1"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
...

On the page as displayed, I get a blank line above my theme's header with this bool(false) appearing.

On refreshes, that goes away (basically, it only happens when I log in a user programmatically using user_login_finalize()).

It seems that the problem went away if I commented out the user_module_invoke() call inside user_login_finalize().

Obviously, I didn't want to maintain a patch for that, nor did I want to take out that behavior, as I may want to use hook_user_login() sometime. So, I basically copied user_login_finalize() into my own private function, removed the user_module_invoke() call, and am now using the private function for my particular need. Seems to be working fine!


How to print and/or manipulate individual image attributes and suppress width and height via the image.html.twig template I had to get rid of the width and height attributes in my images and wanted to learn better the possibilites of Twig in Drupal.

Copy the image.html.twig file from core/modules/system/templates/ to your theme /templates folder.

If you want to simply hide width and height as image attributes:

{%
set classes = [
    style_name ? 'image-style-' ~ style_name|clean_class,
]
%}
<img{{ attributes|without('width','height').addClass(classes) }} />

If you want to do further things it would be probably better to use template preprocessing functions in the theme file (because of too much logic here) - so this is more a use case for the possibilities in twig files ...

If you want to hide width and height and also want to hide empty class and alt attributes for example:

{%
    set classes = [
        style_name ? 'image-style-' ~ style_name|clean_class,
    ]
%}
{% set printattributes = attributes.addClass(classes)|without('src','alt','class','width','height') %}
{% set printclass = attributes.class.value() ? 'class="' ~ attributes.class ~ '"' : '' %}
{% set printalt = alt ? 'alt="' ~ alt ~ '"' : '' %}

<img {{ printclass|passthrough }} src="{{uri}}" {{ printattributes }} {{ printalt|passthrough }} />

This is also very useful in this context: http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340


Remove node_access check from content revisions view For the 'content' Views one can simply check tickbox 'Disable access checks' in UI under Advanced => Query, and the View returns all the records regardless of the node_access check.

However, in the 'content revisions' Views this tickbox is not available.

How can I make 'content revisions' Views to bypass the access_check?

In the hook_views_query_alter is possible to alter the query tags. Unfortunately, the method tag_remove is not present, but the $tags variable is public, which allows us to do:

function yourmodule_views_query_alter(&$view, &$query) {

    // Disable Node Access check for myview
    if ($view->name == 'myview') {
        $view->query->tags = [];
    }
}

I hope this will help somebody who needs unrestricted Views (e.g. for Services).


How to change the order of fields in field account in the user profile form? In the user detail screen (user_profile_form) there is a field: account.

In this field there a different form fields. How to change the order of these form fields? I would like to group the fields current password, new password and confirmation password together.

I did by form_alter ...

if($form_id == "user_profile_form") {
   dpm($form)
}

But then? I do not see any key or weight in this array..

You're half-way there: just add something like

$form['account']['pass']['#weight'] = -6;

(event if you don't see the #weight key) and check the results - in this example you should see the current password field go right below password fields.


Search option just as that provided in drupal.org can you please tell me which module to use to provide search options just as the search provided in https://drupal.org/download

Thanks

Facetapi module will help you. From facetapi module page:

  The Facet API module allows site builders to easily create and manage
  faceted search interfaces.

You may also look into search_api module. From module page:

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc.

If you do not want to use the default Drupal search you can use apachesolr search module. This module can also be integrated with facetapi module.


Why don't external JS files load on mobile site built with jquerymobile/JQM? I'm developing a site that uses the Mobile Tools module to switch between a "desktop" and "mobile" theme. The mobile theme is implemented using the jquerymobile module and s sub-theme of JQM theme.

Unfortunately, the mobile theme will not load any external javascript files that are inserted by other modules (Google Analytics, Facebook Connect). These work fine on the "desktop" theme, but just don't load at all on the mobile theme, so I'm not getting any Google Analytics stats for views on that theme, nor can I implement Facebook Connect login.

According to the jquerymobile docs, there are some issues with the loading of scripts because of the AJAX page loading feature in jquerymobile, but I've turned that off, so every page is its own complete page request.

I am using version 1.0b2 of the jquerymobile library, and gently hacked the jQuery Update module to provide version 1.6.2 of jQuery, since that is a requirement for that version of jquerymobile.

The problem turned out to be that a call to the in_array() function in the jquerymobile module did not use the optional third parameter for strict type comparison, so array keys that were strings were getting cast to the integer zero when compared to another zero, and returning true.

The fix was to add the TRUE parameter to the call to in_array.

Here is a quick sample that proves the problem:

<?php

$haystack = array('foo', 'bar', 'baz', 'bat');

$needle = 0;

$test = in_array($needle, $haystack); // same as in_array($needle, $haystack, FALSE)

var_dump($test); // bool(true)

$test2 = in_array($needle, $haystack, TRUE);

var_dump($test2); // bool(false)

?>

Patch file is uploaded on the drupal.org issue.


Drupal 8, override User Class for a custom added field I am not a great POO specialist, maybe my ask will seems stupid x)

When I create new field from the user UI administration, I would like find quickly this field when I work from my IDE in customs modules.

So, I think I need add a custom method for the User Class, like :

public function mycustomfield_value($user){
    return $user->mycustomfield->value;
}

From my IDE, if I type "$user->" the IDE auto-complete must show me "$user->mycustomfield_value(..." method.

My ask is : how can I add this method ? I must create a new Class implement/extends User Drupal 8 Class ? I don't know how can I do that..

Don't. The field system doesn't work like that, there is currently no useful way to get autocomplete.

You could replace the entity class with your own and add methods for your fields, but it's not worth the trouble IMHO as you might get into trouble of some other module wants to replace the class as well.

You could add helper method or functions somewhere else and pass in the entity.


Display all taxonomy terms's ids associated with nodes in a view I need to display the term ids of each node under its title in a view.

I can do similar display by adding node: title and node: all taxonomy terms. But I just want to display tid's instead of term names.

My view result should look like this:

title: Node title 1

tids: 1, 2, 4

title: Node title 2

tids: 3, 5, 6

Is there a way to alter or add a views field for this?

Also in general, how are fields that is available to the views constructed?

Add field "All taxonomy terms". Then check the "rewrite output of this field" box, and in the rewrite box enter the token [term_node_tid-tid].


How do I enable a features module in the setup of a simpletest testcase I'm trying to test some permissions that are related to custom node types and Organic Groups that I've built and packaged as a feature using the features module.

I'm trying to enable the feature (and create all the content types and taxonomies that are part of the feature) in the setUp method of my simpletest test case class like this:

class PermissionsTestCase extends DrupalWebTestCase {
  public function setUp() {
    parent::setUp(array(
      'addressfield',
      'ctools',
      'date',
      'entityreference',
      'features',
      'file',
      'list',
      'node',
      'og',
      'og_field_access',
      'og_ui',
      'options',
      'strongarm',
      'taxonomy',
      'text',
      'my_custom_feature',
    ));
    debug(module_list(TRUE));
    debug(features_get_features());

    // More setup stuff that depends on content types and taxonomies in my feature
    // ...
  }
}

However, when I look at the output of module_list it doesn't include my feature or the dependencies and subsequent setup tasks that rely on a taxonomy that's part of my feature don't find the taxonomy vocabulary.

Can I enable a module created with features in the setUp method? What's the best way to do this?

Do I have to explicitly specify the dependencies of my feature in the call to parent::setUp?  What about the dependencies of my dependencies? Does the order matter?

As of Drupal 7 you don't have to explicitly specify module dependencies, they are resolved automatically.  The order doesn't matter either for that same reason.

As far as actually enabling the feature, it should be fine... I was going to suggest calling drupal_static_reset('system_list') before module_list() but it already does that itself when you pass TRUE as the first param like you did.

I've had some issues when testing features modules and, in certain situations, I've found that it's actually better (and much slower) to force SimpleTest to use the live database.

Granted, that's very specific to certain types of client projects, but still, might help! :)


Changing Button Text on Content Type form I created a content type called "video" and I created a module named df_video.module with:

function df_video_video_node_form_alter(&$form, &$form_state) {
    $form['actions']['submit']['#value'] = t('Upload');
}

I am trying to change the button text of my Video content type form from "Save" to "Upload" but nothing seems to work when I hit refresh. I also tried clearing the cache. I've tried many variations of the function name with no success. I would prefer to use the specific name of the form in the function name so I don't need to do a switch statement.

Also, just out of curiosity does anyone know if there is something special for placing hooks in a .inc.php file? Not doing this currently but I'm thinking it would just be an include to the main module file.

You cannot target only the video_node_form with an existing hook in D7, but you can target all node forms and then check against the node type to alter the form. Take a look at the documentation and comments on hook_form_FORM_ID_alter(). It may also help to check out how the Book module implemented this hook in D7.

function df_video_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  if ($node->type == 'video') {
    $form['actions']['submit']['#value'] = t('Upload');
  }
}

With regard to your second question, you generally want to place your hooks in the .module file so that they are guaranteed to be picked up by Drupal. There are some cases where this is not necessarily necessary, like in hook_views_api() where you can points to a file containing other views-specific hooks.


taxonomy_term entity loadByProperties depth not found The terms returned contain depth as a Term object attribute.
$vocabulary = 'category';
$entity_manager = \Drupal::entityTypeManager();
$entity_storage = $entity_manager->getStorage('taxonomy_term');
$terms = $entity_storage->loadTree($vocabulary);

However, when I try to load terms by depth, I get an error.
$entity_manager = \Drupal::entityTypeManager();
$entity_storage = $entity_manager->getStorage('taxonomy_term');
$terms = $entity_storage->loadByProperties([
  'vid' => $vocabulary,
  'depth' => 0,
]);

The error is the following.

Uncaught PHP Exception Drupal\Core\Entity\Query\QueryException: "'depth' not found

What is the way to find attributes I can use on loadByProperties()?

What is the way to find attributes I can use on loadByProperties()?

I guess with Devel's Kint, loading one and then looking at the "iterator contents" tab
  $entity_manager = \Drupal::entityTypeManager();
  $entity_storage = $entity_manager->getStorage('taxonomy_term');
  $term = $entity_storage->load(1);
  kint($term);


How to hide empty ratings using Rate module? I run a site that uses the Rate module on Drupal 7, using the 5 star rating.  A lot of the items haven't got any ratings yet, so are displayed as 5 blank stars, which makes it look like they've got a score of 0 out of 5.  Is there a way of only displaying a score if there is at least one rating?

How would people rate the item the very first time if the widget is hidden?

Look in Rate module's template folder for rate-template-fivestar.tpl.php. Copy it over into your theme's template folder then make changes.

I think the variable $count might be available (Number of votes), so you could print out a message if $count is 0 to say that the item has not yet been rated.


How can I enable search on parts of a word and autocomplete suggestions? I'm using Search API in Drupal 8.

I tried with Search API pages and even views, but I didn't find %like% function query

Can I do %like% in Search API or Views?

Click in "Edit" this Database server, and navigate to the end of that page:


Updated to Drupal 7.51 and website is now stuck in maintenance mode I just went to update Drupal 7.5 to 7.51 and fortunately the update worked. Unfortunately our site is now locked in maintenance mode and I was logged out of the system and cannot get back in as an admin or anything on the site for that matter.

We tried to do a site rewind to go back to our original settings before the update but still no luck. We also tried using /user and also /?q=user but this doesn't work either. The site seems to be stuck in some sort of page refresh loop. Does anyone have any suggestions of what else we should try or what we should do?

I am compiling here some points which I found. Following list I have ordered them from common to complex solution.

1. Clear cache:

First thing you can do is clear the cache. If you read the forum discussion on the Drupal forum page titled: Site stuck in maintenance mode!, you'll find various people solved this issue just by clearing the cache.

Through Admin UI: As per this comment just clear the cache by going at Administration/configuration/performance.
Using Drush: If you are using drush, you can do this by command drush cc all.
Other methods: If above both methods are not accessible for you, you can try other methods witch are listed in this article: [Drupal]Methods to clear Drupal caches

2. Login to site:

You can try some methods to login into site while still site in maintenance mode.

Login to site using /user/login: On this question of DA: How can get my site out of maintenance mode? @Dmitry has stated in his answer,

  Just go to /user/login, it works even in maintenance mode, and then
  sign in as an admin.

On other Drupal forum QA also if you see the comment on this Link, it talks about using /user/login. I have pasted here,

  I just had a similar issue with a D7 site I was performing maintenance
  on. Logging in via http://example.com/user and
  http://example.com/?q=user wasn't working. What did, though, was
  http://example.com/user/login.

3. Changing Maintenance Mode setting:

@mixerowsky has very well explained various ways of changing the maintenance mode in his answer at this DA question: How can get my site out of maintenance mode?


Drupal 7 - FAPI - Multistep form - with add another option I'm creating a multistep form in Drupal 7 - FAPI.

In the main hook_form() the redirection to the different steps are handeled.

function hook_form($form, &$form_state) {
    if (empty($form_state['storage']['step'])) {
        $form_state['storage']['step'] = 0;
    }

    switch($form_state['storage']['step']) {
        case 0:
          $form=  _step_0($form, $form_state);
        break;
        case 1:
          $form =  _step_1($form, $form_state);
        break;
        case 2:
          $form =  _step_2($form, $form_state);
        break;
        case 3:
          $form =  _step_3($form, $form_state);
        break;
        case 99:
          $form =  _step_end($form, $form_state);
        break;
    }
    return $form;
}

function _step_2($form, &$form_state) {
    ....
    $form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 80,
        '#size' => 80,
    );

        $form['Street'] = array(
        '#title' => t('Street'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 80,
        '#size' => 80,
    );

    ......

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

    $form['add'] = array(
            '#type' => 'submit',
            '#value' => 'Collega toevoegen',
        );
}

In step 2 I have an optional button 'Add onther' which saves the form_values into storage and reloads the same form (step 2). But when it reloads this form for the seconds time. the previous form values are being represented as default form values and not a blank (new) form, which is wanted.

function inschrijven_form_submit($form, &$form_state) {
    switch ($form_state['storage']['step']) {

        case 0:
          switch($form_state['values']['op']) {
            case 'Next' :
              ....
              $form_state['storage']['step'] = 1;
            break;
          }
        break;

        case 1:
          switch($form_state['values']['op']) {
            case 'Next' :
              ....
              $form_state['storage']['step'] = 2;
            break;
          }
        break;

        case 2:
            switch($form_state['values']['op']) {
                case 'Next' :
                    ....
                    $form_state['storage']['step'] = 3;
                break;

                case 'Add another' :
                    $form_state['rebuild'] = TRUE;
                    ....
                    $form_state['storage']['step'] = 2;
                    return;
                break;

        .....

    }
}

I've try to clear the form_state['values'] manually after each submit but with no success. Who can this multistep with add another functionality be achieved?

When you want to add a new set of values, you have to build the form in a different way - the fields that should be "multiplicated" have to be in an array.

so, your

$form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',

should instead look like this :

$form['step2'][$i]['Name'] = array( ...

where $i is set to zero in the begining and increased by the callback for your "add another" button. The "step2" fieldset is there just to help you distinguish the parts that are repeated from the others - its not necessary i guess.
The aformentioned examples module has nice examples how to acheive that even with ajax, so you dont have to reload the whole thing. Dont forget to set

$form['#tree'] = TRUE;

so that you can process the several sets of results.


Restricting node reference values to owner I have played with a bunch of modules (Node Reference Node Access, Views Field, View Reference) and can't seem to find one that does a very simple job; In one content type I want a field that provides a select list of all nodes owned by current user from another content type.

Think of it (roughly) as blog content types.

Blog 1 - Owned by user 1
Blog 2 - Owned by user 2
Blog 3 - Owned by user 1

In another content type (updates) we'll have a field that is used for building a relationship (ie, select the blog that this update will be related to) and that field should be populated with the blogs owned by that user;

Select Blog (for user 1 the list would contain;

Blog 1
Blog 3

I have read so much, installed so many modules and I just cant get it to work. The closest I have got is a field that contained the name of the view, which is not overly helpful.

EDIT:
Screen Shots:

If I understand you right, you can use a View as the source for the nodereference widget, and give it appropriate filters to only show nodes of a certain type authored by the current user. To use a view (assuming you have Views installed and appropriate perms) you can

edit the nodereference by going to Content management -> Content types -> Edit [whatever content type] -> Manage fields -> [whatever field name];
in the fieldset Global settings click to expand the fieldset Advanced - Nodes that can be referenced (View);
select the appropriate view in View used to select the nodes;
if you want to use arguments you can specify them in View arguments.


Drupal multi-site Aegir caching strategy We are migrating many sites from various content management systems onto a single Drupal/Aegir platform. We used to have a high density of sites on the same servers and Aegir definitely makes managing high density Drupal sites easier. Unfortunately having the same density of Drupal sites on scaled up hardware is leaving us with slower response times for the same amount of traffic. The platform/codebase is itself a bit of a beast, with some sites having 250+ modules enabled and response times stretching to 30+ seconds with Drupal caching disabled. The shared codebase acts as a sort of menu for business divisions to be able to choose features/themes from. With APC, Drupal cache and memcached running we still struggle on ocassion.

I think it makes sense to look at building up a caching layer in front of Apache-Drupal-Aegir before we start scaling the application layer horizontally. Aegir brings a big benefit to managing multiple sites and ending up with multiple Aegir instances takes away some of that benefit. In particular I like the idea of being able to cache some/all of the dynamic content for anonymous users in case the Aegir server is unavailable for any reason.

The options as I see it are:

Drupal boost module. Probably the easiest to setup but unfortunately does not appear to work with Aegir without some manual patching.
nginx as a reverse caching proxy. SSL support, easier to configure
Varnish as a reverse caching proxy. No SSL support, more difficult to configure
Ditch Apache and run Aegir on nginx/PHP-FPM. I prefer running Aegir on Apache at this stage as it will be easier for other engineers to troubleshoot.

We also have an HAProxy installation which load balances (actually failover/fault tolerance) for other applications, so we could always terminate the SSL at HAProxy and failover across multiple nginx or Varnish instances, with a single Drupal application server at the back. Though that means requests jumping through 3 layers to potentially hit the back-end, which doesn't sound too great.

Questions:

I'm tending to go for nginx as the reverse caching proxy because of simple configuration and management by other users and a single entry point for SSL management.
Is there any reason why I should choose Varnish instead?
Is nginx able to serve cached "dynamic" content to anonymous users in the eventuality of the back-end Drupal server being down?
Or is it purely restricted to static content such as images, JS, CSS etc?
What about having HAProxy on top of that, so we can failover between multiple nginx instances?
Or is it insane to have requests potentially going through 3 layers of proxy to reach the Apache/Drupal back-end?

Use what your comfortable with for maintenance and configuration.
Probably, depending on config. (I don't use nginx)
Not crazy, it allows for a very quick switch time to another webserver.

I have varnish combined on my webservers with a separate apache reverseproxy doing ssl termination.

A little custom hook triggers a reverse proxy update on a Aegir migrate task.


{500 service unavailable (with message)} error when trying to register a user with API I want to register a user on drupal site through REST,
I read this article, and implemented the instructtins exactly the same using Postman on drupal 8.3.

specially when I send this specification :

POST: http://example.com/user/register
Content-type: application/json
Data: { "name": [
  {
    "value": "test"
  }
],
"mail": [
  {
    "value": "aa@bb.com"
  }
],
"pass": [
  {
    "value": "test"
  }
]  }

Response is: 500 service unavailable (with message)

What should I do to solve the problem?

Just a stab in the dark here.

It seems that you have extra square brackets. I think this is why your error message refers to field 0 -- you're sending it an array. Try it exactly as the article displays, with no square brackets?

For example:
    "pass": {
        "value": "test"
      }

Good luck.

Update

To enable setting a password, you need to change a setting which is default in the install.

Go to admin/config/people/accounts (Configuration > People > Account Settings) and uncheck  "Require email verification when a visitor creates an account":

Granted you are allowing POST to Anonymous users as described in the article above, you should be good to go and get a response such as the following in PostMan:

{
  "uid": [
    {
      "value": "5"
    }
  ],
  "uuid": [
    {
      "value": "70738718-d4e9-455e-a1f6-cf95df613507"
    }
  ],
  "langcode": [
    {
      "value": "en"
    }
  ],
  "name": [
    {
      "value": "ac@bb.com"
    }
  ],
  "created": [
    {
      "value": 1487319576
    }
  ],
  "changed": [
    {
      "value": 1487319576
    }
  ],
  "default_langcode": [
    {
      "value": true
    }
  ],
  "user_picture": []
}

Hope this helps!!


Update field via url Is it possible to modify a field on a node via a url string? For example, my node (1) has a field (field_stage) which I'd like to update using the following url:

www.mysite.com/node/1?field_stage=complete

I can't seem to find a lead on this. Any help is greatly appreciated.

There's the Prepopulate module

  The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.

  For example, the following URL,

  http://www.example.com/node/add/blog?edit[title]=this is the title

  will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well.

It's only in dev for Drupal 7 but I've used it in a couple of projects and I haven't had any major problems. If it doesn't quite match your use case you could always take a look at the code, it shouldn't be that tricky to adapt for other purposes.


Efficient way to keep Drupal 7 session alive from another web app? Is there a simple PHP file I could create which, when called by an authenticated user, will keep their Drupal session alive?

I don't want to do an AJAX call to /index.php as this will cause unnecessary overhead. I just need a way to keep the session alive from another app.

Could I use the bootstrap method below, rather than instantiating the whole stack?

<?php
    define('DRUPAL_ROOT', '/my/local/root');
    include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
?>

If you're worried about unnecessary overhead, why not check out the High-performance JavaScript callback handler module.

It allows you to control what exactly gets loaded during the Drupal bootstrapping process, so that you would only spin up the bare essentials to keep your session alive from another app.

Check out this blog post for a good breakdown of how you implement this module:

High performance AJAX callbacks with Drupal 7 and the JS module


AJAX form submit error when sending form to twig in hook_preprocess_page I have a simple AJAX form that I can't submit when the form is passed from module to the template in hook_preprocess_page.  The same form works fine if sent from controller, it's just that the layout is complicated and I prefer to write the HTML part in the twig file and integrate the form where it fits best.

The form class:

    <?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SubmissionForm extends FormBase {
  public function getFormId() {
    return 'mymodule_submission_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['mail'] = array(
      '#title' => 'E-mail',
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['actions'] = array(
      '#type' => 'actions'
    );

    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#attributes' => array(
        'class' => array(
          'btn',
          'btn-success',
          'use-ajax-submit'
        ),
      ),
      '#ajax' => array(
        'wrapper' => 'submission-form-wrapper',
      )
    );

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }
}

The preprocess function:

/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$vars) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $vars['page']['submission_form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\SubmissionForm');
  }
}

The error:

  TypeError: Argument 1 passed to
  Drupal\Core\Ajax\AjaxResponse::setAttachments() must be of the type
  array, null given, called in
  /Volumes/Work/Git/myproject/public_html/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php
  on line 56 in Drupal\Core\Ajax\AjaxResponse->setAttachments() (line 37
  of
  /Volumes/Work/Git/myproject/public_html/core/lib/Drupal/Core/Render/AttachmentsTrait.php).

it's a fresh Drupal 8.7.10
devel and kint as contrib modules enabled
core inline form errors enabled
the form has only one required textfield and the submit button

Any suggestions on how to fix this?

Thank you!

The #ajax['wrapper'] replaced with #ajax['wrapper_selector'] that's why the form disappear see this issue:

Try with:

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SubmissionForm extends FormBase {

  public function getFormId() {
    return 'mymodule_submission_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['mail'] = [
      '#title'    => 'E-mail',
      '#type'     => 'textfield',
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type'       => 'submit',
      '#value'      => 'Submit',
      '#attributes' => [
        'class' => [
          'btn',
          'btn-success',
          'use-ajax-submit',
        ],
      ],
      '#ajax'       => [
        // Change here the wrapper with wrapper_selector
        // 'wrapper' => 'submission-form',
        'wrapper_selector' => '#submission-form-wrapper',
      ],
    ];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }
}


referencing a field in a node in hook_node_api I am using drupal 6. I have a simple question:

Here's a snippet of code from my hook_node_api function:
...

case 'presave':
    {
        if($node->type == 'example')
        {
            if($node->content['field_alert']['#value'] == TRUE)
            {
                //do something
                drupal_set_message('Your update will be emailed out.');
            }
        }
    }
   break;

I want to reference the value of a field named field_alert inside of a node type "example" but I'm doing it properly since its not working. How do I do this?

If memory serves it should be something like this:

if (!empty($node->field_alert[0]['value'])) {
  //do something
  drupal_set_message('Your update will be emailed out.');
}


How to get user data/authenticate with bearer token - Simple OAuth - Decoupled I am working on a single page application using NUXT and Drupal 8 as headless CMS. for user authentication token I am using Simple OAuth Drupal 8 module. Everything is working fine. I am getting the access token when I send request to this API https://website.com/oauth/token as you can see below.

What I want now is to authenticate the user using this token. How will I get the user detail every time I refresh the page using this response? Is there any API where we send the access token with the bearer .

Excuse me Please if I am using the wrong terms I am new to Decoupled.

But as you know setting up JWT for authentication. we send two requests. 1 request to get the token and another request to get the user using that token as mention in this tutorial.

I don't know if I made my point clear. I am totally lost here.

Thanks

I'm not familiar with the Nuxtjs framework discussed in the tutorial you linked to, but basically once you have the access_token the user should be authenticated in Drupal. It should be enough that you on each request set an Authorization header that contains that access token, as described in the tutorial:

this.$axios.setHeader('Authorization', 'Bearer ' + resp.data.access_token)

Drupal will then read the Authorization header value and authenticate/authorize the user based on the Drupal role that the user has assigned to itself. So provided you have the REST endpoints for user information active you should be able to make a GET request to /user/{user} and get the logged in user information.

You can try this out using curl or Postman by manually adding the header to the request:

Authorization: Bearer HereGoesTheValueOfTheAccessToken

A curl example:

curl --request GET \
  --url https://mydrupaldomain.com/user/123 \
  --header 'authorization: Bearer HereGoesTheValueOfTheAccessToken'


How can I see my drupal site as a anonymous user while logged in as admin? I want to use Devel Themer to look at the "homepage" comment field, but it only shows up for anonymous users.

Is there anyway to see a page as a anonymous user would, and at the same time be logged in as an admin so that I can use the Devel Themer module?

No that is impossible.

What you could do is give access to devel for all users. You shouldn't be using devel in a live environment anyways, so just make sure you remove devel and revoke permissions before staging to production environment.


What would be best method to append bootrap css to non bootstrap themes but not affect layout? I want to use Adaptive themes, I like the layout options, however, I like the Bootstrap look and feel.

So I want Adaptive theme layout css with boostrap visual css basically.

What would be the best way to achieve this short of getting into the HTML of Adatptive them and changing all the classes on elements?

You can customize your bootstrap package for download here:

  Customize Bootstrap's components, Less variables, and jQuery plugins to get your very own version.

http://getbootstrap.com/customize/

After that, you can add just the required CSS/JS to your theme as per the usual methods


How to prevent the form from redirection after submission in order to see the kpr() results? I installed Basic Cart module and I needed to completely modify its submission handler. So I used the following code:

function THEME_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'order_node_form'){
        $form['#submit'] = array("my_form_order_submit_handler");
    }
}

and It works perfectly. The order_node_form form has some values in its inputs and I need to get them. I don't know how to get the values from the $form variable so I need to kpr this variable. This is the my_form_order_submit_handler function:

function my_form_order_submit_handler($form, &$form_state) {
    kpr(1);
}

The problem is it doesn't kpr the 1 and is redirected to some where else. In the question kpr() in my form validation and submit function is not being called it has been suggested to add the following codes in form alter function and tried this code:

function THEME_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'order_node_form'){
        $form['#submit'] = array("my_form_order_submit_handler");
        $form_state['rebuild'] = TRUE;
        $form_state['no_redirect'] = TRUE;
        $form_state['redirect'] = FALSE;
    }
}

But it is still redirected and I can't see the kpr(1) result in the submission function. How can I prevent the page being redirected to some where else after the my_form_order_submit_handler function?

Thanks


Creating a "Remind User" link in Views I've created a View that lists when a user has last logged in, using table format. I'm wanting to add a field that's a link to remind the user to login again (I've used a UID field and am rewriting the output to be a link, with UID as an argument at the end).

What's the most sensible way to trigger an email via Views?

Thanks!

Instead of Views, I would use Rules + Rules Scheduler (bundled with Rules).  This will allow the site itself to automatically send e-mail reminders at intervals you specify.  Johan Falk explains how to set this up in his Rules Scheduler screencasts.

EDIT: To do this in Views, I would add the Flag module, which also integrates with Rules.  Set up a flag for "Send reminder e-mail" (give permissions only to admin, etc.)  Then, write a rule that sends an e-mail that is triggered on the event "User is flagged..."  Last, add the flag as a relationship in your view and then add a flag link.

You will have to consider what to do about unflagging users.  By default, the user will show up as flagged after a reminder is sent, which might be nice because you'll know that the user has already received a reminder.  However, if you need something more sophisticated, you could make an additional rule that automatically unflags the user after he/she is flagged and keep track of the number of reminders you have sent by using flag's count property (also accessible via rules/views).


Migrate D2D UI - Source field missing from dropdown menu when editing field mappings I got an PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value error on one of the fields for a content type that I'm importing from a D6 site to a D7 site, and the import of all those nodes is failing. I looked at the field on the Field Mappings page, and found that the field is not in the Source dropdown menu, and therefore cannot be mapped. I think this is why the import is failing. The field exists in both the source D6 database and the destination D7 database.

How do I get Migrate D2D to recognize this field so that it appears in the field mappings menu?

I found the cause of the problem, and a solution:

I had cloned my old D6 site, then performed the core and CCK upgrade to D7 as described in Drupal's documentation, during which I mistakenly converted the above-mentioned field to a Boolean type when it should have been (based on the old site's field) converted to the List (text) type. I manually deleted the field and recreated it as the proper type, ran the migration, and the nodes were imported as expected.


drupal 7, db_select(), strange behavior : malformed query I have a table: mantenimiento_extras.

I want a query like this: select * from mantenimiento_extras where id in (7, 9).
(this case assumes passing array(7, 9), but it could be variable, even including the case for "in ()".

I execute this query:

db_select("mantenimiento_extras")->fields("mantenimiento_extras")->condition("id", $values, 'IN')->execute();//$values is guaranteed to be an array.

I get this query, and an error:

SELECT mantenimiento_extras.* FROM {mantenimiento_extras} mantenimiento_extras WHERE (id IN ()); Array( )

I modify the dynamic query:

db_select("mantenimiento_extras")->condition("id", $values, 'IN')->execute();

I get this query, and an error:

SELECT FROM {mantenimiento_extras} mantenimiento_extras WHERE (id IN ()) ; Array ( )

Now I bang my head against the nearest object in my desk.

Why is it generating malformed queries?

If the array is empty, you'll get WHERE foo IN (). That's invalid SQL syntax.

To prevent, use a conditional:

if (!empty($values)) {
  // Run the query.
}


how to get summary of content in following code In my block code i have following code in one case:

$query = db_select('node', 'n');
    $query->condition('n.status', NODE_PUBLISHED);
    $query->condition('n.type', 'news');
    $nids = $query
    ->fields('n', array('nid'))
    ->orderBy('changed', 'DESC')
    ->range(0, 1)
    ->addTag('node_access')
    ->execute()
    ->fetchCol();
    $nodes = node_load_multiple($nids);
    $content = '

Latest News
';
    foreach($nodes as $record)
    {
        $content.='
'./*need summarry here*/.'
'.l('Read more', 'node/'.$record->nid);
    }
    $content .= '

';
    $block['subject'] = t('Latest news');
    $block['content'] = $content;

How do i get summary of content in there?

You'll need to look in $record in your foreach statement and find the content you want. (probably $record->body) Since you are polling the database manually (vs. using display_modes like teaser / full) you'll probably have to create the summary yourself.

I suggest using the truncate_utf8() function which "Truncates a UTF-8-encoded string safely to a number of characters.", it supports adding "...", word boundaries etc.

As for this "looking" into your $record var, I suggest using the Devel module, which ships with a function dpm() which can take basically any variable and output it in a pretty navigationable message on your page.


Drupal JavaScript settings versus jQuery.data() When I writing JavaScript code for my module, I could use jQuery.data() or the setting object passed to the Drupal behavior my module add.

Should a module always use the settings object, or could I use jQuery.data() in my module?
Is there any case where using jQuery.data() is problematic when used in AJAX code?

Personally, I used Drupal.settings as a read-only object for communicating settings and configuration information from PHP to JS.  Runtime state isn't appropriate here.

jQuery.data() should only really be used to pull out data attributes that you have set via PHP, and for setting data that is specific to that element-only.

Runtime logic and state should be stored in its own closure.  I use a variant of the Javascript Module Pattern, which I have adapted for Drupal.  Boilerplate looks like:

var FOO = (function(me, $, Drupal, undefined) {
    me.name = "FOO";

    // local properties

    var foo = null;
    var bar = null;

    // local functions

    function somethingAwesome () {
        console.log(me.name + '.' + arguments.callee.name + '()');
    }

    // global properties

    me.baz = null;

    // global functions

    me.somethingAwesomer () = function somethingAwesomer {
        console.log(me.name + '.' + arguments.callee.name + '()');
    };

    // Drupal

    function init (context, settings) {
        if (settings.foo) {
            console.log(me.name + '.' + arguments.callee.name + '()', $.fn.jquery);

            // do stuff
        }

        Drupal.behaviors[me.name] = undefined;
    };

    Drupal.behaviors[me.name] = {
        attach: init
    };

    return me;
}(FOO || {}, jQuery, Drupal));

I don't do a lot of true behaviors, though, hence making my initialization function a oneshot.


D8 render a contact form from theme preprocess I want to render a form in a node view. I made an entity reference to a contact form, then in the preprocess_node I'm trying to get the render array of the contact form.

function mysupertheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mynodetype') {
    if (!empty($node->field_mynodetype_form->referencedEntities())) {
      $contact_form = $node->field_mynodetype_form->referencedEntities()[0];
      $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $contact_form->id(),
      ));

      //$form = \Drupal::entityFormBuilder()->getForm($message);
    };
  }
}

I don't know how to call entityFormBuilder in preprocess. Is this the right way to do this ? How can I display a choosen contact form in a node ?

Thanks

Your code will work when this patch is implemented:

Add a view builder for contact_form


How do I get the menu ID based on the menu title? I am looking for a function to call like in the following snippet:

get_menu_id("my menu title");

Do you have any tips?

Tricky question. In short, you can't. You can query the menu_links table all you want, be my guest, but realize please that the title you see on the page and the title in the database is the same only in one case: you are running an English-only website and the title_callback is t. (And if you are on D7, you are not overridden in settings.php or in D6 with string overrides and...) Otherwise the title is generated dynamically and it's literally impossible to figure out from the DB alone.


Custom variables in node content Is it possible to use custom variables in content?

For example we have the price of a product which is listed on a large number of nodes as £9.99... This price then changes to £11.99. Updating this price becomes a pain!

What we would like is to be able to have a variable such as [product1price = £9.99] which we can include in node body. Then should we need to change this price, we can edit the variable to instantly update it everywhere it appears in the system.

Does a Module already exist for functionality like this?

You could implement custom tokens, and the coupled with the module http://drupal.org/project/token_filter - your content will be rendered as per usual.

In this way you could have a token:

[price-tier-1] = $9.99

and when the price changes you only have to change the token value (in one place, in code)


How do I change the delta values using a hook? I have a view getting all fields from nodes that have a relationship with the viewed node (using delta = all); it then only shows one node using CSS styles.

How do I change the delta value for every request and take its value as an argument from the URL?

I reloaded the page from JavaScript when the user needs to see the next field (using pager controls).

Which hooks does the Views module provide to edit that value?

You can specify the validation criteria with PHP code in your contextual filter settings:

When the filter value IS in the URL or a default is provided

Specify validation criteria -> PHP Code

if($handler->argument){
  $view->display['default']->handler->options['pager']['options'] = array(
    'offset' => 0,
    'items_per_page' => $handler->argument
  );
  return true;
}
else {
  return false;
}

That's it. Now, for every request the delta will be equal with the argument from the URL.
$handler->argument It's the argument which has been provided by your contextual filter.


Is there any way of removing (or unflagging) all of a user's flags? I have a situation where a privileged user (role that is purchased) can flag content and receive email notifications to comments posted. When the role is expired, I need for them to stop receiving these emails. Is there any way (possibly using rules) to unflag all of the content they have flagged? Or is there another approach I should be taking?

You have to find out the event for expiring the roles, there you can unset the flag programmatically. However with other approach you can also add a check the role of user you are sending email to.

Here goes the steps:

Install rules_conditional module. This module allows to add
extra conditions inside the rules action.
Please check the screen shots.

Configurations as in following screenshot.

Remember to have the nesting structure as in screenshot.


recursive entity reference in a view (tree view?) I have content type with entity reference to node of same content type. And I would like to show the nested references in the node view. Sort of a tree view.

How could I accomplish that?

I guess I need a view and a view field? But even not yet sure how to create a view which does recursive relationship...

It is for managing software dependencies and releases, there are libraries (=content type) dependent on 1:n libraries.

That can be accomplished with a custom module (great question by the way)...

First define a function to handle the whole process:

function make_tree() {

  // This is the nid of the root of our tree - could be passed in as an argument
  // instead of being static.
  $root_nid = 110;

  // First build an array with 3 fields - id, parent_id, title.
  $data = array();

  // We call add row once and then it's called resursivly to fetch each child.
  add_row($root_nid, null, $data);

  // Here we can inspect our data in it's flat form.
  //dpm($data);

  // Now turn the flat data into a multi-dimensional array.
  $tree = build_tree($data);

  // And inspect our tree.
  dpm($tree);

  // Could return the tree here or do anything we want with it...

}

Then define the function to build the flat array of data:

function add_row($nid, $parent_nid, &$data) {

  $node = node_load($nid);

  $data[$node->nid] = array(
    'id' => $node->nid,
    'parent_id' => $parent_nid,
    'title' => $node->title,
  );

  if(isset($node->field_dependent[LANGUAGE_NONE])) {
    // Now loop childeren to add rows for them too.
    // My entity relationship field is called dependent but rename here as
    // necesary.
    foreach($node->field_dependent[LANGUAGE_NONE] as $child) {
      add_row($child['target_id'], $node->nid, $data);
    }
  }

}

Once this step has been completed the $data array will look like this.

And then finally the function to turn the flat array into a multi-dimensional one (credit to this answer for this step):

function build_tree(array $elements, $parentId = 0) {
    $branch = array();
    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = build_tree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }
    return $branch;
}

I've just tested this and my final array looks like this.


form and answer in the same URL I'm working my way around Drupal API with limited success.

I want to have a URL with a form in it, so that when I "GET" that URL I get the form (have that), when I input a wrong "code" into that form and POST that same URL I get the same form with an error message (have that too), but when I POST that same URL with the right "code" I get a different code, no longer displaying the previous form.

No redirects, all the requests (posts and gets) should be targeted to domain.com/entry

This is a code I have (simplified):

function entry_menu() {
    $items['entry'] = array(
        'page callback' => 'entry_handler',
        'access arguments' => array('access entry'),
        type => MENU_CALLBACK,
    );

    return $items;
}

function entry_handler() {
    return drupal_get_form('entry_daily_code');
}

function entry_daily_code($form, &$form_state) {
    $form['code'] = array(
        '#type' => 'textfield',
        '#title' => 'Code for Today',
    );

    form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Access',
    );

    return $form;
}

function entry_daily_code_submit($form, &$form_state) {
    if (isset($form_state['values']['code']) && $form_state['values'] == "1234") {
        drupal_set_message(t('Success'));
    }
    else {
        drupal_set_message(t('Fail'));
    }
}

I imagine that what I want to do should happen in "entry_handler".

It needs to know the status returned by the form, and to either return the form, or a different content, but I'm failing at that.

Made a diagram to illustrate my point, in case it wasn't coming across:

Thanks for any pointers in the right direction.

When your visitor send the form, Drupal process the input, executing the validate and submit handlers (you have only provided your submit handler).

Once handlers are executed, Drupal needs to send a page to the user (the answer), so, if no redirection is made (in $form_state['redirect']), Drupal renders the content for the current URL, so Drupal renders your form again (because is a new HTTP petition, there's no memory of past petitions).

You must do something in the submit handler to let Drupal know your visitor can see the protected content.

For example, you can set a flag in the $_SESSION data. Then, in the entry_handler check for that value: if it's there the content is rendered, if not then the form is rendered.

Something like this (I've also divided your submit handler into validate and submit handlers):

function entry_daily_code_validate($form, &$form_state) {
    if (isset($form_state['values']['code']) && $form_state['values'] != "1234") {
   form_set_error('code', 'Invalid code!');
}

function entry_daily_code_submit($form, &$form_state) {
  $_SESSION['code_validated'] = TRUE;
}

function entry_handler() {
  if ($_SESSION['code_validated' == TRUE) {
    return 'Arbitrary content';
  }
  else {
    return drupal_get_form('entry_daily_code');
  }
}

If your visitors are registered users you can edit the user account or whatever merthod you like. Remember that session data can be lost.


Programmatically adding argument to view that already uses a context filter I have a view that uses the id of the currently logged in user as a contextual filter. This was set using the Drupal UI and works well. Then I wrote a custom module that adds another parameter (a specific node id) to all views on my site. All views need this second parameter (and it needs to be added programmatically). This approach works well for all views that only use the programmatically added parameter as a contextual filter. However, the view that needs 2 filter values does not work, because I think I do not handle the order of parameters in the args array correctly. How do I set up views that already use filter values, but I need to add more programmatically (I set $args[0], but I guess this might be the problem) ?

I should say that I do not want those filters to appear in the URL.

testmod.module:

function testmod_views_pre_view($view, $display_id, array &$args) {
  ...
  $args[0] = $value;
}

I thought I could just read the view's $arg array and add my special argument to it programmatically, but for the view that already uses the logged-in user as a contextual filter, when I print print_r($args) it is an empty array, although the view is working correctly (and only shows results for the current user). Are contextual filters that I set up via the UI stored in a different place than $args ?

What needs to be done to tell the view how to use the 1. and 2. filter values correctly ?

Edit: I read that hook_views_pre_view() is too early to find contextual filters in the arg array (at that point you would only see arguments in that array passed via URL). Which hook would be best to achieve what I'd like to do ?

I now have a better understanding and found a solution. hook_views_pre_view() is indeed too early to see arguments that are NOT passed to the view via URL. That explains why $view->args was empty in my case. In hook_views_post_build() you do see ALL arguments (URL+nonURL) passed to the view. However, the way I solved my issue is still using   $args[0] = $value; in hook_views_pre_view. That means the first argument passed to all views will always be $value. For views that are using additional arguments, Drupal will add them to $args later on. In my special case I have views that might not necessarily need the first argument that I pass, so I had to add a contextual filter Global: Null (at the first position) that allows a contextual filter value to be ignored (and as a default I set 0). This way each view does have the correct number of contextual filters and the order is correct, whether the view needs to use the very first argument or not. It might not seem intuituve to pass an argument to every view, even though not all views really need it, but adding a Global: Null dummy filter is easier than excluding views in an if() statement and always having to modify the module code when a new view has to be added later on.


How do I alter the title display with hook_user_view? /**
 * Implements hook_user_view().
 */
function my_statistics_user_view($account) {
    $account->content['statistics']['daily_avg'] = array(
        '#type' => 'user_profile_item',
        '#title' => t('Daily average'),
        '#markup' => 'Hello',
        '#attributes' => array('class' => array('daily-avg')),
    );
}

The above code renders:

Daily average
Hello

in a user's account profile. I would like to render it inline, like this:

Daily average: Hello

How is this done? Thanks.

You don't. To alter display, you have to create or edit user-profile.tpl.php file in your theme, or template_preprocess_user_profile() function in template.php


How do I get the current taxonomy term from the plug-in context? When on a node, the following annotation will obtain the node from the context:

/**
 * @Condition(
 *   id = "node_type",
 *   label = @Translation("Node Bundle"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
 *   }
 * )
 */

As shown here: https://www.drupal.org/docs/8/api/plugin-api/plugin-contexts

Is there an equivalent way to do this with taxonomy terms when on /taxonomy/term/%?

The code below certainly works but I'm wondering if there is a cleaner method like for nodes. Note that I'm also aware of the Term::load($tid) method but that still requires parsing the URL to obtain the tid and isn't portable (the code can be used only when run on a page).

  /**
   * Return current term.
   */
  public function getCurrentTerm() {
    $term = null;

    // Below we are using the general method to obtain the objects.
    // \Drupal\taxonomy\Entity\Term::load($tid) is the other

    // Get the unaliased path in the form /taxonomy/term/tid.
    $current_path = \Drupal::service('path.current')->getPath();

    preg_match('/\/taxonomy\/term\/\d+/', $current_path, $matches);

    // Return null if not in proper form.
    if (count($matches)) {
      // Find the parameters for this route.
      $params = \Drupal\Core\Url::fromUri("internal:" . $current_path)
        ->getRouteParameters();

      // Fetch the taxonomy object.
      $entity_type = key($params);
      $term = \Drupal::entityTypeManager()
        ->getStorage($entity_type)
        ->load($params[$entity_type]);
    }

    return $term;
  }
}

Update 10.05.2019:

There is an unresolved issue about that on drupal.org:
Term route context.

It uses the same solution as in my answer below.

Original answer:

You can create a custom context provider "Taxonomy term from URL".

service definition in MYMODULE.services.yml:

  MYMODULE.taxonomy_term_context:
    class: Drupal\MYMODULE\ContextProvider\TaxonomyTermContext
    arguments: ['@current_route_match']
    tags:
      - { name: 'context_provider' }

The /src/ContextProvider/TaxonomyTermContext.php

<?php

namespace Drupal\MYMODULE\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Sets the current taxonomy term as a context on taxonomy term routes.
 */
class TaxonomyTermContext implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * The route match object.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs a new object.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $result = [];
    $context_definition = new ContextDefinition('entity:taxonomy_term', $this->t('Taxonomy term from URL'));
    $value = NULL;
    if (
      ($route_object = $this->routeMatch->getRouteObject())
      && ($route_contexts = $route_object->getOption('parameters'))
      && isset($route_contexts['taxonomy_term'])
    ) {
      if ($term = $this->routeMatch->getParameter('taxonomy_term')) {
        $value = $term;
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition, $value);
    $context->addCacheableDependency($cacheability);
    $result['taxonomy_term'] = $context;

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    $context = new Context(new ContextDefinition('entity:taxonomy_term', $this->t('Taxonomy term from URL')));
    return ['taxonomy_term' => $context];
  }

}

The ctools module provides already the condition plugin for entity bundles:ctools/src/Plugin/Condition/EntityBundle.php. You can use it together with the new service.

See also config block visibility by vocabulary, but it not show block access fail(miss context).


Add a new Taxonomy term page I use drupal 8 and I want to add a new view page to taxonomy view.

I tried to dublicate default taxonomy page view and changed path

from: taxonomy/term/%/
to : taxonomy/term/%/newpath

but this is not working. why would this not work?

Did you tried to change the "Contextual filter" settings ?

WHEN THE FILTER VALUE IS NOT IN THE URL to -> Provide default value (taxonomy term from url)

or check the WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED validation


Adding custom actions to rules I am trying to add custom actions, events and conditions to work with Rules interface. I began by adding custom actions by creating a custom module. Here's my code till now.

rules_example.info :

name = Rules Example
description = Test module to add new actions, events, and conditions
core = 7.x

rules_example.module :

<?php
/**
 */

rules_example.rules.inc :

<?php

 /**
  * @file
  * Example rules module to create actions, events, and conditions
  */

/**
 * Implement hook_rules_action_info()

 * Declare any meta data about actions for Rules
 */

function rules_example_rules_action_info() {
$actions = array(
    'rules_example_actions_hello_world' => array(
        'label' => t('Print Hello World on the page'),
        'group' => t('Rules Example'),
        ),
    'rules_example_actions_hello_user' => array(
        'label' => t('Print Hello to the logged in user'),
        'group' => t('Rules Example'),
        'parameter' => array(
            'account' => array(
                'type' => 'user',
                'label' => t('User to say hello to'),
                ),
            ),
        ),
    );

return $actions;
}

/**
 * The action function for rules_example_action_hello_world
 */

function rules_example_action_hello_world() {
drupal_set_message(t('Hello World'));
}

/**
 * The action function for rules_example_action_hello_user
 */

function rules_example_action_hello_user($account) {
drupal_set_message(t('Hello @username',
 array('@username' => $account->name)));
}

Well, this is it. I have saved all these files in a folder rules_example in sites/all/modules. When i install the module or rather try to install it i get this error:

ReflectionException: Function rules_example_actions_hello_world() does not exist in ReflectionFunction->__construct() (line 1691 of /opt/lampp/htdocs/sites/all/modules/rules/includes/rules.core.inc)

I am not sure what the error is. I am going to rules.core.inc but am not able to understand what is causing the error. Thanks.

There is a typo in your code - the function name is "rules_example_actions_hello_world" in your actions definition, while the actual function is called "rules_example_action_hello_world".


LDAP module and AD global catalog Does anybody successfully authenticate against AD global catalog? I've got the following configuration:

LDAP server:
ldaps://service.mydomain.com
LDAP port:
3269
Binding Method:
Service Account Bind
Base DNs for LDAP users:
DC=service,DC=mydomain,DC=com
DC=otherdomain,DC=mydomain,DC=com
AuthName attribute:
userPrincipalName

The module successfully authenticates users, which are members of parent domain called "service", but LDAP search can't find any user from "otherdomain", which is connected to parent domain inside AD domain forest. I´m able to test LDAP search using ldp.exe and using this tool I can find any user from any domain.

Also, there is the following error message in the Drupal watchdog:

  ldap_search() function error. LDAP Error: Referral, ldap_search() parameters: ldap_search() call: base_dn: DC=otherdomain,DC=mydomain,DC=com, filter = (userPrincipalName=somebody@otherdomain.mydomain.com), attributes: , attrsonly = 0, sizelimit = 0, timelimit = 0, deref = , scope = 3

Any help will be greatly appreciated.

I know it's been over half a year so you may have already found the answer to this, but I thought I would weigh in as it is a process that I am working on myself.

For the Base DN, consider simply using DC=mydomain,DC=com.  I have not had to do this yet, so it was just a thought from their suggestion of using a higher Base DN.

I had problems authenticating until I made sure of these items:

AuthName attribute and AccountName attribute set to: sAMAccountName,
PUID set to: objectGuid
then check the box with the question "Does PUID hold a binary value?

After that, authentication went perfectly.  Good luck!