Using call_user_func_array on the db_select object call_user_func_array() makes calling a variable function with a set of arguments fairly simple. I would like to do the same with db_select() passing in various options to different methods. Going to use dblog_cron from 6.x and 7.x as the examples. How can I do something similar in D7?

D6 Code

<?php
// These 2 lines return the same thing in D6
$max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
$max = call_user_func_array('db_result', array(call_user_func_array('db_query', array('SELECT MAX(wid) FROM {watchdog}'))));
?>

D7 Code

<?php
$min_row = db_select('watchdog', 'w')
  ->fields('w', array('wid'))
  ->orderBy('wid', 'DESC')
  ->range(999, 1)
  ->execute()
  ->fetchField();

 // Getting closer but not what I'm looking for.
 $min_row = db_select('watchdog', 'w')
   ->{'fields'}('w', array('wid'))
   ->{'orderBy'}('wid', 'DESC')
   ->{'range'}(999, 1)
   ->{'execute'}()
   ->{'fetchField'}();
?>

How can I call the above code without eval using something like call_user_func_array() or ReflectionMethod::invokeArgs?

Breaking this down...

<?php
$x = call_user_func_array('db_select', array('watchdog', 'w'));
$x = call_user_func_array(array($x, 'fields'), array('w', array('wid')));
$x = call_user_func_array(array($x, 'orderBy'), array('wid', 'DESC'));
$x = call_user_func_array(array($x, 'range'), array(999, 1));
$x = call_user_func_array(array($x, 'execute'), array());
$min_row = call_user_func_array(array($x, 'fetchField'), array());
?>

In-lining everything... so it can be done.

<?php
$min_row = call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array('db_select', array('watchdog', 'w')), 'fields'), array('w', array('wid'))), 'orderBy'), array('wid', 'DESC')), 'range'), array(999, 1)), 'execute'), array()), 'fetchField'), array());
?>

---Solution below---

<?php
// Setup data array.
$args = array(
  array(
    'db_select', array(
      'watchdog', 'w',
    )
  ),
  array(
    'fields', array(
      'w', array('wid')
    )
  ),
  array(
    'orderBy', array(
      'wid', 'DESC'
    )
  ),
  array(
    'range', array(
      999, 1
    )
  ),
  array(
    'execute', array()
  ),
  array(
    'fetchField', array()
  ),
);

// Helper function.
foreach ($args as $data) {
  if (!isset($last)) {
    $last = call_user_func_array($data[0], $data[1]);
  }
  else {
    $last = call_user_func_array(array($last, $data[0]), $data[1]);
  }
}

// Get output
echo $last;
?>


Why is the database not updated before a next Rule is launched? I have two Rules (created with the Rules module) that are both launched when an article is flagged with the Flag Approved:

Rule 1. Publish the flagged article with the action Publish content.
Rule 2. Count the amount of published articles by the author of the flagged article. Display a message when this number is 5.

I'm using the following code in the condition of Rule 2:

return MYMODULE_count_articles($flagged_node->uid) == 5;

where my custom module contains the function

function MYMODULE_count_articles($uid) {
  $count = db_query("SELECT COUNT(*) FROM node WHERE uid=$uid AND status=1 AND type='article'")->fetchField();
  return $count;
}

The condition of Rule 2 is evaluated as FALSE when the 5th article is flagged with Approved, but evaluates as TRUE when a 6th article is flagged.

I suspect that this problem is caused because the database hasn't been updated yet when Rule 2 launches, because debugging the $count variable at the 5th flagging returns 4 instead of 5. Also, executing the condition's code afterwards yields the correct value 5.

Is this a know problem/phenomenon or a bug in the Rules module? Or is there an easy way to fix it (apart from changing the condition to ... == 4, which is really dirty)?

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rule 2 in a Rules Component, so that your Rule 1 "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Publish content" for sure completed, and your "number" will have been updated as expected.


How to use glossary contextetual filter? I created a user type view and add a contextual filter of User:Name. I enabled the glossary mod add character limit to 1. Same setting as glossary view. But still it not showing the filter (A|B|C). Am I missing any setting?

Solved by Adding a Attachment Display to views.


DatabaseSchemaObjectExistsException: Table products already exists I try to install my module, and everything goes ok, without an error while enabling

  DatabaseSchemaObjectExistsException: Table products already exists. in
  DatabaseSchema->createTable()...

I checked it and there wasn't the products table.

My install function is:

function products_schema() {
    $schema['products'] = array(
        'description' => 'The base table for products.',
        'fields' => array(
            'pid' => array(
                'description' => 'The primary identifier for a product.',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'name' => array(
                'description' => 'The title of this product, always treated a non-markup plain text.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'created' => array(
                'description' => 'The Unix timestamp when the product was created.',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'description' => 'The Unix timestamp when the product was most recently saved.',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
            ),
            'description' => array(
                'description' => 'The product description.',
                'type' => 'text',
                'not null' => FALSE,
            ),
        ),
        'indexes' => array(
            'node_changed' => array('changed'),
            'node_created' => array('created'),
        ),
        'primary key' => array('pid'),
    );

    return $schema;
}

function products_install() {
    drupal_install_schema('products');

    cache_clear_all(NULL, NULL, '*');
}

function products_uninstall() {
    drupal_uninstall_schema('products');

    $result = db_select('file_usage', 'f')
            ->fields('f')
            ->condition('type', 'product')
            ->condition('module', 'products')
            ->execute()
            ->fetchAll();

    foreach ($result as $row) {
        $file = file_load($row->fid);

        if ($file) {
            file_usage_delete($file, 'products', NULL, NULL, 0);
            file_delete($file);
        }
    }
}

From your previous questions it looks like you're using Drupal 7, but the above code is partly for Drupal 6.

You don't need to add/remove the schema manually any more in Drupal 7; implementing hook_schema() is enough. Drupal installs the schema for you, and then when you it hits your implementation hook_install(), the table does already exists so it throws an error.

Just remove the calls to drupal_install_schema() and drupal_uninstall_schema(), uninstall the module and try again - it should work fine.


Merging numbers into one field in YAML I'm trying to use a Webforms to create a team registration form, but I was thinking to automatically generate a participants ID number in the Webform based on certain fields in the form and based on user attributes.

The ID number is composed of 5 different fields.

A group code, this is independent on the form that is being submitted
A organization code, this is a multi-organization team registration, so each organization is given a specific code embedded into a participants ID number
Team code, each group of people (or team) is also given a specific code
Person Code, each individual person is given a number so we can distinguish persons in a team.

All of these codes are already set on the form (either through the registering user's attributes) or via the form itself. The user will not have to enter any of these attributes.

I understand in Microsoft Excel that you can combine 4 different fields by the following

=A1&&A2&&A3&&A4

But is there something similar in YAML code for Webforms?

Thanks!

The Webform module for Drupal 8 supports a Computed Twig element which can be used to combine and calculate a dynamic value using Twig based on multiple elements.


Site name cannot be changed for different languages and domains Drupal 7 I have installed Domain Access, Domain Variable, Variable + i18n integration, etc. I have been able to change the value of site_lema for different domains and languages, but I cannot override the value of site_name, which is taken, apparently, from the Domain Access human readable name. I don't understand if that is a limitation, if I have something wrong in my Drupal (I have tested in two different installations), or there is some conflict with other module? Someone has achieved to have site_name changed for every possible domain/language combination?

It seems that the option in Domain Access "Override site name with name of domain." was causing all the problems. It was so simple, but was driving me crazy. It was checked and thus if I tried to change the value elsewhere (in the Variables section or in the Site info section), nothing happened, the value was not changed. Unchecking this option ("Override site name...") in the Domain Access configuration, this variable "site_name" can have multiple values depending on language and domain combinations.


resizing the dimensions of the an image field I need to re-size all the thumbnails of my article images to fit the dimensions of the redesign.

Is there a easy way to do this?

I hope you attach an image field to the content type. In that case, you can define the image styles at admin/config/media/image-styles. It is the core continuation of the Imagecache module.

Create a new style and set the dimension for the images; then, go to admin/structure/types, click "Manage display" in "Article", and click the icon under format of image field; choose the image style you created.


Advantages of utilizing Entity Field query over views? I've been reading a little about entity field queries.

What are the advantages of using entity field queries (EFQ) over views?

What are the largest pain points/disadvantages of using EFQ ?

Advantages of EFQ:

It's in Core, so you don't actually depend on an extra contrib module. Sometimes Views isn't considered an option.
It's very easy to handle programmatically, while Views is kinda awkward to handle in code.
I have made no performance measurements, but based on the fact that EFQ's are simpler than Views, I believe it will often have better performance.

Advantages of Views:

You can do (almost) arbitrary joins and collect most any kind of data. EFQ finds entites and their fields, period. It's also fairly easy to expose new data to Views. There's even a module for that.
It has a UI, and is as such far more user-friendly than building everything in code.
Views can easily be cached. An EFQ needs custom logic for this.


Error 500 when including controller file in Route I am trying to upgrade a mailing list from drupal 7 to 8. I am getting an 500 error when I include my controller in the route file. I checked the path in both route and controllers and almost tried removing all values from the class, still I am getting the error my route file is:

mailing_list.admin:
  path: '/admin/structure/mailing_list'
  defaults:
_controller:'\Drupal\mailing_list\Controller\MailingListController::mailingListList'
_title: 'Mailing List'
  requirements:
_permissions: 'administer mailing lists'

My Controller Code is:

namespace Drupal\mailing_list\Controller;
class MailingListController extends ControllerBase {
  public function mailingListList() {
$output = array('table', array('header' => '1'));
}
}

I have removed the lines in controller function to avoid 500 error, but still I am getting 500 error.

If that is the entirety of your controller, then you are missing use statement for ControllerBase.

namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = array('table', array('header' => '1'));
  }
}

You also need to return a Response or renderable array from the controller method the route calls.

Example:

namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = [];
    $output['#markup'] = $this->t('Hello!');
    return $output;
  }
}

See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

If that does not work you need to post the full error you are getting.


Displaying embeded image as background I would like to allow users on my site to be able to display a background image, not from their computer but from an outside source, for their profile page.

I assume the best way to do this is to add some kind of an image embed field on the front end of the profile page and tweak the CSS so that the image resides in the background (panel.)

If so, my question is twofold: (1) What is the best module to use to link to the image and, (2) how do I display the field to users? Do I create a content type and use exposed filters in views to display it?

Is there a better approach?

Thanks. :)

Try the Background Images module as a ready-built solution:

  Background images is a collection of modules that allows users to add
  background images to html elements on pages of the site


Copy site to another domain - XML SiteMap wrong and Theme Settings not the same I copied my productive site from www.mydomain.com to a testsite www.mytestsite.com on the same server. I did it this way:
On productive server:

Set productive site to offline
Disabled Clean URL
Emptied Cache
created backup with the "backup and migrate" tool. All tables are backuped exept all cache-table and watchdog
Copy all files

On target test server:

Create new empty DB
Import SQL script via MySQLAdmin from provider
Copy all files
change settings.php
Login as Admin, set online, enable clean url, empty cache

Now I should have an identical site. But I have two differences (maybe more, which I cannot see):

XML Sitemap: Takes still the old domain name ("www.mydomain.com"). I can delete it and rebuild, no change. Why? This means that somewhere in a file the domain name must be written
The colors of hyperlinks are blue instead green as in the original site. When I go to "Theme settings" and simply press "save", then all is ok. Also here: Why is there wrong information about theme settings? Is this not saved in the DB?

Any help appreciated, thanks

Go to admin/config/search/xmlsitemap/settings and set the correct domain. If that does not work look at your variable table in database and make sure xmlsitemap_base_url is correct.
Make sure your folder permissions are correct. If you have caching enabled and some themes need to write temp files inside sites/default/files so make sure permissions are correct and that Drupal can write there.

If that does not work can you inspect where the styles are coming from using Firebug and also post what theme you are using and I can update my answer.


Set the value of a hidden field in form block Using the code below in a block, I am displaying a form in a block on all pages for a content type called Goals. I want to use this block / form to update progress on the goal to a content type called Goal Progress, and connect the two through a key called goal_id - the nid of the Goal.

The challenge that I am having is setting the value for the goal_id field (Goal Progress content type). I suspect I need to use $form_state['values']['field_goal_id']['und']['0']['value'] = 'value'; to declare the value, but I can't figure out where that should be placed.

Been looking for a solution for a couple of hours now, so any suggestions are greatly appreciated.

<?php
  $node = menu_get_object();

  if (isset($node->nid)) {
    $nid = $node->nid;
  }

  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('goal_progress');
  print drupal_render($node_form);
?>

OK, I have found a working solution. I added $form['field_goal_id']['und']['0']['value']['#value'] = $node->nid; to hook_form_alter in template.php, and the value is populating the field and the form is submitting successfully. Sweet!


Error installing any module I have an error in my Drupal 7 site when I try to install any module.

If I try the Install from a URL I get:

  HTTP error 0 occurred when trying to fetch http://ftp.drupal.org/files/projects/google_analytics-7.x-1.3.tar.gz.

  Unable to retrieve Drupal project from http://ftp.drupal.org/files/projects/google_analytics-7.x-1.3.tar.gz.

If I try Upload a module or theme archive to install I get:

  An AJAX HTTP request terminated abnormally. Debugging information follows. Path: StatusText: ResponseText: ReadyState: 4

The error page shows me:

  Notice: Undefined index: log in update_authorize_install_batch_finished() (line 235 of V:\www\site\modules\update\update.authorize.inc).
  Warning: Invalid argument supplied for foreach() in update_authorize_install_batch_finished() (line 235 of V:\www\site\modules\update\update.authorize.inc).
  Notice: Undefined index: log in update_authorize_install_batch_finished() (line 276 of V:\www\site\modules\update\update.authorize.inc).
  Notice: Undefined index: tasks in update_authorize_install_batch_finished() (line 277 of V:\www\site\modules\update\update.authorize.inc).
  Installation failed! See the log below for more information.

Any ideas on how I can troubleshoot this?

This looks like a ownership / permissions problem on a Linux server. Make sure to set the ownership of the drupal root folder and underlying files to the webserver's user (like 'apache', for example).

Also, make sure that the "temporary" and the "private" folders are setup correctly and with the right permissions (if in doubt, just test with 777 - don't forget to lower them to your requirements afterwards).


Events calendar & time When working with an Event content type and creating an Events Calendar using views, is it best to keep the date and time separate or together? I was thinking of having them separately, but there is no Time field type, and if I select the content type of Date for the Time only, it messes things up, in a sense that it also requires a date, which conflicts with my Date Field. :S

The reason why I want to separate the Date from Time is because I only want the time to displayed in the calendar view.

Any tips would be greatly appreciated.

Drupal 7?

Use admin/config/regional/date-time/formats and create a new Date/Time format that only outputs the time. Then in your view set the field display to use that format by selecting  "date and time" under "formatter." Now select your newly created format under "choose how users view dates and times."

I think that is the same in D6 as well or at least similar.


CKeditor not working for users only in forums I Installed CKeditor in drupal 7, and all works fine, except in the forums. If I enter as an administrator, there CKeditor works just fine (in the administrator overlay) but if I log as a standard user CKeditor works in all areas but the forums, where I get the following error: TypeError: $(...).get(...) is undefined as in the following line of code: $("#node-form").get(0).setAttribute('action', '/?q=node/add/forum/0&29e0_name=0a'+v+'8f52a260a1342d3127_form');

I'm out of ideas and the solutions offered here are usually for CK editor not working in general, but here the frustration is that it only doesn't work in the forums section and only for standard users.

thanks in advance

This looks like a javascript error. Have you tried installing the jquery_update module and evaluating what javascript libraries or drupal modules making use of Javascript are installed on the website and looking for conflicts between the modules.

What javascript file is producing the error. Using Chrome Developer Tools or Firebug for firefox and looking at the Console will give you the filename.


hook_pathauto_alias_alter() on bulk update EDIT: I've found out that this question doesn't make sense.
The problem isn't that the hook is not called during the bulk_update.
The problem is that the code generates unexpected aliases because of the "variable_set" request, which led me to think that the hook wasn't called.
See my answer for the correct code to programmatically set alias patterns.

I have created a function to alter the alias for a particular content type when certain conditions are met, using the following code:

function HOOK_pathauto_alias_alter(&$alias, array &$context) {

   if(isset($context['data']['node']->field_myfield['und']))
       variable_set('pathauto_node_contentype_pattern', 'something/[node:title]');
}

The problem is, when I create a node and save it, it works, but when i try to bulk update the aliases, it doesn't, and the default pattern set from the GUI is used instead.

Issue can be with the setting for Url aliases, when  you run the bulk update.
You need to keep it on the " Create a new alias. Delete the old alias. ". SO it will run update your old aliases. Please check if it works for you.


Access Individual Fields - Contact Form - Swiftmailer So I followed the steps here https://drupal.stackexchange.com/a/199464/49661 to configure Drupal 8 to send contact form emails via Swiftmailer.

I created a template in my theme's template directory, swiftmailer.html.twig, which the emails do seem to be using. The issue is, I only seem to have access to all the fields at once using {{ body }}. This just spits all the field values out in one, giant mess. Random spacing everywhere, random new lines, some fields with labels, some without.

Ideally, I'd like to be able to access individual field values so I can template it. For example:

Full Name:
{{ fields.full_name.content }}

I've tried kinting a few variables out, but all body contains is the cluster of every field value together.

I've also tried creating more variables using [yourtheme]_swiftmailer_preprocess(&$variables) after reading very little documenation available here https://www.drupal.org/node/1590184. This doesn't even seem to be ran when a contact form submission is made.

Here's what it looks like when I kint out body|raw:

Thanks for any help in advance

This definitely isn't a very nice solution, but it does "work".

I created a module, and added this into the .module file.

function modulename_mail_alter(&$message)
{
  if(empty($message['params']['contact_message'])) {
    return false;
  }

  //$message['body'][1] = str_replace("\n\n\n\n",'',$message['body'][1]);
  //$message['body'][1] = str_replace('   ','',$message['body'][1]);
  $contactMessage = $message['params']['contact_message'];

  // Build message body
  //$message['body'][0] = [];
  $message['body'][1] = [];
  $message['body'][1] = "

";

  if($contactMessage->hasfield('field_your_name')) {
    $message['body'][1] .= "

Full Name:
";
    $message['body'][1] .= $contactMessage->get('field_your_name')->getString() . "

";
  }

  if($contactMessage->hasField('field_email_address')) {
    $message['body'][1] .= "Email Address:
";
    $message['body'][1] .= $contactMessage->get('field_email_address')->getString() . "

";
  }

  if($contactMessage->hasField('field_telephone')) {
    $message['body'][1] .= "Telephone:
";
    $message['body'][1] .= $contactMessage->get('field_telephone')->getString() . "

";
  }

  if($contactMessage->hasField('field_mobile')) {
    $message['body'][1] .= "Mobile:
";
    $message['body'][1] .= $contactMessage->get('field_mobile')->getString() . "

";
  }

  if($contactMessage->hasField('field_company')) {
    $message['body'][1] .= "Company:
";
    $message['body'][1] .= $contactMessage->get('field_company')->getString() . "

";
  }

  if($contactMessage->hasField('field_enquiry_type')) {
    $message['body'][1] .= "Enquiry Type:
";
    $message['body'][1] .= $contactMessage->get('field_enquiry_type')->getString() . "

";
  }

  if($contactMessage->hasField('field_version')) {
    $message['body'][1] .= "Version:
";
    $message['body'][1] .= $contactMessage->get('field_version')->getString() . "

";
  }

  if($contactMessage->hasField('message')) {
    $message['body'][1] .= "Message:
";
    $message['body'][1] .= $contactMessage->get('message')->getString() . "

";
  }
}

So basically I clear the message, and then build it up again...


Undefined property in a Views PHP field I need to have a field with user's picture URL. I'm trying to build it with a Views PHP field.

The field's value is defined

$account = user_load($row->uid);
$uri = $account->picture->uri;
$url = image_style_url('avatar', $uri);
return $url;

It returns value I expect, but returns also a warning

  Notice: Trying to get property of non-object in __lambda_func() (line 2 of /home/testwww/web/informator/sites/all/modules/views_php/plugins/views/views_php_handler_field.inc (131): runtime-created function).

Do you have any idea on how to solve the issue or what exactly is the cause?

From what I've found out:

it seems that the notice concerns uri attribute of $account->picture..
The result of print_r($account->picture) is

        stdClass Object
        (
            [fid] => 168
            [uid] => 58
            [filename] => picture-58-1310836862.jpg
            [uri] => public://portrait/picture-58-1310836862.jpg
            [filemime] => image/jpeg
            [filesize] => 49505
            [status] => 1
            [timestamp] => 1310836862
            [rdf_mapping] => Array
                (
                )
        )

Users who have not uploaded a picture (also the anonymous user) will not have any object set for $account->picture. You just need to check that there is an object available:

$uri = isset($account->picture->uri) ? $account->picture->uri : NULL;

image_style_url() will return a bogus URI when passed NULL. You'll want to handle this somehow.

Note:
The user picture is already available as a field, you don't need PHP to get it.

In views 3, you must first add the "Content: Author" relationship before the User fields (including one for the user picture) will show up.


Error is raised when I try to redirect webform submission to external webpage with query string Dear Drupal community,

I created a webform using the webforms module in Drupal 8 in order to add information to a webpage. Since I don't want to update the webpage manually I'd like to automatize this process by redirecting the information entered in the webform to a cgi script which then takes care of the rest (The target webpage is not based on drupal). So I used the [webform_submission:values:<>] tokens and added them in the query string of the external url. In principle it works, but I noticed that for some fields in the webform entries spaces and special characters like " and ' are possible. In these cases I get an error message that the confirmation URL is not valid. I attached a .png. At the blue line you see a space, this seems to be what causes the problem. But if I enter the url manually in the browser my cgi script works as expected. So I only need to prevent drupal from stopping the redirect.

I appreciate any help.

best regards

ps. I created the same post over at the drupal.org forum. Strangely though, I don't see my post appearing at the forum.

pps. While the approach with the query string is probably an unsafe approach it's alright for my purpose since everything happens in an password protected internal area.

I think there's an easier way to achieve what you want.

In you webform go to "Settings > Form" then you'll see near the bottom "Custom settings" with a dropdown for "method". There you can change it to "GET (Custom)" then enter the url for your third party site.

If you needed the get variable names to be something specific you might need to remake your fields with the right key to match your get variable names you need.

But that should do the trick and it will take care or encoding any special characters for you


How to programmatically delete a display from a view Is it possible to programmatically delete a display from a view?

The view object has numerous member functions related to displays (add_display, attach_displays, choose_display, set_display, new_display, etc.) and I can also disable a display like this:

<?php
  $view_name = "faq";
  $display_name = "page_1";
  $view = views_get_view($view_name);
  $view->display[$display_name]->display_options['enabled'] = FALSE;
  views_save_view($view);
?>

But I can't see how I can remove the display completely. Can anyone advise? Thanks!

This is how you do it. It is how it is done in views_ui_edit_view_form_submit() when you delete a display via the admin UI:

unset($view->display[$display_name]);


How to setup external CSS and JS to prevent render-blocking from Google PageSpeed? We are using Google's PageSpeed to help optimize the site. A couple constant issues that come up include render blocking CSS and JS. We have tried the following in our libraries.xml file, but cannot find the appropriate way to do this in D8.

We have found this to be an issue with our local aggregated CSS files that come from our theme and with external CSS and JS

We have tried:

AddAgg module but that still does not solve the issue as we still get render blocking CSS and JS
code below is what we have tried with and without preprocess = false. setting the attributes to async: true does not load the page properly so we using defer: true
We also tried moving the css-placeholder and js-placeholder from our html.html.twig file to the bottom of the page but that has side effects.

mytheme.libraries.yml

fonts:
  css:
    theme:
      //fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i: { type: external, preprocess: false, minified: true }
      //maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css: { type: external, preprocess: false, minified: true }

slick_carousel:
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css: {type: external,preprocess: false, minified: true}
  js:
    //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js: { type: external, preprocess: false, minified: true, attributes: { defer: true }}

What is the proper way to add external and local CSS and JS without render-blocking?

Defer for JavaScript is how to do js. CSS is a lot harder. You need to generate critical css and inline it and then still load the CSS in a deferred way. This explains how to do so with the 7.x version of AdvAgg; the 8.x version shouldn't be that far off.

https://groups.drupal.org/node/517292

Font's are their own special thing, the advagg relocate sub module handles the browser cache part, the advagg font module makes font loading async.

This is the easiest site to use to generate critical css
https://www.sitelocity.com/critical-path-css-generator but it might not give the best results.


How to insert a text field inside boolean (single on/off) field in node form I have created a a content type and I am using it as a registration form to be created by anonymous users.

When I create a field with type of boolean> single on/off checkbox
for my terms and conditions (where it will display the terms and they will be required to check the single checkbox if they agree).

My problem is i want to add another text field for this particular field type in node form for me to put in the text for terms and conditions.

There is a help text box there which i can use, but i used it to display tooltips.

What is the best way to add another text field to boolean type field in node form?

You could implement hook_form_alter() and add a suffix or prefix to your field. The suffix and prefix may contain html.

    $form['terms'] = array(
      '#prefix' => '
Something before the field
',
      '#suffix' => '
Something after the field
',
    );

For a detailed instruction how to write a module that implements hook form alter see this blog post.

There is also a module that can add markup widgets to forms. Checkout Markup.


How to know if i click any link in drupal and set a variable? I need some help for the following case:

In my content-type i have a cck link that redirect to another page.
So, i need do this:

When, i click in the link.. In my content-type_form ([name_content_type]_node_form) i need to extract a variable of this form of my node:

form_state['values']['id'] = $id;
variable_set($id, 1);

Then, when i stay in the another page (that is a form) ; in this form do:

$form['id'] = array(
        '#type' => 'textfield',
        '#default_value' => variable_get($id, 1)
);

for view the corresponding id.

How to do this?

As I understand it, you need to pass a value via the URL, and fix a forms element based on this.

You have to output a link ith your variable in it, in the form yoursite.com?variable=value, preferably via the l() function.

On your second page, the value will be accessible in several ways, for example in the $_GET variable.

More powerfull and Drupalish, you could also implement a hook_menu to be able to use clean URLs like yoursite.com/some_menu_entry/yourvalue and the corresponding function.


Region and language selection in URL Is it possible in Drupal?

I'm developing a website in multilingual. It contains region (country name E.g USA, German, french....) and language (English, French, Japan....) selection.

When user select the region it brings in URL.

Eg: http://www.example.com/us[region-name]/en[language-name]

For single region, we can select many language

Eg: http://www.example.com/us[region-name]/jp[language-name] or http://www.example.com/us[region-name]/fr[language-name]

I achieve this by using Purl with help of mytheme_url_outbound_alter()


User Avatars on My Relationships: friends Block I have read several tutorials about doing this through views but I was wondering if it is possible to modify the block created out of the box by user relationships without having to create a view.

Am using the following version for the module;
-UR 7.x-1.0-alpha4

Copy /user_relationships/user_relationship_blocks/templates/user_relationships-block.tpl.php to your custom theme's directory and you can make any modifications you want from there.

Make sure NOT to edit that in place. You don't want to end up in a situation where your modifications are scattered all over different module folders.


Print {{ node.body.value }} in node--content-type.twig missing figure and figcaption tag of image My code in node--content-type.html.twig is the following.

{% autoescape false %}
  {{ node.body.value }}
{% endautoescape %}

In my node there are images, centered and with a caption, but when I view the node detail, the images are not centered because of missing figure and figcaption tags.

How can fix it?

This is my code to corrected it:

<p>{{ content|without('body') }}</p> <!--Other fields in Full content mode-->
{{ content.body }} <!--This is body field. Don't forget config show it in Full content mode-->

If someone has a better solution please help me! Sorry my English not good.


How to use different entity info per entity bundle? I have three specific vocabularies that reside on different URIs and I need to have the Field UI configuration available for those URIs instead of only at one specific URI.

How could I configure this? The entity info is cached so alteration would not yeald the required result.

Bundle info only allows altering the label and some other unimportant value at this time.

This should basically act just like the entity uri override done by Forum module(although I think this is still not implemented yet).

Edit:
As I have mentioned I have three vocabularies A, B and C. I have three routes for each of those vocabularies and in there I am calling the Drupal\taxonomy\Form\OverviewTerms form with vocabulary argument which is the name of the vocabualry that I want to display.

This gives me the vocabulary term list overivew. Now I want to add the vocabualry edit form as local task on those paths which I still can do(manually).

The issue is that I would also like to have the Field UI(ie. manage fields, manage form display, manage display) available at those routes/paths. And this is problematic since the field ui route is defined in the vocabulary entity annotation and is universal for all vocabularies.

The only way I think I can do this is by somehow duplicating what \Drupal\field_ui\Plugin\Derivative\FieldUiLocalTask does but I was hoping for more simpler way by just having a different per-bundle information.

For more context/information see https://www.drupal.org/node/2460207

I don't really understand what you are asking, but it's not possibly to have different entity type definitions per bundle. The only exeption is the uri callback, that forum.module is using, as you mentioned yourself.

As I said, I don't understand/you don't explain what you're actually trying to achieve. Try to explain that, maybe there's a way to achieve your goal, just not in the way you imagined it.


How can I add color to drush output? I'm writing a drush command, and outputting the results in table format. Everything works fine, the command runs, the output is displayed where it should be. However, there is one column where I am putting "Ok", "Warning", "Error" and I would like to be able to add color to that (the way drush does for its own commands). Yet I have looked everywhere without success to find instructions about how to do it, and would welcome some pointers.

In Drush 8 you may access Symfony Console output object directly.

<?php

/**
 * @file
 * Contains example drush command.
 */

use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Implements hook_drush_command().
 */
function MODULENAME_drush_command() {
  $items['example'] = [
    'description' => 'Command description.',
  ];
  return $items;
}

/**
 * Callback function for example command.
 *
 * @see http://symfony.com/doc/current/console/coloring.html#using-color-styles
 */
function drush_MODULENAME_example() {
  $output = new ConsoleOutput();
  $output->writeln('<info>Green text</info>');
  $output->writeln('<comment>Yellow text</comment>');
  $output->writeln('<question>Black text on a cyan background</question>');
  $output->writeln('<error>White text on a red background</error>');
}


Create entity view block I have 2 content types: schools and courses.

On the schools content type, I created a field called 'Courses At This School' which is an entity reference field to the courses content type.

So, I edit a school and then I can add which courses the schools runs based on nodes I created on courses.

I now need to create a block view but cannot get my head around how to do this. This block will be placed on the schools node pages and will show which courses the schools run so I'll need a contextual filter too.

I have tried playing around with this but I am getting nowhere. Do I create a view and filter by courses or schools?

Please follow the below steps. You will achieve what you have asked.

1. Go to Structures > Views > Add a New View (named Courses)> Select Type as Courses > Create a Block

2. Enter the Block Title as Courses > Continue and Edit

3.  Under the Advanced > Add Relationships search for Entity Reference: Referencing entity (select the same field which was referenced under school content type) and click on apply

4. Under contextual filter > Search and select Content: Nid and in relationship option select the relationship and under WHEN THE FILTER VALUE IS NOT AVAILABLE
 select as  Provide default value > Content id from URL > Click on apply

5.  And under format or Fields, you can select anything depending on how you want to display the data


How to add a no result text in Views? I am using D7 and views for one of my sites. In views I am using contextual filters to get the result based on the url arguments. My question how to display a text like "No results found" in the views if I don get any match based on the url.

It's under 'Advanced' on the right hand side. Then 'add' a NO RESULTS BEHAVIOUR.


Static html page import I want to import static html reports generated for source code by code analysis tools like doxygen, understand. Is there any module that can import the html reports generated by these tools directly into drupal? I tried import html without any success. Any tried and tested procedure to achieve this feature ?

You can do it with the built-in text filter named "PHP Code".  To get access to this, you need to first enable the core PHP Filter module (in core, but disabled by default).  Then navigate to Home » Administration » Configuration » Content authoring  » Text formats and allow the Administrator to use the filter named "PHP code".

Now the Administrator can create nodes that use the PHP include statement to embed static HTML pages in Drupal nodes. For example, to import a static HTML page located in the Drupal root named static.html, create a Basic page node with this contents:

<?php include $_SERVER['DOCUMENT_ROOT'] . '/static.html'; ?>

and set its text format to "PHP Filter".

Note that the "PHP code" text filter allows arbitary PHP to be embedded into nodes, so make sure that only highly trusted users have access to this filter.


Programmatically add a views I'm writing a little module which should simplify creating a new view proccess for my site manager. What I want to do is to create a form, where the editor can fill some options (like title, path, some specific values for filtering etc) and then my code has to insert those options in my view template and import it to the database like a noraml view created via UI.

But as I understood, hook_views_default_value just loads the ready view item which is conteined in the module. But i want to create a new one each time with the same template. How can i do this?

Will be very appreciated for any advice.

I would suggest You to check views export functionality (admin/structure/views/view/name-of-some-view/export). There you should get the view object.

Then, copy this object to your form_submit function, replace desired values with form values and call $view->save() function. The view should be created (or updated, if such machine name exist.)


Change page.tpl template inside a hook_menu callback I have a hook_menu like that:

function mymodule_menu() {
    $items['mymodule-test'] = array(
        'page callback' => '_mymodule_test_callback',
        'access callback' => TRUE
    );
    return $items;
}

and the callback function:

function _mymodule_test_callback()
{
    // processing
    return $html;
}

I googled around but i cant find how to force the page template inside my _mymodule_test_callback function.

Edit: why i cant (or dont feel comfortable with) url-based suggestion

Url-based suggestion are easy to implement, however they can not completely fit my needs.

The template I have to use is determined in the _mymodule_test_callback function, according to very various aspects, for example:

Does exists a node of type 'foo', and does the field 'abc' value's be 'xyx'? => choose template 'page-mymodule-foo.tpl.php'
The node does exists, but the field 'abc' value is empty? => Choose temlate 'page-mymodule-bar.tpl.php'
The node does not exist at all, but the user has the 'bimbumbam' role? => Choose template 'page-mymodule-foobarz.tpl.php'

...and so on.

I know this is a rare behavior, and that i could redirect instead of switching template, but actually the function body is not big and i prefer to do this way.

Is not possible?

You cannot directly change the page template from a page callback. You can either bypass the full page rendering by printing your page content from your page callback. Or you can use a global variable to trigger addition of template suggestion in hook_preprocess_HOOK implementation.

function _no_template_page_callback() {
  // ... processing ...
  // Print the result, and bypass the page template (so no blocks, no CSS, no JavaScript, etc.).
  print $html;
}

function _template_suggestions_callback() {
  global $MODULE_page_template_suggestions;
  // ... processing ...
  // Set flag to trigger usage of our custom page template.
  $MODULE_suggest_page_template = $suggestions;
  return $html;
}

function MODULE_preprocess_page(&$variables) {
  global $MODULE_page_template_suggestions;
  if (!empty($MODULE_page_template_suggestions)) {
    // Use template suggestions set from _template_suggestions_callback the module.
    foreach ($MODULE_page_template_suggestions as $suggestion) {
      $variables['template_files'][] = $suggestion;
    }
  }
}


drupal 7 SSL a lot of insecure urls My site is now using a SSL certificate but i have about 300k pages with insecure urls (http) - What is the best and most efficient way of fixing this problem?

The problem is the dynamic content is referencing HTTP content. The site is already forcing SSL.

One solution, if you're wanting to force your site to always to use SSL, is to do it at the Apache level by adding this to your .htaccess:

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

That's probably the quickest way. The best way is subjective; your needs might be different depending on priorities (e.g. for performance reasons you might want to force many static pages to HTTP).


Custom button for CKEditor not showing up in node creation page I want to add a simple custom button to CKEditor in Drupal 8. So far I followed the Instructions here and here, and my custom button is showing up on the configuration page under Configuration > Content authoring > Text formats and editors, where I added it to the Basic HTML and Full HTML presets.

However, when I want to create a new article, the button is not being shown in the editor toolbar.

I can verify by JS console outputs that my plugin is being loaded by CKEditor, and the init function actually runs. The button just does not appear. I appreciate any pointers. I have seen this question, where somebody seems to have a similar problem, but I don't really understand the accepted answer as it seems to be specific to CKEditor templates. So my question is: why does my button show up in the configuration page, but not in the node creation page, although the corresponding JS is being run?

I have not implemented any hooks in my module.

info.yml of my module

name: Glossarion
type: module
description: >
  Some description. I'll think about it later.
core: 8.x
version: 0.1
package: CKEditor
dependencies:
  -ckeditor

.php of my Drupal plugin

class Glossarion extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

public function getDependencies(Editor $editor) { return array(); }
public function getLibraries(Editor $editor) { return array(); }
public function isInternal() { return FALSE; }
public function getConfig(Editor $editor) { return array(); }
public function isEnabled(Editor $editor) { return TRUE; }

public function getFile() {
  return drupal_get_path('module', 'glossarion') . '/js/plugins/glossarion/plugin.js';
}

public function getButtons() {
  return [
    'glossarion' => [
      'label' => t('Insert a Word from Glossarion'),
      'image' => drupal_get_path('module', 'glossarion') . '/js/plugins/glossarion/icons/glossarion-editor-icon.png',
      'command' => 'insertTimestamp'
    ]
  ];
}
}

.js of my CKEditor Plugin

'use strict';

CKEDITOR.plugins.add('glossarion',{
  icons: 'glossarion-editor-icon', // %REMOVE_LINE_CORE%
  init : function( editor ) {
    console.log("Glossarion init is being called");
    editor.addCommand( 'insertTimestamp', {
        exec: function( editor ) {
            var now = new Date();
            editor.insertHtml( 'The current date and time is: <em>' + now.toString() + '</em>' );
        }
    });
    // do I have to add the button here again? Seems to have no effect
    editor.ui.addButton( 'Timestamp', {
        label: 'Insert Timestamp',
        command: 'insertTimestamp',
        toolbar: 'basicstyles,0'
    });
    console.debug(editor);
  }
});

See the documentation at https://www.drupal.org/developing/api/8/ckeditor.

You can find examples in Drupal 8 core, at:

\Drupal\ckeditor_test\Plugin\CKEditorPlugin\Llama
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaButton
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextual
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextualAndButton

(This is the exact same answer as I gave at https://drupal.stackexchange.com/a/191869/7632.)

To answer specifically why the button is not showing: CKEditor's Advanced Content Filter (ACF).

Please add your button to CKEditor in the "Full HTML" text format. Check if it shows up then. Chances are it does.

Your plugin does not specify ACF metadata. ACF is what ensures CKEditor produces clean markup. In "Full HTML", there are no restrictions, and no guarantees of clean markup.


Multilanguage Website I'm trying to run some script from Pinterest, to validate my site.

What's happenning is I need to write in Pinterest the url of my site, but my site redirects always like this : "XXX.com/es". How can I avoid that for this test made it by Pinterest.

I also can include on HTML file given by Pinterest but that would be the same, since again my website adds the language (=es) at the end of the path.

I'm pretty sure your question is about a "multilingual" site, and not really about "multi sites". Consider editing your question (title, tags, etc) accordingly.

Moreover, your question is a variation of these types of questions, and that your issue is actually caused by a language detection issue (something you have not yet configured correctly in your site. Consider updating your question as appropriate. After doing so, I can also update my answer here, to actually pinpoint what kind of admin changes you might have to apply to achieve the desired result.

Based on the info provided in your question for now, I wonder what the DEFAULT language is that you specified within /admin/config/regional/language of your site. Could it be that it is "es"? If so, and if you also have enabled the "en" language, then change that default to "en" and retry again. Eventually, change the default language back afterwards, to whatever it was before (whenever your Pinterest script no longer requires you to (temporary) change that default language).

You may also want to check your configuration at Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


How to alter OpenLayers map settings? I'm writing a module that will alter map zoom level and map center based on argument from url. But I cant figure out how the hook_openlayers_map_alter(&$map = array()) works, I'v tried to test this hook with:

function openlayers_mapalter_openlayers_map_alter(&$map = array()) {

    $map->center['initial']['zoom'] = '1';

}

but it has no effect on maps. What is the proper way to call this hook?

have you tried using drupal_message to make sure it's being called?

Or calling the hook_openlayers_map_alter() function and using map as an array like so:

function hook_openlayers_map_alter(&$map = array()) {
    $map['center'] => array( 'lat' => '0',
                             'lon' => '0',
                             'zoom' => '2'
                           );

}


How to access current amount of earned userpoints in a Rules Condition? I have no access from Rules to [points] field or any userpoints field (User points module).

I have enabled: Rules, Rules scheduled, Rules_ui, Userpoints, Userponints_rules_integration, Userpoints_role (from userpoints_contrib),

I have done un/installed several times one by one modules mentioned with clear cache and cron in between and nothing, no access to userponits fields.

My event is "before saving content", in the Rules Conditions I have "User has a role-->auth-user", also in Rules Conditions I have "content is of type-->My custom contentype" in that order (I have changed that order with no results).

I need to update userponits field value before (preferred) or after a node is saved.

I tried also via Rules Components with an element "User has a role-->auth-user", same thing: no access to Userpoints fields.

I have another rule applied and reacting on Rules Event: “After saving a new user account” and there YES I have access to those fields.

Any ideas? Reference module? Do I have to implement a hook in template file to load current user? Do I need a custom module? I've seen all the node.one screencasts about Rules several times. And I have read many post in here, and (think) I’ve done everything right, but no success.

Any suggestions?

In case that your suggestions are: hook or module (I’m not a skilled programmer) please submit some code within.

There doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


How to create a default image per taxonomy term? I want to associate a different default image with each taxonomy term.

I saw this module - https://www.drupal.org/project/taxonomy_image - but it's in alpha.

Anyone got any recommendations how to do this?

Many thanks!

When creating a vocabulary you can add a image field this is the only way to add a default image for all future taxonomy terms (in that vocab)
so then when you create the term you would simply add your image to that term be it "default" or other.


AJAX doesn't work for "flag" field print in node.tpl In node.tpl I use this code:

<?php print flag_create_link('prova', $node->nid); ?>

Flag links work fine, but JavaScript toggle not. The flag link doesn't change to "Unflag link" after click.
Any idea?

Why put me on hold? What's not clear about that?

Update

At moment I solved with views. Set view full content node and set "Ajax" and "Flag refresh" under Other settings of views.
In original node view the problem remains.

It might be too late to add the required JS in the node template.
Try adding your flag link to hook_preprocess_node in template.php instead.

e.g

function MYTHEME_preprocess_node(&$vars){
  $vars['flag_link'] = flag_create_link('prova', $vars['node']->nid);
}

then in your node template

<?php print $flag_link; ?>


Webform - User to edit submission (admin can close) I have a webform that a authenticated user can submit. Where is the page for the authenticated user to re-edited their submission? I can't find it?

I also want to extend a another function. I want to have the ability to close a submission (so the authenticated user) can't re-edit it anymore.

Any suggestions?

Thank you,

You have to view your submission and click on edit to update. Remember you can only edit your own submission.


Entity form with pre-populated entity reference from URL I have two entities which are in a parent/child relationship. Now I want to add a operations link in the parent's list view so that I can show the child's entity form with the reference to the parent pre-populated.

Ideally, the URL would look something like /admin/myparent/123/mychild/add, where 123 is the ID of the parent entity to which the new child should have a reference. I have the link in place in the operations menu, but I can't figure out how to have my ChildEntityForm load in the parent entity based on the URL parameter. How do I do this in Drupal 8?

I found a couple of questions regarding this here on SO, but they were all about Drupal 7. In addition, the documentation (Using parameters in routes) regarding upcasting url parameters states this:

  Note that this method of providing the entity data to a form is not used for entity forms, such as forms to add/edit/delete entity data.

So is there a solution to this, preferably one that would not require installing a third-party module?

The prepopulate module is now able to handle this in the usual way like

http://www.example.com/node/add/child?edit[field_parent_ref]=17


How to re-activate the Drupal administrator account that got accidently blocked? The admin user account of my Drupal site accidently got deactivated. Because of that, I have no more access to Drupal administration.

How can I change the status of that user account to active again?

Open the users table and in the admin row, check the status column. 0 means blocked and 1 means active. Make sure it is set to 1.


How can I extract and print specific field values from $page['content'] in page.tpl.php (vocabulary page) I am trying to print some specific fields on a vocabulary term page in order to lay the page the way I want. <?php print render($page['content']); ?> prints the entire content but I want to extract specific values like title, field_photo etc. so that I can put them where and the way I want!

Here is an example how I want this to work:

I am creating a movie database website where each movie has casting associated with it. Each casting (actor or actress) is a vocabulary term. When I click on a term it takes me to a page (example URL: http://localhost/moviedb/tags/kate-winslet) where movies associated with that actor/actress are listed. The list is coming fine but I want to customize the look-n-feel of this page.

I overrode page.tpl with page--vocabulary--tags.tpl.php. Also I created a template.php file and written this function inside:

function introduction_preprocess_page(&$vars) {
     $vars['temp_var'] = $vars['page']['content'];
}

which is equivalent of using $page['content'] directly inside .tpl file. I also used

<?php print var_export(get_defined_vars(),TRUE) ?>
 to get a the nested structure of nodes array. Based on that I tried to access a specific field like <?php print render $temp_var['title'] ?>, nothing is showing up.

I am definitely doing something wrong, but don't know where to check and what to change! I have started learning Drupal just a few weeks back.

UPDATE

I also tried the following code but no luck yet.

function introduction_preprocess_page(&$variables) {
   if (arg(0) == 'node') {
      $variables['node_content'] =& $variables['page']['content']['system_main']['nodes'][arg(1)];
   }
}

INTRODUCTION is the name of my theme.

In .tpl file I tried to access title the following way:

if (isset($node_content) && $node_content['title']) {
    print render($node_content['title']);
}

I have referred the following URLs:

https://www.drupal.org/node/2288941 and https://www.drupal.org/node/223430

Please help me understand what wrong I have done.

EDIT (27.05.2016)

I tried the solution but it did not work. By doing some trial and error I noticed that my node--film.tpl.php template is actually being used even on taxonomy page. In my application film is a content type I created and there is a field called "cast" which is eventually a vocabulary called "tags". I am putting names of actors by using this vocabulary when adding a "film" type content.

My intention was to show a list of films where an actor is associated when a tag (actor) is clicked. The functionality works OK but I don't understand why this page is also using node--film.tpl.php template file and not taxonomy-term.tpl.php. I copied taxonomy-term.tpl.php to my theme folder, took out the line which is rendering the content, cleared cached but nothing happened. But when I take out the same code snippet from my node--film.tpl.php file, the content disappears! Which confirms that node--film.tpl.php is the template being used!

I then renamed the file as taxonomy-term--vocabulary-tags.tpl.php just as a random test, but nothing changed either!

I am still unable to customize the look-n-feel and field display in my vocabulary page.

There are a few things here:

Taxonomy term pages are not nodes, and on a taxonomy term page you are going to have the following args:

arg(0) ~ taxonomy
arg(1) ~ term
arg(2) ~ tid (taxonomy term ID)

To override term pages copy site_root/modules/taxonomy/taxonomy-term.tpl.php into your theme templates folder to override all taxonomy term pages. You will also find really helpful instructions in that template file.


Programmatically add button to block 7 - How do I programmatically create a button, place it in a block, 'weight it' and then make it visible to certain pages?

Code I've tried:

function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  $blocks['openid_connect_register'] = array(
      'info' => t('Register Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => '/user/register',
  );
  return $blocks;
}

This code creates the button but doesn't put it under the content block and doesn't make it only visible on the specified pages.

Why not render in a tpl so you can control the look of it?

I see you already used hook_block_info() so you can complete this using hook_block_view() with a custom callback function to use hook_theme()

Here is a complete example of it:

function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  return $blocks;
}

then:

function openid_connect_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'openid_connect_login':
      $block['content'] = openid_connect_login();
      break;
  return $block;
}

then:

function openid_connect_login() {
  return theme('openid_connect_login_tpl', array('data' => NULL));
}

last thing here:

    function openid_connect_theme($existing, $type, $theme, $path) {
      return array(
        'openid_connect_login_tpl' => array(
          'variables' => array('data' => NULL),
          'template' => 'openid-connect-login',
          'path' => drupal_get_path('module', 'openid_connect') . '/theme',
        ),
);
}

create your file inside you module under the name we gave openid-connect-login.tpl.php and put it in a folder I named theme ..

I hope I understood it right and was helpful for you issue ..


Re-indexing of site stalled, & running cron won't advance I have a site recently moved from D6 to D7. The search in D7 was not finding nodes containing the search terms, so I began a re-index in the search settings. This has stalled at 11% of site (with 3570 items left to index), and running cron does nothing to advance the re-index.

The log messages show that when cron runs, it encounters this error:

  EntityMalformedException: Missing bundle property on entity of type
  comment. in entity_extract_ids() (line 7766 of
  /var/www/html/[domain]/includes/common.inc).

And this notice:

  Notice: Undefined variable: key in comment_prepare_thread() (line 901
  of /var/www/html/[domain]/modules/comment/comment.module).

Also, there are many instances of this notice, which is associated with use of the site, not cron:

  Undefined index: weblinks in custom_search_form_alter() (line 232 of
  /var/www/html/[domain]/sites/all/modules/custom_search/custom_search.module).

None of these seem to affect the function of the site, and it's not clear to me that they are actually related to the stalled re-indexing. But it's all I've got to go on at this point.

If anyone could give me some ideas for how to troubleshoot this, I'd very much appreciate it.

Thanks!

This problem was caused by discussion forum posts with a single comment from a user whose id was no longer in the user table (threads with more than one comment, even though one was from an invalid user id, did not cause the error).

The fix was to find comments with invalid user ids, then change those ids in the Comment table to 0.

This SQL query identified the problem user ids:

SELECT DISTINCT a.uid FROM comment a left join users b on a.uid = b.uid
WHERE b.uid IS NULL

With the problem user ids identified, you can either edit the table directly, or use UPDATE to change the column values.

With those values changed in the comment table, the re-indexing proceeded to 100% without a hitch.


Clone View as attachment I am using Views-7.x-3. I have a master view and many content panes views under it. Recently I have a requirement in which I have to create attachment for one of the content pane view. When I clicked on adding an attachment it cloned the all the formats, fields, filter criteria etc from the master display, which I do not want as I want to have same copy of the my content pane view as an attachment which has many addition fields, context filter as well.

My query: Is there any way to clone desired view as attachment rather re-creating same fields again?

It is possible to clone a View Display (in this case an attachment). For example:

Go to admin/structure/views/view/frontpage on your Drupal site
Select the 'Feed' Display under Displays
Under 'Feed details', notice the 'Display name' field, look all the way to the right of here and you'll notice a 'view Feed' drop down menu, click the 'down' icon
Then click 'clone Feed'

That will cone that particular display, click 'Save' when you're ready to save the changes. For your attachment, follow the steps above and replace the steps with your view, and the name of your attachment.


Trying to filter a View based on a Paragraph entity reference I want to filter a View by content type 'Article' and only content that is referenced to a specific node id 123. I have a Paragraph in Article content type. Inside the Paragraph is an entity reference 'my_field' to content and also a few other text fields. In my View I added a relation: Paragraph referenced from my_paragraph_field. I can now add a normal View field - my_field and use the relation. But it doesn't display results of the field. I can also add a filter - my_field and make it equal to nid '123'. But it doesn't filter on the result? How can I make this work. Is this related to this issue. I can create a new View that displays Paragraphs and I can filter on that reference field without adding a relation.

The way to list nodes that reference the one you're currenty viewing is by adding a Contextual filter for the Entity reference field that connects them.

You have one more connection in between - the Paragraph. You already added the Relationship to it so you're half way there.

Now that you have the 'my_field' available you need to add the Contextual filter for that field. Configure it to Provide default value, Content ID from URL, and set the other options in a way that makes sense in your particular case.

This will give you a Views Display that is sensitive to the context of the node you're currently viewing, and it will show all the other nodes that reference this node through their Paragraphs.

Usually this Views Display is a Block that you then put in a region of your theme to be displayed on Articles only, and don't forget to set the Block contextual option too.

If you're using regular Filters like you mentioned to filter only node 123, the normal fields will display its info, and not the info from the node that refereces node 123. To display "the child" node info that references the filtered node you have to make the fields use the Relationship for it. Either add the 'my_field' Field (it will automatically use the Paragraph Relationship), and if that won't work you need to add another Relationship that introduces that node info into the Views, then you'll be able to add the Title field for example, and make it use the second Relationship to show the node that references the current node.


Add subquery with count, having, and orderby I just started working with Drupal 7 and I'm stuck at something I believe should be really easy (I could easily write it using plain SQL).

I have a query, rather complex (but that's not relevant) which I wanted to extend with hook_views_query_alter. What I need to achieve:

Based on base table users I need to:

Join a table node based on users.uid (many-to-one)
Then join a table node_param on node.id (one-to-one)
select count(node_param.id) WHERE node_param.value is greater than X
Order everything based on that count field

I've done research on Drupal website and stackoverflow, but couldn't find anything that would actually work, everything I've tried ended up with no results at all and I did build the query with SQL that returns results - therefore I believe my altered query gone wrong.

I will really appreciate your help here! :)

P.S. I can only modify this query using this hook!

So, from reading your question, it seems you're missing a fundamental step to data modeling with Drupal. The first thing you're going to want to do is to build out content types and fields for your data. This is done through the content types user interface. Once you have all of your data in node content types and fields, it becomes much easier to access this data in views.

When it comes to creating joins in views, you'll want to use "relationships" under "advanced" on the right hand side of the views UI. Since you're new to Drupal, but not to SQL, you might find it helpful to turn on "Show the SQL Query" here: /admin/structure/views/settings

So, the big realization here is that you don't create custom tables in Drupal databases manually. There are use cases where using a node doesn't make sense. In that case, you'll want to create a custom content entity. This is not done manually in Drupal. While creating entities can be done through code, you're better off using this module to generate your tables:

https://www.drupal.org/project/eck

Finally, most Drupal developers prefer nodes for data storage because Nodes are special entities that have many wonderful features that almost all data in Drupal needs.


How to add Cancel button to Batch operation? How to add Cancel button to Batch operation?
Is this even possible?

There is no good way to interrupt a batch process, afaik. There used to be a hackish trick in Drupal 6 though, see http://drupal.org/node/894222. Maybe if you can figure out how that worked, you can make Drupal 7 do the same.


Customize search result How can i remove Only of the type(s) on the advance options. and username and created day display on the footer search result?

The Custom Search module provides easy control over many of those search options.


Why is the Edit View link not appearing in Panels? I've got a Views block display placed inside a Panels pane.  It works well, and I wanted to add two similar blocks, so I cloned the View and changed the necessary settings. The original block has the cogwheel "Edit View" contextual link, but the clones do not. Any ideas? I can still go to Structure -> Views -> name to edit, but it's much easier to use the contextual link. If anyone knows why it isn't appearing and how to get it back, I'd appreciate it!

I discovered the answer by accident yesterday. When adding a Views block to a Panels pane, Panels will ask you if you want the "Master" or "Block" display. I'm not sure there's a difference in the output at all, but if you select the "Block" display, the contextual cogwheel "Edit View" link will not show up.  If you select "Master", it will.  Unfortunately, you can't change the display once it has been added, so you need to remove the "Block" display and re-add it, selecting the "Master" display.  This could cause you to have to redo some work, if you had spent any time configuring things already.


Suggest linking of content types I have two OG groups - Organizations and E-hoods. and group content types - goals and ideas. I would like users to have a suggest feature which enables people to basically link groups and group content. Also the linking should be moderated.

Is there a module that does this ? or if anyone can give me a direction to work on, I can work on it too. I'm using Drupal 7 and have a limited knowledge on drupal.

Thanks!

You should take a look at References for the linking part, and also Workbench for the moderation part, and lastly Field Permissions to give users access to do the linking.

Create a Node reference field on one content type, to link the child node to the parent (or vice-versa)
Use Field Permissions to grant everyone access to enter/edit the field
Use Workbench to force changes into a new revision which need to be approved.


Why does the Webform disappear after changing Submit button text in Form settings? I have created a Webform page called "Quick Quote".

It is working fine in the website. But when I change the "Submit button text" to a new value in Advance Settings >> Form Setting configuration, then the entire form (i.e Quick Quote page) disappears.

Why does it disappear, and how to enable it?

Difficult to know what's going on based on the limited information you've provided, but it could be permissions. If you don't have permissions to view the webform then you won't see it.

The scenario you've described might occur if you are configuring the webform while logged in, then testing it while logged out (or in another browser) as an anonymous user that does not have permissions to view.


Undefined index: cck_time_field_presave() I have imported about 2 thousand nodes that include start time.

I have imported and the formating and time looks the way it should.

Now if i try to publish the nodes i get following error -

  Notice: Undefined index: hour in cck_time_field_presave() (line 97 of
  public_html/sites/all/modules/cck_time/cck_time.module).

The time fields gets changed to null time.

But if I open the node and save it - the node is saved with the correct time as it was before.

Im at a loss.

And hoping for some guidance.

Go to CCK Time then open cck_time.module

find this:

function cck_time_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items)

change this:

if (($items[0]['hour'] === '') || ($items[0]['minute'] === ''))

to this:

if ( empty($items[0]['hour']) || empty($items[0]['minute']) )

It helped solving my problem getting the same error Undefined index: cck_time_field_presave()


How do I find the role id from role name? On log in I want to check a third party data source (table in the db) for a user, and if found I want to add a role to that user.

I don't want to guess the rid of the role, I want to get it from the role name.

Knowing the machine name of the role, it is enough to use user_role_load_by_name().

if ($role = user_role_load_by_name('Role Name')) {
  // The role ID is in $role->rid.
}

If the Role might not exist...

$role = user_role_load_by_name('Role Name');

$role_id = $role ? $role->rid : NULL;


Add a default value for existing Image alt field I have an image field in article content type and have created hundreds of nodes for article content type, but now I need to add a value for image alt fields for these existing nodes.
Even the default value field for image alt is not showing when I try to edit the field.

How can I add values for the alt attribute of the image field in existing nodes?

Add a node_preprocess function to your theme file. The logic would be to check if the current node has a value in the field for "image alt text", if not then set a default value, else return.

These are not the exact field names but this should get you started on what to look for in your code.

 function MYTHEME_preprocess_article(&$variables) {
      if (!field_image_alt_text->getValue().strlen() = 0 || null ) { set value to something } else {return;}
};


sites/subDomain/libraries doesn't load the library files My website has two sub-domains, I need to install imageFlow library in both of these sub-domains but for some reasons I need to replace default images of imageFlow (I mean slider.png, button_play.png and button_pause.png) library in sub-domian1 with some images and in sub-dmoin2 some other pictures. To do so I created folders sub-domain1/libraries  and sub-domain2/libraries and I copied the modified version of the imageFlow in there. But unfortunately it doesn't work and imageFlow is not loaded. If copy the imageFlow library in sites/all it works well but in this way the same version will loaded for all sites.

I think you would want to keep the imageFlow library itself in the sites/all/libraries folder, then to adjust the images for each site, modify your theme to override the default css and images of the imageFlow library. You could do this by copying the imageflow.css stylesheet into your theme, including it, then modifying it to point to custom images instead of the imageflow default images.

This would be a little bit more standard approach than changing the imageFlow source files.


Specific Content Access only after successfull checkout I'm creating a website where user can buy content & can view that content online.Suppose user buys a book online.Now after user successfully completed the payment process,that book should be added to user account page from where user can access the content page.Just like E-book read online,where user can only read books user purchased.
I'm using Drupal Commerce module.

You can actually accomplish this with no code using the Entity Reference, Content Access, and Access Control List modules. I just implemented this for a client! I added an entity reference field to my product type that I used to point to the node the customer should be granted access to upon successful purchase of that product. I then added a rule when an order is first paid in full that grants access through the access control list to the referenced node.

The trick is to configure your node type used for the premium content so that those nodes are only visible to administrators and then depend on the access control list to grant access to users on an individual basis. One advantage of this, too, is that you could create an "all you can eat" subscription using a user role that may also have access to view any content of that type if you wanted to.

To show a list of content the user has access to on their profile, you can simply create a list of nodes of the specified type, and Views's automatic inclusion of access control on node queries should ensure users only see the nodes in the list they have access to.


How to get XML/JSON data for api.drupal.org? In my earlier question How to get node IDs from drupal.org?, I can get the XML data of a node by going to https://www.drupal.org/api-d7/node/274365.xml where 274365 is the node id of a particular page. In similar way I can access all the node in drupal.org Website.

Now I want the same kind of XML data for a node pages in https://api.drupal.org.

For example what is the XML data page for https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7 ?

I was curious about this, too. Below is a dump of the API in JSON format. Unfortunately I don't think the same is available in XML format, or that the query can be further refined to, say, retrieve only a list of hooks.

URL structure:

api/(project)/full_list/(branch)?limit=M&page=N

https://api.drupal.org/api/drupal/full_list/7?limit=20&page=0

Source: Issue# 2369135: Public API into api.drupal.org?


Kickstart installed nothing? I followed the install directions by deleting all but the /sites folder, copied the files into the drupal dir, deleted the cache but nothing changed except and notice that drupal core needed updating to 7.24, which i did.  What am i missing here?

By considering that you have gone through pre-installation checklist of Commerce Kickstart, following are the steps to install commerce kickstart :

Download Commerce Kickstart.
Extract the Files into root directory.
Installation Screen, welcome.
Requirements Problem Screen.
Setting up the database configuration.
Installation running through.
Site Configuration.
Configure Store Content.
Importing Products.


Views 2 - Embed a View inside Empty Text of another View I want to embed a View (or a display of a View) inside another display of View when these view has no results. I figure out that I can embed a View inside the 'Empty Text' filed. I must say that I can show some php echo "hello world"; using this 'Empty Text' filed, but when I try to embed a View, I can not embed a another View or display of View.

this is one example that I used, but without results:

$viewName = 'test_view';
$display_id = 'page_1';
print views_embed_view($viewName, $display_id);

In D7, Views 3 you can enable "NO RESULTS BEHAVIOR" which is under the "Advanced" tab.  Here you can add "Global: View area" (or just "hello world" as a text area for testing) which will allow you to display a view when there isn't any results.

If you want this is code, you can always export the View after it is configured and see how it was done.


Quick question about filter_xss() If I'm creating nodes programmatically does Drupal deal with filter_xss(), or do I have to add the function to my code?

Sanitization functions, which include filter_xss(), are used when a value is shown as output, not when something is saved in the database.

None of those functions is called when saving a node in the database.

See Writing secure code.

  Use check functions on output to prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into HTML.

  Use check_plain() or theme('placeholder') for plain text.
  Use check_markup() or filter_xss() for markup containing text.
  Use the t() function with @ or % placeholders to construct safe, translatable strings.


How can I set Dkim in phpmailer? I have installed phpmailer module and it works fine.
https://drupal.org/project/phpmailer

But it doesn't seem to have the option for DKIM.
How can I set DKIM for the mails sent by phpmailer?

Support for this it was requested over 2 years ago, and was moved to 7.x-3.x-dev branch, so it will not be possible in phpmailer for Drupal 6. The reason is that Drupal 6 will reach the end of its life soon, when Drupal 8 stable will be released. Thus, it will never be possible to set it in phpmailer for Drupal 6.

Anyway, enabling it at PHP level is a costly procedure. PHP is not really the best language for cryptography. As you can read here, configuring DKIM support at the MTA level makes all your server generated email for a given domain signed by default, and also off-loads the calculation burden to the system that's supposed to be optimized for it.

To make sure there is your MTA involved, you can use SMTP Authentication Support module. As you can see in it's issue queue it does not enable you to force DKIM from Drupal, but at least it ensures your mail server is sending mails, and does not interfere with mailserver's DKIM settings either.


Change default text (-Any-) of select option in Exposed View Filter I am using views exposed filter.

I want to change the text -Any- into something else.
How can I do that (without using jquery/javascript) ?

If you use the Better Exposed Filters module you can do this using the views interface. Changed exposed form style to   'better exposed filters' and adjust the settings

  The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.


How do I show nodes/articles with specific taxonomy on a page? Maybe the title is not appropriate, so please dont hesitate to change it or give suggestions for it.

Here's how our Drupal site is done:

A vocabulary called "PAA".
With this vocabulary there are many terms organized like this:

PAA
  |
  \-- MainTerm01
  |   |
  |   \-- SubTerm01
  |   |
  |   \-- SubTerm02
  |   |
  |   ...
  |
  \-- MainTerm02
      |
      \-- SubTerm03
      |
      \-- SubTerm04
      |
      ...

Then we have tons of articles that are associated with only one MainTermXX and only one SubTermXX (whatever XX is).
Here's what we'd like to do: make a page where we can search for a term (either MainTermXX or SubTermXX) and display all articles that are associated with the term.

My question is: is there a way to do this easily (= is this native in Drupal, just configuration) or will I have some work to do about this?

You can use Views for building the output of the page and filtering according to the search query (that is called "exposed filter" in views).

To get familiar with Views and see all what you can do with them, check out Nodeone library of videos on Vimeo.


How to add back to top using drupal behaviors? I have added the following Drupal behaviors below to my main.js file which is already included in my theme and renders on the page with the correct main.js file. The purpose of this behavior is to scroll the user to the top of the page and it is not working. I cannot even get it to log an alert('clicked'). Need help figure out what i am missing.

main.js

Drupal.behaviors.scrollToTop = {
  attach: function (context, setting) {
    $('#back-to-top', context).on('click', function(){
        alert('clicked'); //does not work
        $('body,html').animate({scrollTop : 0}, 500); //does not work
    });
  }
};

html

div is used to insert up arrow

Try wrapping it:

(function ($) {
    Drupal.behaviors.scrollToTop = {
      attach: function (context, setting) {
        $('#back-to-top', context).on('click', function(){
            $('body,html').animate({scrollTop : 0}, 500);
        });
      }
    };
}(jQuery));

Had the same issue, AFAIK the wrapper is necessary to actually fire the behavior.


How do I get a date selector field in a content entity? I have a content entity in Drupal 8 that generates form for datetime. I just want to show only the date selector in the form, but it shows date and time selectors.

     $fields['start_date'] = BaseFieldDefinition::create('datetime')
            ->setLabel(t('Start date'))
            ->setDescription(t('The date that the survey is started.'))
            ->setRequired(true)
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'type' => 'string',
                'weight' => -4,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'date',
                'weight' => -4,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

How do I show only the date selector?

Your problem is that you are setting the option on the form and not the field.  The datatime field has an option, datetime_type which can be two strings 'date' or 'datetime' (see DateTimeItem), and it defaults to 'datetime'.

So, when you are creating your field, you need to update this setting.  The following should work for you:

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('The date that the survey is started.'))
  ->setSetting('datetime_type', 'date')
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

As a side note, when you are having problems like this, the first place to look is at the class implementing the field that you are using, and then look at the tests that cover that field.  Often, you will find the example code that you need.  In this case, you would look at DateTimeFieldTest and see what that integration test is doing.


Getting image SRC with xpath - Simpletest (WebTestBase) I am developing a Drupal 8 test which will check for a image's existence. The image will not be loaded while running the test and I want to catch that using xpath().

The HTML I am trying to search is,

  blockquote

In this HTML you can see that I need to find the SRC in the  tag. The SRC is invalid and it should be http://local/test.png. I am searching the HTML with $this->xpath('//span[@class="cke_button_icon"]/img[@src]'); but getting a blank array in return.
How can I fetch this element?

Perhaps you could try the following XPath: //span[@class="cke_button_icon"]/img/@src.


Fatal Error: Call to undefined function in a drush backup module I am getting a weird error when attempting to use Drush.

  Fatal error: Call to undefined function variable_get() in
  /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc on line 29
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function variable_get() in /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc, line 29

I have disabled and removed the xmlsitemap module, but it looks like it is referencing some weird backup version of the module.

The function variable_get doesn't exist in Drupal 8. I suggest just removing ~/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc or moving ~/.drush/backups to ~/.drushbackups if you can control this.

Your problem is probably caused by the fact that you are putting the backup inside the ~/.drush directory and Drush is parsing code/files in that directory.


dynamic options list based on the previous select box value I have a webform. I want the second select box values to be loaded based on the 1st select box value. And these values should be loaded from DB table. Please let me know which hook i need to use and how to do it.


Views exposed filter autocomplete weird function() code Should one worry when a Views exposed filter autocompletes a function for certain words?

Type fbn on the exposed filter field for Users. This is an autocomplete field.
RESULT: The autocomplete list offers two options starting with function(..). See image.
Choose the first option, function (E, F) ...
RESULT: The word filter is filled in.
Type again fbn in the field, then choose the secons option, function (B, C) ...
RESULT: The word indexOf is entered.

Inspecting the elements doesn't work very well, as soon as the focus leaves the field the autocomplete vanishes. I'll try some more with a network sniffer or Firefox instead of WebKit, maybe I'll have more luck.

This could be an XSS injection attempt. Should I worry?

I do not think it is a major problem.  I had a similar problem a while back ( I don't remember how I cleaned it up :( ).  I would recommend you do check on another browser, but also try running update in the URL  (example.com/update.php) this script makes certain that all DB updates of  modules are completed.  If it persists, you may want to visit the Views issues site at Drupal.org.

Please post back on this page with what worked.


Do we have an option to change/override the drupalsettings variable which is defined by some other module through our custom module? What is the best approach to change/override the drupalsettings variable which is defined by some other module (basically core) through our custom module ? If I follow the same hooks then how to call it at very last in Drupal 8?
Here: by drupalsettings, I am asking about the Drupal behaviors variable.
The question is updated as suggested by @leymannx.

You can alter the drupalSettings with the hook "hook_js_settings_alter":
function hook_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {

  // Add settings.
  $settings['user']['uid'] = \Drupal::currentUser();

  // Manipulate settings.
  if (isset($settings['dialog'])) {
    $settings['dialog']['autoResize'] = FALSE;
  }
}

For more information see: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_js_settings_alter/8.9.x
I checked the code and the theme hook is run after the module hook. So if you really want to be last. Add the hook to your theme.
web/core/lib/Drupal/Core/Asset/AssetResolver.php:
$this->moduleHandler->alter('js_settings', $settings, $assets);
$this->themeManager->alter('js_settings', $settings, $assets);


Integer user form field with min 11 digits and max 11 digits I need an integer form field with has a validation of min 11 digits and max 11 digits. In other words; the user has to fill in an 11 digit code.

How do i make this field and validation?

Update:

I managed the field by setting a min of 10000000000 and max of 99999999999. But now i get this validation message:

  RIZIV number: the value may be no greater than 99999999999.

How do i change this validation/error message to something like:

  Fill in your right 11 digits RIZIV number.

Go to admin/config/people/accounts/fields add an integer field and set the limitations and by hook_user_update you can check the validation after saving the user profile.


How can I install CKEditor on a server without downloading the files locally? A bit of background info before I get down to my question - I'm using the URL method of loading modules to Drupal as I do not wish to save them to my dinosaur age PC. I have also not uploaded Drupal to my PC, but am operating it via Pantheon. This is not only because of my old PC, but as I am only in the very early stages of developing my website, one advisor has said I don't need to worry about that and other programs such as MySQL.

I'm keen to get CKEditor onto my Drupal platform, so have added the CKEditor - WYSIWYG HTML editor module and this appears so far to be successful.

The tutorial I am following assumes that I am able to save the CKEditor program to my PC... which I guess in essence I can, but I am hoping there is a way to avoid doing this and load it the same way I do a module via URL perhaps?

Pantheon assumes that you are using git; although there is an on-server development feature, the primary workflow is designed to use git as a conduit between your local machine and Pantheon's servers.

Nearly all tutorials you encounter will also assume you are able to download files to your server/local machine.

Even if you don't install Drupal to your local machine, you can clone your Pantheon repository and download/edit/commit the files locally without running Apache, MySQL, etc.  (Documentation here)

I would not try loading modules via URL using Pantheon; you need to learn how to use Git or you will constantly be running into problems later when you try to sync your sites.

Alternately, if you just want a WSYIWYG editor and some other nice features, you could try spinning up the Panoply distribution of Drupal 7, which includes a bunch of modules pre-configured out of the box (though it still has a fair number of bugs).


Make a page unsearchable I made an AJAX email page that allows the user to send a short email, and it loads a separate page showing a message similar to"Your email has been sent." Can I make that last page (the one that shows the message) unsearchable? It's just a success page, and I think it shouldn't come out in any search result.

There is a good article by Lullabot that covers this: Hiding content from Drupal's search system.


How to do (unit) testing of Drupal specific JavaScript code? For PHP code in custom module, we use SimpleTest. But how do you test the JavaScript code in a module or a theme?

I known about JavaScript testing frameworks like Jasmine or QUnit, but I'm curious to known if and how they are used to test Drupal specific JavaScript code.

Right now we don't have any automated testing of the UI. There have been talks about using Selenium and there is even a proposed session about it for DrupalCon London, but i don't know of any work that has been done yet.

This could be a nice contribution for Drupal 8.


Date module is missing but it's exisit I have installed Date module since i made drupal installation, i built many date fields but Suddenly this message show up when i go to my content type's manage field page "Inactive fields are not shown unless their providing modules are enabled.

The following fields are not enabled:(here my date field and tell me date module is not enabled)"

When open modules page can't find date module but other sub modules exist like (date tools, date views ....)

I tried to recopy the date module and nothing change, date module still lost.

All my date fields disabled please help, thanks.

Check the permissions and owners of the date module folder inside your sites/all/modules it should be same as others...

Check drupal watchdog logs for more information on errors....