Preprocessing a front page block causes errors on other pages: why? I'm currently working through self-set tasks to learn Views and pre-processing in Drupal 7. I've created an unformatted view which creates a list of images (which are linked to a content-type but it seems if I replace the fields in view with node:type then I get a link to the node page which is not what I'm after) to place them in a block. I've placed the block into the highlight region and have written a views-view-fields--image.tpl.php file to output the list into various unordered list formats which are then transformed by jCarousel or the featureList jQuery plug-ins.

On top of this, I've created a page--front.tpl.php file to restyle the front page and it appears to work in that the CSS, js and HTML are working correctly and the carousel and lists appear & work in the defined block.

However when I leave the front page to another page where the view should not appear, I get the following error:

  Notice: Undefined property: stdClass::$_field_data in iaintest_preprocess_views_view_fields() (line 10 of /Applications/XAMPP/xamppfiles/htdocs/drupal/sites/all/themes/iaintest/template.php).

To pre-process the list that the view outputs, I've written the following pre-process code:

function iaintest_preprocess_views_view_fields (&$variables) {
  if (!$variables['view']->result[0]->_field_data) {
    // Line 10 where the error occurs.
  }
  else {
    drupal_add_css(path_to_theme() . '/jcarousel/skins/tango/skin.css');
    drupal_add_css(path_to_theme() . '/featureList.css');
    $js = "
      jQuery.noConflict();
      jQuery(document).ready(function(){
      jQuery('#mycarousel').jcarousel();

      jQuery.featureList(
        jQuery('#tabs li a'),
        jQuery('#output li'), {
          start_item: 1
        }
      );
    });";

    drupal_add_js($js, 'inline');
    $items = array();

    foreach ($variables['view']->result as $key => $vars) {
      foreach ($variables['view']->result[0]->_field_data['nid']['entity']->field_images['und'] as $k => $v) {
        $variables['carousel'][] = array(
          'uri' => $v['uri'],
          'alt' => $v['alt'],
          'title' => $v['title']
        );
      }
    }
  }
}

I have tried using drupal_is_front_page() or $variable['is_front'] === TRUE to limit this part of the preprocessing to the front page, which is the only place where the original view appears.

Is this possible at all, or have I misunderstood anything?

Try:

<?php
if (isset($variables['view']->result[0]->_field_data)) {
//
?>

Instead of your weird if/else construct. Not really sure what you are trying to accomplish with that code, so there might be a better way to check if you want to execute it or not.


Which Rules Event should I use to change the value of a Select List field? Use Case:

I've got two select lists

Due Date
Status

The Due Date is a Date field, the Status is a select list with options: Current, Past Due.

By default, Current is pre-selected.

I want to run a Rule that when the current date is greater than the Due Date, the value of the select list will change to Past Due.

I was trying to experiment with the Rules module, not sure about the event. Would it be Drupal is initializing?

What's the best approach?

Add event entity has a value or data comparison
Add condition according to your select list
Add action set data value against changed value


Very simple but working drush extension? I want to implement my own Drush command, and struggle because while the "Make me a sandwich" example is very good, it's also quite complex, and for someone that has never made such an extension it's easy to loose track of what is mandatory, and what is optional.

I would like to see a basic Drush extension implementation.

This is valid for Drush >= 4

<?php
/**
 * @file EXAMPLE.drush.inc
 * Provides a simple drush extension example
 */

function EXAMPLE_drush_command() {
  return array('COMMANDNAME' =>
    array(
      'description' => 'My example command',
      'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    ),
  );
}

function drush_COMMANDNAME_validate() {
  // Return
  // drush_set_error('MACHINE_NAME_OF_FAIL', dt('Command failed because [reason]'));
  // on error.
}

function drush_COMMANDNAME() {
  echo 'Extension working!';
}


How to run  code in a block I'm trying to utilize some pre-built code to display data in a Block. Specifically, show a crude oil price quote in a block.

On oil-price.net, they give you code to embed on an HTML site to display a price quote. So how the heck do i get this on a Block?...it looks like this:

This is what they give to embed...

 To get the BRENT oil price, please enable Javascript.

Create a block (navigate to Structure -> Blocks -> Add block or http://example.com/admin/structure/block/add)
Make sure you set the Text format of the block to "Full Html"
Paste in your embed code

Please be aware of the security risks involved http://example.com/admin/help/filter, https://drupal.org/node/213156


Custom module versioning I'm writing some custom modules (for a customer), but as expected their are showed in error in update dashboard (/admin/reports/updates): "No version available"

I was wondering if there's any way to tell Drupal that these module belong to another webservice to check for latest updates. So I can manage my module versioning and be aware quickly if some of my module are up to date or not.

I searched a lot about it but no result so far, if this is a duplicate feel free to point it out so I can check it out.

By default, Drupal assumes that any installed module or theme is hosted on drupal.org. This means that, if you are using a custom module (which is probably not hosted on drupal.org), Drupal will return the error you are seeing because it doesn't find any information about the module you are using, on drupal.org.

If you just want to stop Drupal from looking for a module updates, normally because you are using a different method to update it, or because the module is not hosted on drupal.org (for example, a custom module you have on your computer, on Git, Gitlab, or similar services) you can implement hook_update_projects_alter().

function custom_module_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['custom_module']);
}

With this example code, the custom_module module is hiding itself, but a module can hide any module. For example, if I had a custom_core module that is a dependency for every custom module I use on my site, I would implement the hook using code similar to this.

function custom_core_update_projects_alter(&$projects) {
  // Hide all the site-specific modules from the list.
  unset($projects['custom_user_data']);
  unset($projects['custom_entities']);
  unset($projects['custom_spam_prevention']);
}

If you want Drupal checks for updates on a site that is not drupal.org, then the .info.yml file for the module needs to contain the following line. (See the code of the UpdateFetcher class, which is the class that fetches project information from remote locations.)

project status url: http://example.org/project-history

In this case, for a module using my_module as machine name, Drupal will fetch the information about Drupal 8 releases of the module from http://example.org/project-history/my_module/8.x.

Notice also that:

If the .info.yml file also contains a project: my_custom_project line, Drupal will check for information about Drupal 8 releases of the module from
http://example.org/project-history/my_custom_project/8.x, not http://example.org/project-history/my_module/8.x (This is useful when a module is a sub-module of another module, and both are packaged in the same file.)
Drupal expects that http://example.org/project-history/my_module/8.x returns XML data that follows a specific format; you can see for example what drupal.org returns for the Date module (https://updates.drupal.org/release-history/date/8.x)

<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
  <title>Date</title>
  <short_name>date</short_name>
  <dc:creator>vijaycs85</dc:creator>
  <type>project_module</type>
  <api_version>8.x</api_version>
  <project_status>unsupported</project_status>
  <link>https://www.drupal.org/project/date</link>
  <terms>
    <term>
      <name>Projects</name>
      <value>Modules</value>
    </term>
    <term>
      <name>Maintenance status</name>
      <value>Actively maintained</value>
    </term>
    <term>
      <name>Development status</name>
      <value>Under active development</value>
    </term>
  </terms>
  <releases>
    <release>
      <name>date 8.x-1.x-dev</name>
      <version>8.x-1.x-dev</version>
      <tag>8.x-1.x</tag>
      <version_major>1</version_major>
      <version_extra>dev</version_extra>
      <status>published</status>
      <release_link>https://www.drupal.org/project/date/releases/8.x-1.x-dev</release_link>
      <download_link>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</download_link>
      <date>1380568703</date>
      <mdhash>f36524e70ed83fe7f2812d3768a337c0</mdhash>
     <filesize>164918</filesize>
     <files>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</url>
         <archive_type>tar.gz</archive_type>
         <md5>f36524e70ed83fe7f2812d3768a337c0</md5>
         <size>164918</size>
         <filedate>1380568703</filedate>
       </file>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.zip</url>
         <archive_type>zip</archive_type>
         <md5>781eb8cb238ed8649c93f0e8e2b9e778</md5>
         <size>232819</size>
         <filedate>1380568703</filedate>
       </file>
     </files>
     <security>Dev releases are not covered by Drupal security advisories.</security>
   </release>
 </releases>

Not all the information provided is required, but for each release there must be a URL for the archive containing the module code, which is used from Drupal to download and copy the module on the site server.

As side note, updating a module files with Composer would be the first step to update the module. Drupal still needs to invoke the update hooks the module provide, and update the module information it stores in its database tables (and cache).


How can I add a second submission handler to a form to run after the default handler node_form_submit I need to generate a node of a dependent content type when creating a node of the primary content type.

I have successfully created the function to be called and attached it to the form and it creates the node as desired, but since the function that generates the secondary node runs first, it cannot be populated with the node id of the primary node, nor with any other data elements from the primary node.

How do I ensure that the submit handlers are executed in the proper order?

   $form['#submit'][] = 'nttac_custom_tta_submit';
   $form['actions']['submit']['#submit'][] .= 'nttac_custom_tta_submit';
   $form['actions']['submit']['#submit'][] = array('node_form_submit','nttac_custom_tta_submit');

None of the above methods seem to work although they do get the handlers in the proper order

All the methods you have mentioned should be calling your custom submit handler at the end. However check your $form array when the page is loaded to confirm your custom submit handler is at the right place.

If not try

MYMODULE_entity_insert($entity, $type) {

//Paste your secondary node creation code here

}

See https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_insert/7 for more details on this hook


Password confirmation before submitting a form I have a signature field uploaded in the user profile. So while submitting a form I need users to confirm with their login password to use the signature and copy it into the relevant field. Form gets submitted only the user inputs the correct password which will validate against active directory. Is there anyway we can do this.

You might want to use hook_form_FORM_ID_alter(). Then you can create a valitate function, that checks if the password is correct.

function mymodule_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_article_form_validate';
}

function mymodule_article_form_validate($form, &$form_state) {
  //This is just a dummy example that will not 100% work, so you need the get the correct information.
  $password = 'TesT128#';
  if ($form_state['values']['password'] != $password) {
    form_set_error('password', t('You have entered the wrong password'));
  }
}


How to see if the test works? There is a way to see if the Drupal tests are working? I wanted to test the FileSystemTest, but when I type phpunit command on the test folder this error appears:

1) Drupal\Tests\Core\File\FileSystemTest::testChmodFile
Argument 1 passed to Drupal\Core\File\FileSystem::__construct() must be an instance of Drupal\Core\File\StreamWrapperManagerInterface, instance of Mock_StreamWrapperManagerInterface_428d696c given, called in /var/www/html/drupal-8.0.5/core/lib/tests/FileSystemTest.php on line 43 and defined

/var/www/html/drupal-8.0.5/core/lib/Drupal/Core/File/FileSystem.php:62
/var/www/html/drupal-8.0.5/core/lib/tests/FileSystemTest.php:43
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:153
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:105

Someone know how to make the test work with phpunit?

See https://www.drupal.org/node/2116263.

You either need to run it inside the core folder, or (easier IMHO), you need to pass the -c core argument, so it finds the phpunit documentation.

Also note that only a part of Drupal's tests are phpunit, others are based on our own test framework and you need to run them with run-tests.sh or through the UI.

That said, you only need to run core tests if you work patches for Drupal core. Drupal's tests always path, nothing is added unless it is passing all tests.


A clean solution for adding _target attribute on flickr thumbnails I have a module relying on media_flickr.

Some images in the body are thumbnails with anchors:

What hook to use to add the _target HTTML attribute on links?

The markup is to be found in

body['und'][0]['safe_value']

I prefer not to use javascript.

There isn't one - links contained in HTML in a node body are not structured, do not run through l(), and no opportunity is given to 'hook' into them during rendering.

You have 3 options:

Change the markup to include the target attribute.
Preprocess the field and run a regex replace on the HTML to add the attribute.
Use javascript (by far the best option).


How to theme the edit page of a form and retrieve $form variable from the hook_form_alter into the template for theming purposes? I have a content type A
How can I add custom theme to edit page of that content type A in drupal 7 only for specific role ?
In my module,

function hook_form_alter(&$form,&$form_state,$form_id) {
if (form_id == 'content_type_a') {
global $user;

if (in_array('rad',$user->roles)) {
$form['#theme'][] = 'custom_content_type_a_node_form';
}
}
}

In my template.php file I have the following code

function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
      'variables' => array('form' => NULL),
    );
  );
}

function THEMENAME_custom_content_type_a_node_form($form) {
// When I check here for $form I get an empty value
// I want to get the $form value derived from the form_alter function's $form //variable . How can I achieve it?

}

How can I retrieve the $form value from the hook_form_alter's $form variable?

Try something like this:

function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
      'render element' => 'form',
    );
  );
}

function THEMENAME_custom_content_type_a_node_form($variables) {
  dpm($variables);
}


How do I export/import views? I know how to do it in Drupal 6/7, but I cannot find where to export/import views in Drupal 8. From which admin page is possible to do it, in Drupal 8?

Views are available through configuration in Drupal 8, and can be exported via the Configuration Management interface.

In the admin menu select "Configuration" in the DEVELOPMENT section, select "Configuration synchronization":

In that menu area, the Export tab leads to the path:
http://sitename/admin/config/development/configuration/single/export

In that area, a single view can be exported or imported, and the steps are about the same so I'll include Export here to help explain.

Select 'Export' menu tab.
Select 'Single item' sub menu tab.
From the first item drop down 'Configuration type' select 'View'.
From the second item drop down 'Configuration name' select the name of your view.

The result is a views.view.view_machine_name.yml "YAML" file that can be copy pasted into the 'Import' area.


Preprocess variables only for certain blocks Is it possible preprocess variables only for certain blocks?
I created mytheme_preprocess_block__aggregator(&$vars), but it doesn't work.

Unfortunately, there is no way to do it like that (similar to hook_form_alter()).

The best way to do this would be to use $variables['block']->bid to apply modifications only to the blocks you want:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block']->bid === 'target_block_id') {
    // do something for this block
  } else if ($variables['block']->bid === 'other_target_block_id') {
    // do something else for this other block
  }
}


Content Field Type Image not auto resizing I am fairly new to Drupal, I am currently working through Tom Geller's excellent video series on Lynda.com. All is going well, except I am having a problem when trying to set display properties for any content types containing an image field. If I keep the display settings for the image field as the original image then it will display. However if I try to set an image style for example to use as a thumbnail for a teaser, the image does not show. In Chromium there is an empty frame of the correct size but the image does not display. In Firefox only an empty space is shown where the image should appear.
I am running my site on a local Apache server which contains multiple sites, and the issue occurs in all the sites. I have the most recent stable versions of Apache, PHP and mySQL. I have come across other threads on various sites where people have had this issue however their fixes have not worked for me. I'm sure its simple fix but its been bugging me for hours!
Thanks in advance,
Jackson

Verify that the images are being created by checking public://styles - (/sites/default/files/styles) by default.  If you see that the images are not being created then you might have your folder permissions set up incorrectly.  /admin/reports/status might hint at any permissions problems.


Edit theme login page I'm using a theme called Nexus.

Now in the login page, /?q=user, it looks somewhat like this:

All I want to do is change the order of the tabs, where "Log in" is in front, number one, then Request new password, then lastly Create new account.

Aka:
[Log in][Request new password][Create new account]

I've tried looking in the theme's folder, including page.tpl.php, and in the user module files to see if I could find where it was defined/rendered but I couldn't find anything.
This also did not seem to be what I wanted.

Sorry for being such a noob.

You may use hook_menu_alter function to do it

/**
 * Implements hook_menu_alter.
 */
 function MYMODULE_menu_alter(&$items) {
   $items['user/login']['weight'] = 0;
   $items['user/password']['weight'] = 1;
   $items['user/register']['weight'] = 2;
 }


Custom field in order not shown on checkout panel I just discovered the commerce 2 module.
I create a date field in the order type ( each customer need to select a shipping date when they bought product ).
If  I create the order from the adminstrator interface the field is displayed.
But when the customer use cart to buy a product the date field is not display ?
Can you help ?

There is no code that shows custom order fields at checkout. You will need to write a custom checkout pane plugin.


Translate with t() function from spanish as source I have a Drupal 7 webpage already developed with all texts in Spanish, but now I want to add English language to the page.
As all my texts are written in spanish, I would like to know what is the best/fast way to translate it to english. I tried with t() function, something like this t('Hola mundo') expecting to be manually translated by me with Drupal translation module (admin/config/regional/translate/translate) to 'Hello world'.

The Drupal 7 documentation says this:
$string A string containing the English string to translate.

So my question is: is there any way to translate with t() from the default language (spanish)?

If it is not possible, how can I translate all the texts to english from spanish?

Thanks

If you look at the API for t() - https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7 - you'll notice that it allows you do specify $langcode in the options array, however, that is a method to override the output language - not the input.

If you don't want to translate from English to Spanish, but the other way, there is a small quirk in Drupal localization framework.  The name "English" in Drupal is reserved as the default index for languages, so you can't use that name for the target language.  But please note that you don't have to use the index named "English" to hold English strings.  You can use anything for that index. You can define new languages, and even invent them, so let us define a target language called "Ingles", and use that for English.

Now for each phrase you want to translate fro Spanish to English, you need to assign an index for lookup in the translation table.  Let say you assign "¡Hola, mundo!" to be the index corresponding to the Spanish phrase "¡Hola, mundo!".  On at least one page (it doesn't matter if it is Spanish, English or "Ingles, you must have t("¡Hola, mundo!"); to get Drupal to pick this up.  Now go to Drupal's translation interface and search for "¡Hola, mundo!".  When you've found it, you can enter the correct strings for the Spanish original ("¡Hola, mundo!") into the field for "Spanish" and its translation into English ("Hello, world!") into the field for "Ingles".  Do that with every phrase you want to translate from Spanish to English.

When done, you should be able to use t("¡Hola, mundo!"); on a page with Spanish as its default language to make the user see "¡Hola, mundo!".  To get the translation into English, you also use t("¡Hola, mundo!");, but make sure the page's default language is "Ingles" (not English).  This is how you use t()-to translate from Spanish to "Ingles" (which is just an alias for "English" - we must use this alias since Drupal has reserved "English" to hold the default translation index).

However, you may find it a bit awkward to "invent" a new language called "Ingles". And there is a simpler way!

Instead of using "¡Hola, mundo!" as an index to "¡Hola, mundo!", you pick "Hello, world!" as your index. Otherwise, you proceed like before - to get this variable into Drupal's inserted into translation interface, you must on at least one page have t("Hello, world");  (it doesn't matter if that page is Spanish, English or "Ingles).

Now, instead of "¡Hola, mundo!" showing up as am index in Drupal's translation interface, you'll see the index "Hello, world!".  But just like before must enter the string "¡Hola, mundo!" as the Spanish original phrase, and for translation into "Ingles", you enter "Hello, world!".

However, now there it is also possible to get rid of the invented language "Ingles".  It just so happens that if the default language for a page is English (not "Ingles"), t();will not look up the string in the table but just return the index.  And since we're now using English phrases as index that index will be in English on pages where the default language is English. So we can stop using the the invented language "Ingles" and instead rely on getting the index back on English pages, while on Spanish pages, the index will be used for table lookup and we will get a Spanish string back.


How do I completely uninstall a custom entity implemented by my module? I need to write an uninstall use-case for my custom entity. I just want to know what operations I should take care of, in order to completely uninstall my entity/module and all attached fields (including custom fields created by Field API).

Should I use hook_uninstall and how should I implement this hook?

The tables declared by the hook_schema() will be automatically remove when you uninstall your module.

If you need to remove other tables or variables use the hook_uninstall()


How to implement Slider Effect for pages? I have few pages in my site and I want 4 specific pages to be rendered as slider with the full content of the node appeared as a slide.

On a desktop I want the slides to change using html arrows and on mobile I can swipe the slides.

I checked for contributed modules but mostly which I came across have been developed for photo galleries.

Is there a way to implement swipe for pages in mobile view and slider for specific pages?

It depends on the JavaScript library a module uses.

I use the Flex Slider https://www.drupal.org/project/flexslider that it have both arrows for desktop and swipe for mobile.

I can't understand what you want to achieve (static?), but:

I think the best way it to create a new content type (let's say slider) to upload images that will be used by the slider plus a taxonomy field that you will specify the slider you want to display the image.
Then create a slider view with a filter based on that taxonomy.
Finally render the view as a block.

-- EDIT --

So, you want to create a slider that will present nodes.

Let's say we have two content types Article & Basic, with fields: Title, Description, Image, Taxonomy.

Create a View
Format: FlexSlider, Show: Fields
Fields: Title, Description, Image etc
Filter criteria: Content type->Article, Basic
Save
Edit the appearance of the slider with css
Enjoy

The nodes will be pre-loaded and there will be no waitting time from slide to slide (but it will take longer to load the page).


Dynamic about us page I'm fairly new to Drupal and have this task to create an about us page. Now every customer has two certain co-workers assigned to him. This information is stored in the database. I want to show the two co-workers depending on the customer that is signed in. Someone said that I need to create a custom content type, but i couldn't find anything about it online. What would be the best approach to this problem?

Sounds like you need to use Views with a contextual filter based on the logged in user and a relationship from the user to the coworkers


Can't log onto drupal with any email address I am receiving "Account Approval" spam at one of my email addresses. I can't log onto to Drupal using that or any other email address I am using. When requesting new password using various email addresses, all are rejected as unknown. Will creating a new account allow me to install module(s) to kill spam?

Consider editing the eMailId currently stored in the Drupal database, using PhpMyAdmin. And this by replacing that eMail ID with some other eMail ID that is usable for you.

Then use the "request new pasword" feature for that account, which should be mailed now to the eMail Id that you can work with. Use the password reset link and you should be up and running.

Does this help?


How can I give Ajax access to currently set fields on my form? I'm working on a block form that needs to update certain elements in the form based on what the user selects with certain elements. I've defined the internal class method and it's getting called correctly; however, it can't access the values stored in the form from the $form_state.

For example, when I call $form_state->getValue('filter_field'), it returns an empty value, even though it has been set on the page. I suspect that this may be due to the fact that I'm setting the callback like so: 'callback' => [get_class($this), 'updateWidgetAjax'], and in the final comment in the API, it says to do it like this: 'callback' => '::updateWidgetAjax'. However, when I try this, I get the The specified #ajax callback is empty or not callable. error. I tried following the tutorial on the API page as well as here, yet neither of them worked properly, spouting out the same error as before. I also went through this checklist, but most of the items don't apply.

Additionally, and this is just something annoying but related, if I don't mark updateWidgetAjax as static I get the following message in my log: Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\global_filter\Plugin\Block\FilterBlock::updateWidgetAjax() should not be called statically, which I suspect will be resolved with fixing the above issue.

In short, how do I get the form values in my Ajax callback?

The element calling the Ajax:

$form['filter_field'] = [
  '#type' => 'select',
  '#name' => 'filter_field',
  '#title' => t('Select field to get the filter value from.'),
  '#options' => self::getAvailableFields(),
  '#empty_option' => t('Select a field'),
  '#ajax' => [
    'callback' => [get_class($this), 'updateWidgetAjax'],
    'event' => 'change',
    'wrapper' => 'default-value-ajax-wrapper',
    //The wrapper is elsewhere on the form
  ]
  '#required' => TRUE,
];

The Ajax callback function:

public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
  $widget = '';
  $multichoice = FALSE;

  switch ($form_state->getValue('widget_type')) {
    //code that sets $widget
  }
  //Return a render array
  $render = [
    '#type' => $widget,
    '#name' => 'default_value',
    '#title' => t('Default value'),
    '#description' => t('Select the default value for this filter. Leave blank for none.'),
    '#options' => self::getOptions($widget, $form_state->getValue('filter_field')),
    '#required' => TRUE,
  ];
  return $render;
}

EDIT: I forgot to mention that the form is defined with a blockForm, since I'm trying to create new blocks with this. I'm following the Drupal documentation found here. I think this might be a big part of the issue.

I have tried this on my local it works . So you can achieve the form values by using this . Please try this

    $form['filter_field'] = [
      '#title' => $this->t('Filter'),
      '#type' => 'select',
      '#options' => ['drupal7' => 'Drupal7', 'drupal8' => 'Drupal8'],
      '#empty_option' => $this->t('-select'),
      '#ajax' => [
        'callback' => '::updateWidgetAjax',
        'wrapper' => 'default-value-ajax-wrapper',
      ],
    ];
    $form['widget_type'] = [
      '#title' => $this->t('Widget Type'),
      '#type' => 'select',
      '#options' => ['pdf' => 'Pdf', 'ppt' => 'PPT'],
      '#empty_option' => $this->t('-select'),
    ];

    $form['wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'default-value-ajax-wrapper'],
    ];

    return $form;

//Ajax callback
  public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
   $widget = $form_state->getValue('widget_type');
    print_r($widget); //Print the value of the field
  }


htaccess settings to allow access to special non-drupal page I have a properly working Drupal 6 site, at the webroot of my server, which can be accessed by www.mysite.com or by mysite.com. I have some special html files (not part of Drupal) that can be currently accessed by going to mysite.com/special and that works fine.

I would prefer that people just go to special.mysite.com to get to the html files in that directory (instead of mysite.com/special).   I just had the DNS set up so that special.mysite.com now points to the webroot, and Drupal currently handles it the same as www.mysite.com.

However, I would like it if people coming to special.mysite.com arrive at the index file within the "special" folder on mysite.com. I bet I can do something to the .htaccess file that Drupal uses in the webroot directory - but I don't know what? Any advice? Thanks a ton.

add in your .htaccess.

RewriteCond %{HTTP_HOST} ^special.mysite.com$
RewriteRule ^/?$ "http\:\/\/mysite\.com\/special" [R=301,L]


Undefined variable: _SESSION in template.php I use this code (not mine, I do not know how to code) to disable Maintenance mode message on front-page while developing a site, it's really annoying when it's flashing all the time in the middle of the page.

function theme_preprocess_page(&$vars) {
    if (variable_get('maintenance_mode', 0)) { //no maintenance mode message on front-end
      $message_count = count($_SESSION['messages']['status']);
      if($message_count > 1) {
        array_shift($_SESSION['messages']['status']);
      }
      else {
        unset($_SESSION['messages']['status']);
      }
}

So it works great while logged in and in maintenance mode, but when going to user/login page as anonymous, it gives this notice in red:

Notice: Undefined variable: _SESSION in theme_preprocess_page()
(line 141 of /sites/all/themes/mytheme/template.php).

So what is this? Is the code missing something?

Apparently the $_SESSION variable is not available on the login page (I don't know why, but probably to avoid conflicts with logged in users trying to log in again).

Try checking for it before you try to unset it:

function theme_preprocess_page(&$vars) {
    if (variable_get('maintenance_mode', 0) && isset($_SESSION['messages']['status'])) { //no maintenance mode message on front-end
      $message_count = count($_SESSION['messages']['status']);
      if($message_count > 1) {
        array_shift($_SESSION['messages']['status']);
      }
      else {
        unset($_SESSION['messages']['status']);
      }
    }
}


How to show an Inline Entity Form on a PM page or panel? I'm trying to include an Inline Entity Form on a panels display (via ctools Page Manager).

The Inline Entity Form field is attached to users, and the page in question has the user's context.

The Inline Entity Form field does appear in the panels interface, in two different ways, but neither work:

As a "User" field content type

It simply displays the text 1

As a "User (tokens)" content type

It simply displays the text 1

As a "Form" content type

It simply display the text Entity info

This is a very crude, brute force answer. Basically, it's: create a PHP block that loads the user edit form with all fields except the Inline Entity Form field hidden, then display it.

Enable PHP Filter module (part of Core but disabled by default)
Create a new block with this code:

..

<?php
global $user;
module_load_include('inc', 'user', 'user.pages');
$account = user_load($user->uid);
$form = drupal_get_form('user_profile_form', $account);
print render( $form );
?>

Hide the fields except the ones you want. Two ways to do this:

The tricky, 'proper' way: in the block, hide the array elements in $form by either unsetting or setting type to hidden. There could be complications with this.
The quick and dirty but safe way: just set them to display: none; with CSS. This way the full form is present and unadulterated, but invisible.

This is fine unless you're adding a multiple values Inline Form to a user profile. If that's the case, when you try to add a new item to the multiple value field, you'll hit this error:

  Call to undefined function user_profile_form_validate()

It's because the AJAX doesn't know it's dealing with a user form and so doesn't think to load the necessary pages from the user module. The only way around that I can find is to create a custom module with the following (then flush caches etc):

function custom_module_name_init() {
    module_load_include('inc', 'user', 'user.pages');
}

This isn't ideal since it loads a page of code which is normally unnecessary everywhere - but the overheads for PHP scanning then ignoring one sheet of code are pretty small. If anyone knows a cleaner way to do this, however, please share it!


What file permissions and ownerships are appropriate for the files directory and subdirectories? Possible Duplicate:
  What are the recommended directory permissions?

I've scoured the net, and it seems that everyone has different methods of doing this and I just want to get a quick straight answer if possible. So i'm on Centos with apache installed.

I know the files folder has to be 777, but 777 is insecure as anyone can write to it, but isn't that what we need since anonymous users have to write to it when they upload to the server like images or what not? And not to forget drupal throws an error if its not 777.

Also if my user for that domain is foo, then the ownership of files and all its items inside would be foo:foo  correct? But im reading it should be foo:www-data ? so which one is it?

It depends somewhat on your server configuration but it doesn't have to be 777, and in fact it should not be 777 as that is a security issue.

The web server user (on your server, not your drupal site) is what has to be able to write to the files directory. Whether the drupal user is logged in or anonymous is unrelated.

For information on this see http://drupal.org/node/244924


conditional validation in webform I have webform 7.x-3.18+3-dev and webform presav e 7.x.1.1 installed

how can I make one field be obligatory depending on another field.

Eg if someone selects phone as best form of contact they must fill out the phone field. If they choose email they must fill out the email field.

Take a look at https://www.drupal.org/project/webform_conditional

Just make both e-mail & phone mandatory, but only show the relevant field, based on what was chosen in 'best form of contact'.

The module takes into account the 'state' of the form. It doesn't force mandatory, even if the field is set to be mandatory, but is hidden due to a certain select option ( in your case, the 'best form of contact' ).


Displaying arbitrary HTML (or webgl) inside a Drupal frame (Drupal 7) I would like to have a page inside my drupal site that would show a webGL Canvas but it seems that Drupal tries to shield its user from doing any direct HTML hacking on a page.

How would one embed a webGL Canvas (or any other arbitrary html for that matter) inside a Drupal page?

Depending on your needs, you may also not want to create your HTML page containing a WebGL canvas as content managed by Drupal. Instead, you can create a custom module providing a single page with your canvas and the additional JavaScript and CSS files.

function MODULE_menu() {
  return array(
    'path/to/canvas' => array(
      'title' => 'Awesome WebGL application',
      'page callback' => 'MODULE_canvas_page',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
}

function MODULE_canvas_page() {
  drupal_add_js(drupal_get_path('module', 'MODULE') . '/module.js');
  drupal_add_css(drupal_get_path('module', 'MODULE') . '/module.css');
  return theme('webgl_canvas');
}

function MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'webgl_canvas' => array()
  );
}

function theme_webgl_canvas() {
  return '<canvas id="glcanvas" width="640" height="480">Your browser doesn\'t appear to support the HTML5 <code>&lt;canvas&gt;</code> element.</canvas>';
}

The MODULE_menu() is an implementation of hook_menu(). It declares a page available at path/to/cancvs and handled by the MODULE_canvas_page() function. The handler function adds JavaScript and CSS files using the drupal_add_js() and drupal_add_css() which allow the files to be aggregated into single .js/.css files (if that feature is enabled for the site). It then return the markup for the WebGL canvas. The markup is produced by a theme hook function (theme_webgl_canvas()) declared in MODULE_theme which is an implementation of hook_theme(). This allow the theme or other modules to change the markup.

Because a WebGL page/application would likely use a lot of custom JavaScript, you may also want to check the Managing JavaScript in Drupal 7 guide.


How do I use hook_views_query_alter() to re-write a query? I have a very simple view that lists all the nodes, which shows the following query:

SELECT node.nid AS nid, node.title AS node_title, node.uid AS node_uid, node.created AS node_created, 'node' AS field_data_field_site_node_entity_type, 'node' AS field_data_field_status_node_entity_type
FROM
{node} node
WHERE (( (node.status = '1') AND (node.type IN  ('ticket')) ))
ORDER BY node_created DESC
LIMIT 50 OFFSET 0

I am trying to overwrite it with a custom database query to list only nodes of the user referenced in the URL and all his invitees. This is the code I am using.

function my_custom_module_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "support" && $display_id == "page" ) {
    // Let's start collecting uids and put current page uid as the first member of array.
    $uids[] = arg(1);

    // Now let's collect all invitees of the page uid author and push into the same array.
   $query = db_select('invite', 'i')
     ->condition('i.uid', arg(1), '=')
     ->condition('i.status', '3', '=')
     ->fields('i', array('invitee'));
   $result = $query->execute();
   foreach ($result as $record) {
     $uids[] = $record->invitee;
   }

   // Now let's pull all the nodes of the inviter (page uid) and his invitees.
  $query = db_select('node', 'n')
     ->condition('n.type', 'ticket', '=')
     ->condition('n.status', '1', '=')
     ->condition('n.uid', $uids, 'IN')
     ->fields('n', array('nid', 'title', 'created'));
   $result = $query->execute();
   foreach ($result as $record) {
     dpm($record->nid.' | '.$record->title.' | '.$record->created);
   }

  }
}

dpm() shows all the correct nodes, but reading hook_views_query_alter() I still can't figure out how to make my view use this query.

How can I achieve this?

While exploring a site-building alternative (see comments in OP), here is a direct answer to the question:

Implementing the hook_views_query_alter should do what you want:

function my_custom_module_views_query_alter (&$view, &$query) {
  $display_id = $view->current_display;
  $uid = $view->args(0); // for a view that is loaded from a URL like /myview_url/UID

  // Your code from the OP follows, modified accordingly
  // You have a query object available as an argument by reference
  // You can add joins and filters to it
  ...
}

You would need to implement the hook_views_api in addition to placing the above code snippet inside the my_custom_module.views.inc file, a minimal implementation would be:

function my_custom_module_views_api() {
  return array(
    'api' => '3',
  );
}

Cheers!

P.S.: Have a look at this one, if you haven't already => http://www.kdweb.co.uk/blog/drupal-module-views-hook-sequence


How do I customize hierarchical breadcrumbs? The breadcrumbs I get are like the following ones.

Home / services
Home / service 1
Home / service 2

I want to change them to the following ones.

Home / services
Homes / services / service 1
Homes / services / service 2

How can I change the breadcrumbs to be the way I want them?

In D8 the hierarchy of breadcrumbs is by default path based, so you have to change the path for the second level from /service1 to /services/service1

Or install a module to build the hierarchy based on menus or taxonomy terms:

https://www.drupal.org/project/menu_breadcrumb
https://www.drupal.org/project/taxonomy_breadcrumb


Not able to remember the user id I am new to Drupal. I have created a menu on user page to edit the account settings as user/uid/edit.

I just want to know how to replace uid with the user id of current user.

I have faced a similar problem in the recent past and found two solutions for the same.

Short solution

Install Me alias module, and then replace your uid with me, and the module will replace me with the uid of respective user.

Long solution

Install Menu token module and use token to replace the path of the menu. Go to edit menu and in the path, do the following


Assign tinymce to text formats Just to start with I am trying to do this in code (installation profile), not in Drupal itself.
In my installation profile I create three text formats. Thanks to the drush make file tinymce is also automaticly installed. Now wysiwyg gives you the option to assign the editor to a text format. See image below how the option looks in Drupal.

Now I am wondering how I could change the 'No editor' to 'TinyMCE' in my installtion profile. After changing the option in drupal itself then the database changes to: (see image below)

What is the right way to do this and how can I change these module settings?

Looking through the WYSIWYG modules' code when saving the form, it implements:

db_merge('wysiwyg')
  ->key(array('format' => 'full_html'))
  ->fields(array(
    'editor' => 'tinymce',
  ))
  ->execute();

So that's what I suspect you'll need to put into your install profile


How do I set the active menu item dynamically for a view? How do I change the active menu item when showing a view? This post shows me how to do it for node (using hook_nodeapi()), but how/when/where do I do it for a view? I tried hook_views_pre_view(), but that does not work.

You could use Context and set condition to be your view and reaction to be menu link.


Is it possible to sum on webform I'm newbie and made web form to fill with some values.
I want to sum all values on Column to make it has a total of column Value, like in excel to do sum of several values into one grand total.

Anyone experienced this ?

Thanks in advanced.

There is a tab titled "Analysis" for this. Alternatively you can use the "Download" option. See the example in the screenshot below.


Views displaying node reference fields Will the view chosen (in the advanced settings) of a node reference in a content type get overridden by another view if the node reference field is shared between two (or more) content types?
In more detail: I am working with a Drupal site that has a content type that contains a node reference field. One of the things it asks you when creating the content type is - which views are used to reference the node. I am trying to create another content type that shares the same field as the first one, and it therefore will also be a node reference.
BUT, when I create this new content type, it again asks which view I want to use. If I chose a different one will it override the view in the first content type, since they share a common field?

In Drupal 7 you can have different field settings for different content types. This was not possible in Drupal 6.


Does backup and migrate include the users and login info? I'm migrating from the test environment to the live environment, both of which have a separate set of users/logins/privileges.

How do I not overwrite this information when migrating from one site to another?

If you want to move user data from a Drupal site to another, you need to use the Migrate module. The Backup and migrate module is for exporting and restoring database and files.


ajax request only the first time works? I have made an ajax request to update the select options based on the first select field selection

but the respond only works fine with the first request despite being seen with firebug

help me solve it please

thanks in advance

here is the code

 function listings_form_alter(&$form,&$form_state,$form_id){
    $governments=array();
  if($form_id == 'place_node_form' && arg(1)=='add' && arg(2)=='place'){
    $vocabularies=taxonomy_get_vocabularies();

  foreach($vocabularies as $vocab){
      if($vocab->machine_name =='governorates'){
          $_SESSION['vid']=$vocab->vid;
          break;
      }
  }
        $options=array(0=>'choose gov');
  $g=taxonomy_get_tree($_SESSION['vid'],0,1,FALSE);
  $x=count($g);
  for($i=0;$i<$x;$i++){
                  $options[$g[$i]->tid]=$g[$i]->name;
  }

   $form['gov']=array('#title'=>'Gov','#name'=>'governorate'
,'#type'=>'select','#options'=>$options
     ,'#ajax'=>array('callback'=>'ajax_callback',
  'event'=>'change','wrapper'=>'replace','method'=>'html'));

 $op=array(0=>'choose city');
$form['city']=array("#title"=>'City','#name'=>'city',
'#type'=>'select','#prefix' => '
',
'#suffix' => '
','#options'=>$op);

function ajax_callback($form_state,&$form){

$childs_obj=  taxonomy_get_children($_POST['governorate'],$_SESSION['vid']);
foreach($childs_obj as $child_item){
    $op[$child_item->tid]=$child_item->name;
}

$form['city']=array("#title"=>'City','#name'=>'city','#type'=>'select','#prefix' => '
',
        '#suffix' => '
','#options'=>$op);
return array(
'#type'=>'ajax', '#commands'=>array(ajax_command_html("#replace", render($form['city'])),
ajax_command_alert($_POST['governorate'])
    )

);
?>

Please see http://drupal.org/coding-standards, as it is hard to read.

However that said, I usually find if ajax is only working once then as the element is replaced Drupal gives it a unique id which then breaks a selector. For example #form after the ajax request becomes #form-1 and is no longer targeted. -check for this in firebug


Why is this db_select not working? I can't seem to figure out, are you not allowed to chain db_select methods?

$nid = db_select("node", "n")
            ->fields("n", array("nid"))
            ->condition("f.entity_type", "node", "=")
            ->condition("f.deleted", 0, "=")
            ->condition("f.field_products_product_id", $entity->product_id, "=")
            ->addTag("node_access")
            ->join(
                "field_data_field_products",
                "f",
                "f.entity_id = n.nid"
            )
            ->execute();

I have the above, and it just won't work it keeps erroring on the join. Basically I want to do

SELECT nid FROM node JOIN field_data_field_products ON entity_id = nid WHERE ...

This is answered in this other question:

How to perform join with multiple columns using db_select?

  Calls to SelectQuery::join() (like-wise SelectQuery::leftJoin(),
  SelectQuery::innerJoin(), and SelectQuery::addJoin()) chain-able
  because those methods don't return a SelectQuery object, but the
  actual alias used for the join.


Where to add "No results behaviour" to a view? I'm using an exposed filter. When there is no result, where do I add "No results behavior" for the view?

You can add "No Results Behavior" in view itself.

Then select Text area which will help you to add any custom text.
At last add your custom text and click on apply button.


TinyMCE input format is set to "Full HTML" but code is still being stripped I am trying to enter some HTML into TinyMCE. I know that some input formats can strip code depending on your settings, but I have "Full HTML" selected, yet my code is still being stripped.

What else might be causing this to happen?

Assuming that the stripped tags in question are mostly things like embedded CSS style tags you might need to enable the Full Page plugin to allow them in your content, apparently having style tags in regions apart from HEAD tag is not the best practice and that's the reason the functionality is not enabled out of the box from my understanding. Also assuming that you have the WYSIWYG module with TinyMCE library installed for your cause and not the TinyMCE module, here's a sample code of how I enabled the full page plugin in my case. (The code goes in your custom module, replacing your module name with MYMODULE in the function name).

/**
 * Implementation of hook_wysiwyg_plugin
 *
 */
function MYMODULE_wysiwyg_plugin($editor) {
  // if the editor is tinymce include the fullpage plugin so that embedded css is included
  $plugin_path = wysiwyg_get_path('tinymce');
  switch ($editor) {
    case 'tinymce':
      $plugins = array(
        'fullpage' => array(
          'path' => $plugin_path . '/jscripts/tiny_mce/plugins/fullpage',
          'buttons' => array('fullpage' => t('Full Page')),
          'url' => 'http://www.tinymce.com/wiki.php/Plugin:fullpage',
          'internal' => TRUE,
          'load' => TRUE
        )
      );
      return $plugins;
    default:
      break;
  }
}


Display hash anchor tags into drupal 7 menu items without modifying hooks or adding modules? currently when path url in menu items are set to: node/1#anchor the anchor is removed.

How would you solve this?

Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.


Module installation order Within my custom module i've got an optional implementation to the dynamic entity reference module: https://www.drupal.org/project/dynamic_entity_reference

When the module exists, I add a DER field to one of my custom tables during the module installation.

The issue i am currently facing is that I can not manipulate the installation order of my module. Within the install hook of my module i am using module_set_weight("mymodule",1).
However this is not effecting the installation order at all when I run drush config-import order or drush site-install --config-dir="/my/conf".

Within my core.extensions.yml the weight got applied after config export:
drupal_content_sync: 1

For me this sounds pretty simple to solve. In your custom module just set a requirement:

name: Foo Bar
description: 'Lorem ipsum.'
package: Custom

type: module
core: '8.x'

dependencies:
  - dynamic_entity_reference:dynamic_entity_reference

By that you ensure that dynamic_entity_reference exists and is enabled when your module gets installed. That's it. Except I misunderstand you and you are instead looking for hook_module_implements_alter to change the order of modules calling a certain hook.


Drupal Commerce Export Orders in CSV format How can I export Order details along with custom line item fields data in CSV format?

You can use Views and Views Export modules.

Views Export provides you with a Export display, you do the filter in the view and in the end it will return a link where the orders can be downloaded in csv format.


Trying to create a user with an entity reference taxonomy term using services So I've been trying to create a user with an entity reference taxonomy term, however for some reason it doesn't seem to work.

I've noticed that it depends on the widget used, but I've tried every combination of widgets and data, and it doesn't appear to work.

Here's an example of one way:

                    "field_likes": {
                        "und": "1"
                    }

I've also tried this, also for example:

                    "field_likes": {
                        "und": [
                            {
                                "target_id": 1
                            }
                        ]
                    }

Is there anyway to add taxonomy terms as an entity reference on a user that will work? Has this changed, or am I doing something wrong?

I was able to get it working with the following on checkboxes and select:

"field_likes": {
"und":{
"target_id": "1"
      }
}

This technically solves the problem, though I'm not sure how to send up multiple values this way.

EDIT:

Here is the actual solution, which not only allows you to put in entity reference taxonomy terms, but multiple as well:

"field_likes": {
                 "und":{
                         "target_id": "1",
                         "target_id_1": "2"
                        }
                }

This is with the select list widget, which I think is important for this particular example (based on other links I've been reading).


Allow admin to discount line item price or give a user credit I have a client who'd like to give certain users an arbitrary discount or credit to be used to pay for a class. In these situations an admin will create the registration (using the Registration module) which will automatically create a cart with this class as a line item. I'm having trouble figuring out what process to use to (from the user's perspective) correct the price for the course in cart.

My understanding is that there's no way to modify the price for the line item directly. Assuming this is correct (if this isn't please let me know!), my research indicates I'll need to add a line item to the order that will (from the user's perspective) reduce the price to where they want it.

What should this line item be? A discount? A coupon? Something else? And, whatever the right "thing" is, how does it get applied?

I've tried installing commerce_discount and have set up a discount, but I cannot for the life of me figure out how to apply it to an order. I've read through the info on this page --> https://drupalcommerce.org/user-guide/discounts-and-coupons, but if the answer I'm looking for is in there, I'm not finding it.

I've also just installed commerce_account_balance thinking that might work, and I am still testing it, but it isn't clear it will be a good fit for my use case either.

My assumption is that others must be doing this and I just don't know enough about Commerce pricing to recognize the one or more helpful answers that are already out there (stack exchange or elsewhere)...

Any direction / thoughts / help on this will be much appreciated.

Thanks

(question originally posted here - it was suggested there that I post questions like this here...)

This sounds like a good use case for commerce_coupon + commerce_discount.

Add these two modules (and dependencies).
Add a new discount for an arbitrary % or $ off.
Add a new coupon code for a particular user.

If the client wants to lock it down even more, you can modify the discount to specify a particular course/product that it applies to. You can also modify the coupon code to only apply to a particular user with a limited number of uses, date range it's valid for, and more.

You'll definitely want to add an "Order discount condition" to the discount to ensure that other products, shipping costs or donations are not discounted.

Once the client has set up the discount and coupon code, they can send this to the user they need to give the discount to.

It's difficult to say where you're getting stuck applying the discount to the order, but I'd guess it has to do with the relationship between discount + coupon. At first I found it really confusing why discounts and coupons needed to be set in two different places.

It also appears that the commerce_discount module is incompatible with default configuration of commerce_account_balance. No matter how a coupon code is applied or how much of the total it supposedly reduced, it still requested a downpayment to cover the total (undiscounted) balance. It's likely this could be fixed by changing the order that the rules are executed so that the discount is run before the balance is checked.


Importing shapefiles/kml I need to add support for importing either kml file or shapefiles, preferably using feeds.  The idea is that each record relates to a single node, and the file uploaded could contain hundreds of new nodes.  I've tried Spatial Tools, but the feeds import only works in Drupal 6.  I've also tried GDAL, but it requires the php gdal extension, which has to be compiled.  I'm using windows (not by choice!) and don't have easy access to the compiler and tools necessary, so this is not really an option.  Does anyone know of a way to get either of these to work, or if there is a better way to support importing spatial data?

Not sure but this might help: https://drupal.org/node/1980360 - Importing KML file data into GeoField field instance


Upgrading Drush 6 to Drush 9 on Centos 5 server I haven't updated drush in awhile and looking to update it to the latest. I'm not exactly sure how it was installed originally. But when I do a which drush, it shows it resides in /usr/bin/drush

When I do a drush dl drush - I only get the option to upgrade to 7.x only.

How can I update it to Drush 9?

Can I just do a git clone of the drush repo from: https://github.com/drush-ops/drush

Then do I just do a checkout of the drush 9 tag? But how do I make it the default drush application to run? Or do I just overwrite the file in /usr/bin/drush?

FYI: My linux server admin skills aren't up to par.

drush dl drush downloads the obsolete version of Drush from drupal.org. Drush was never intended to be used to download Drush via the pm-download command, even when it was hosted on drupal.org; the fact that this works is more of an anomaly or coincidence than design.

To update to a newer Drush, follow the usual instructions in the Drush documentation.  Since you already have Drush in usr/bin/drush, use this location instead of the location stipulated in the docs (usr/local/bin/drush).

wget http://files.drush.org/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/bin/drush

The Drush at files.drush.org/drush.phar is always the most recent stable version of Drush. To download a specific version, visit https://github.com/drush-ops/drush/releases. There is a phar available with every release of Drush from version 8 and later.  You can, of course, replace your /usr/bin/drush at any time that you need to upgrade.


How to have a proper alphabetic pager with number support? I'm trying to achieve an alphabetic pager with grouping of special characters + numbers.

All pagers available do 0|1|8|9|A|B|C, while I want 0-9|A|B|C or #|A|B|C, # being for special characters and numbers.

To illustrate it better, here is what I'm trying to achieve:

I'm using Drupal 6 and views 6.x-2.12.

I already searched a lot for this, and also tried asking here at http://drupal.org/node/908716, but I did not have success.

I don't mind solving this with "hackish" methods, but I'm not being able to come up with one of those.

Thank you, in advance.

I recently started putting together a blog post showing how I did exactly this a few months ago using a custom module to create a new filter handler for views. I finished it up and posted here: http://garandwebtech.com/blog/2011/creating-alphabetical-filter-numeric-category-drupal-views-using-custom-filter-handler

Once you set up the new filter you just need to link # to pass the right parameter.


Where does $rows come from in views? Let's say I have a simplest "unformated list" view.

I see that "views-view-unformatted.tpl.php" is outputting $rows in a loop.

When I open my view page on a browser, I see that the following codes are generated by $row.

test1

What template can I edit to remove anchor part?

Non need to edit template in this case.
Just edit title field and uncheck "Link this field to the original piece of content" option.


How can I load a menu programmatically with an active trail set by a provided URL? Working on a headless Drupal site, and have come across an issue. We have a REST resource that returns arbitrary menus by menu-id, however they always have "active-trail" set to false on every menu item.

I'd like to be able to specify a URL or route when building the menu and have the active-trail be equivalent to what it would be if the menu was loaded on that route.

At the moment our solution is to loop through every menu item until we find one that corresponds to the provided URL, and then mark it and all its parents as "active-trail", however this seems unnecessarily cumbersome and I'm left wondering if there's a more sensible solution we've overlooked.

Currently we're loading menus like this:

$tree = $this->menuTree->load('menu_id', new MenuTreeParameters());

Where $this->menuTree is an instance of MenuLinkTree being instantiated via Dependency Injection:

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, MenuLinkTreeInterface $menu_tree, EntityTypeManagerInterface $entity_type_manager, Request $current_request) {
  parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

  $this->menuTree = $menu_tree;
  $this->entityTypeManager = $entity_type_manager;
  $this->request = $current_request;
  $this->alias = $this->request->query->get('alias');
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->getParameter('serializer.formats'),
    $container->get('logger.factory')->get('rest'),
    $container->get('menu.link_tree'),
    $container->get('entity_type.manager'),
    $container->get('request_stack')->getCurrentRequest()
  );
}

Inject the menu.active_trail dependency along with menu.link_tree:

private $activeTrail;

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $active_trail, EntityTypeManagerInterface $entity_type_manager, Request $current_request) {
  parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

  $this->menuTree = $menu_tree;
  $this->activeTrail = $active_trail;
  $this->entityTypeManager = $entity_type_manager;
  $this->request = $current_request;
  $this->alias = $this->request->query->get('alias');
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->getParameter('serializer.formats'),
    $container->get('logger.factory')->get('rest'),
    $container->get('menu.link_tree'),
    $container->get('menu.active_trail'),
    $container->get('entity_type.manager'),
    $container->get('request_stack')->getCurrentRequest()
  );
}

Now instead of:

$tree = $this->menuTree->load('menu_id', new MenuTreeParameters());

get the active trail ID's just before building your menu and pass it in as part of the parameters:

// Change this to menu machine name.
$menu_id = 'menu_id';

// This should return an array.
// Array contains menu link uuid's, keyed by the uuid's iirc.
// For example something like:
//   'menu_link:abcdefg_123' => 'menu_link:abcdefg_123'
$activeTrailIds = $this->activeTrail->getActiveTrailIds($menu_id);

$params = new MenuTreeParameters();
$params->setActiveTrail($activeTrailIds);
$tree = $this->menuTree->load($menu_id, $params);

This should return you a menu tree with correct active trails.


Best database collation for multilanguage site I’m running a  Multilanguage site (drupal 6) using  both: Latin language and  a no-Latin language characters.

Before the install. I used  phpmyadmin,  to change the default MySQL connection collation, from latin1_swedish_ci  to utf8_general_ci.
wondering if I'm doing things right? Or should I leave the  default MySQL  collation in latin1_swedish_ci ?

utf8_general_ci is preferred over latin1_swedish_ci

The good news is that as a result of this issue Drupal now defaults to utf8 so no one should have to worry about this any longer. This fix has been backported to Drupal 6 so this answer should be applicable to Drupal 6, 7, and 8 (when it is released).


How to filter a view according to nodes permissions I would like my view to not display nodes to which the current user does not have access to.

I have implemented hook_permission "access nodes of type mytype"

I have also implemented hook_node_access this way:

function mymodule_node_access( $node, $op, $account)
{

   if ($op == 'create')
    {
     $type = $node;
    }

   else
   {

    switch($node->type)
    {
      case "mytype":
        if ( !user_access("access nodes of type mytype") )
         {return NODE_ACCESS_DENY;}
        break;
    }

   }

 return NODE_ACCESS_IGNORE;
}

I set up the view to displays only nodes of type "mytype".
When a user who does not have the permission "access nodes of type mytype" clicks on a link in the rows of the view, he gets the page "access denied" which is what I want.
But I also want the view to not display the nodes of type "mytype" if a user does not have the permission to "access nodes of type mytype".

How do I implement that?

Thanks,

Baba

The correct answer is actually here.

  It seems that a better way to control node access is through hook_node_access_records and hook_node_grants as described here http://drupal.org/node/1260948. This works with views properly.


set multiple taxonomy values programmatically I have a view that has a "Has taxonomy term ID" contextual filter and also a nid contextual  filter.

I execute this view programmatically, but I need to pass also multiple values for the taxonomy contextual filter.

I tried this:

$view->set_arguments(array($tid, $nid));
$view->execute();

and it works only if $tid is only a number.

I tried to put more than one tid using "+", but it doesn't work.
(example 3+5+8)

Any idea on how I can set a multiple taxonomy argument programmatically?
thank you in advance

I found a solution, but I don't like it. I removed the filter from contextual filter and I added an exposed filter for the same field. Then I changed the code in this way:

$view->set_arguments(array($nid));
$view->exposed_input['field_myfield_tid'] = $tid;  //note that $tid is an array of tid
$view->execute();

You could also implement the "hook_views_pre_view" function in order to alter the contextual filter arguments of your view and display. In order to add multiple taxonomy values for the same argument, you can change the $args[0] element from the $args variable of the hook.
For example: $args[0] = '22+14+64';
Remember to check the "Allow multiple values" option of the contextual filter.

Take into account that altering contextual filter arguments inside the previous hook may produce troubles when using a views exposed form. Specifically, the form "action" attribute may have a wrong URL. If that issue appears, you can solve it by implementing the "hook_form_views_exposed_form_alter" function and changing the $form['#action'] element with the correct URL.


Drupal 6 as a call logging system - question about node performance & scalability We currently use Drupal as a Knowledge, communications and assessments system for our call centre agents and it is working great. However there has been a request that this to also handle our call logging.

We utilise profiles to allow manager roles to check their team members assessment scores and what communications they have read, the idea is that they could also do the same with calls taken.

My concern here is that this will dramatically increase the number of nodes from what we have now (articles, comms etc are all created by our team so nodes will be within the 1000's).

If we employ Drupal for logging calls this would mean that our 1000's of agents would be creating dozens of call logs per day. This potentially would push nodes up into the 1000000's.

Would Drupal and its node / cck be able to cope with this type of load where 1000's of users would be submitting dozens of nodes simultaneously?

This is quite a subjective question. Your best bet would be to ask on some of the Drupal groups that handle this stuff like Drupal High Performance.

There are so many factors in making a drupal site scale it's hard to list them all.

Pressflow is a drupal distro that is built for scaling, they also have some great blog articles on scaling.


Attach a webform into faq module content I'm looking for a FAQ module where users can answer the "Did you find this answer useful? Yes-No" after reading help and I need a page where operators can check all responses.

Any idea?

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

  The Frequently Asked Questions (faq) module allows users, with
  appropriate permissions, to create question and answer pairs which
  they want displayed on the 'faq' page. The 'faq' page is automatically
  generated from the FAQ nodes configured. Basic Views layouts are also
  provided and can be customised via the Views UI (rather than via the
  module settings page)

.


Removing divs added by render and node.tpl.php I'm trying to build an HTML5 template for Drupal 7, and I'm quite particular about clean code. I want full control over the HTML and CSS which for the most part I get using my own custom theme. In other words I have an HTML5 and CSS set I want to use exactly as is in Drupal. I'm not too clued up on how the whole pre-process function thing works.

When I use 'print render($page['content'])' in my page.tpl.php file it adds

And then when I add 'print render($content)' in the node--custom.tpl.php it adds

I don't want any of these divs. How do I get rid of them?

The div ids and classes you see inside $page['content'] comes from region.tpl.php > block.tpl.php > node.tpl.php
Drupal content passes through these template files, each step adds some divs.

Step One

region.tpl.php file contains  the code as follows

       <?php if ($content): ?>
  <div class="<?php print $classes; ?>">
    <?php print $content; ?>

<?php endif; ?>

now if you make changes in this file it will effect all the regions of your page. If you want to control only the content area, create a new file name it region--content.tpl.php in that file paste only

<?php if ($content): ?>

    <?php print $content; ?>

<?php endif; ?>

This will get rid of div created for only content region.

Step Two

Make a copy (if we make changes in block.tpl.php all the blocks will be effected) of block.tpl.php and name it block--content.tpl.php and remove or change the divs. Without the divs the file will contain the following code to output content.

<?php print render($title_prefix); ?>
    <?php if ($block->subject): ?>
      <h2 class="block-title"<?php print $title_attributes; ?>><?php print $block->subject ?>

    <?php endif;?>
      <?php print render($title_suffix); ?>
      <?php print $content; ?>

This will get rid of div created by bock.tpl.php

Step Three

Now edit the node.tpl.php file to remove or change the divs. Without the divs the file will contain the following code to output content.

          >">

    <?php print $user_picture; ?>

    <?php if ($display_submitted): ?>
      <?php print $date; ?> — <?php print $name; ?>
    <?php endif; ?>

        <?php
          // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
       ?>

    <?php if (!empty($content['links']['terms'])): ?>
      <?php print render($content['links']['terms']); ?>
    <?php endif;?>

    <?php if (!empty($content['links'])): ?>
        <?php print render($content['links']); ?>
      <?php endif; ?>

<?php print render($content['comments']); ?>

This will get rid of all div and classes. Now you can wrap the content with your own divs.  Please let me know if it works for you.


How to auto-insert a sequence number in a Webform? Is there a way to add a Webform field that serves a unique sequence number? Hopefully the number can be sequentially counted for each Webform type.

There is a module for this: Webform Serial number:
https://drupal.org/project/webform_serial

  This module provides an auto-incrementing number field for webforms.


How do I remove classless divs around my paragraphs? Using stable as a base theme, I'm building a theme that will provide styles for paragraph items.

The default output (without any templates affecting this area) seems weird to me, though. Take a look at this simplified version (stripped of data--classes):

As you can see, the wrapping element around all paragraphs, as well as the element wrapping each paragraph lack any classes and are therefore quite useless. Furthermore, for the indivudual paragraph, another div inside them has a class that would actually be useful, but it's too far down the document hierarchy to be actually useful in styling.

Attempting to remedy this by myself by modifying paragraph.html.twig, I can get to the div currently holding the .paragraph class, but nothing above that.

I assume all has it's purpose, but I also think this is a weird default behavior, as there is no apparent need for two nested divs for each individual paragraph in any normal use case. Am I missing something?

In the theme stable the field twig has two div's, one overall and one for each item. This would match what you have provided as html markup.

So this should work, copy field.html.twig from stable to field--entity-reference-revisions.html.twig in your theme and remove the div's from there.

That the div's are useless is not correct for all circumstances, because there may be different configurations or modules, which use the attributes of the div's. So if you remove them, you might loose some of that functionality.


Cannot access $node on Computed field I'm using computed field for my content types, but when I used $node, in Display Code, it doesn't display anything :

global $node;
$display_output = l("Apply", "apply_form?job_offer=".$node->nid);

First of all, you are supposed to write to $entity_field[0]['value']. Second problem is that fields operate on entities, not nodes, so you need to use $entity instead. You can always use Devel module and dpr($entity) to see what's in it.

node id should be in the entity field if it is a node. In which case you can load it with node_load().


Webform does not submit when a file field is added I have a single page webform with a bunch of fields (text field, radio buttons, etc) that works fine. As soon as I add a file upload field it stops working:

when submitted, the form returns with all the fields still filled in
there are no validation messages of any kind

I've littered webform.module with lines of print statements and it appears that webform_client_form_validate and webform_client_form_submit are never called at all. I suspect some module may be altering my form because it picks up the file field somehow.

All webform related modules have been disabled.

I suspect I'm having a similar problem this question describes: Webform does not submit, instead redirects to self . The suggested solutions are rather vague though, and I'm not sure how to proceed.

I discovered the issue: I had added a script to my theme to prevent double form submissions: a simple "if the submit button is clicked, disable submit buttons in the form" jquery script.

This script prevented the submit button of the field field from being activated at the same time the main submit button was pressed. This confused Drupal to a sufficient degree that nothing worked anymore.

I fixed it by wrapping the disabling of submit buttons in a window.setTimeout(function yada yada ... , 50).


The EU Cookie Compliance module doesn't display the message I just downloaded the EU Cookie Compilance module 8.x-1.0-beta4 and the legal message doesn't show in my page.

First, I configured the module, and then set the Display EU Cookie Compliance popup permission for the anonymous user, but the message doesn't appear.

Why? What do I need to do to make it appear?

I have tried it in d6 and d7 and had similar problems in bringing it up for the first time, it showed after enabling the module, setting the permissions to anonymous user, logging out and deleting all cookies from my domain, alternatively using an anonymous browser window. So it might be that you have the cookie already.


Add link for each column I'm working on tripal with drupal 7.x
I have created new view. i had chosen the fields and i have this table.

i want to add the link for each row of the column map Name. i put this tag
but i want to change the ID (85) for each row it correspondd to the ID of the map. How can i do? Thank you

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

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

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

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

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

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

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

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

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

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


How do I update HTML content We have a website that is linked to a drupal database. I need to update some HTML text and could not find the file on our server but did find the content in two tables in the drupal DB: dbo.field_data_body and dbo.filed_revision.

I made the change in the db but this has not been relayed to the site.

Please advise

Thank you,
Kai

I do not have admin access to drupal API but have access to the DB and IIS. I assumed that the content from these tables would export into an editable markup file but this does not appear to be the case. Can i do this without the drupal API?

Kai


Conditionaly display fields of another node on a node page I am a Drupal beginner, have some CMS and PHP knowledge. I am strugling with a case which intuitively seems like a thing that had to be been solved many times.

I have these content type:

Product with 2 fields description and company.
Company with various fields but the ones that matter here are company_intro, company_address.

When I create a product page, I fill in the description and choose a company from a list. When I present the product page to the user, I want it to start with "company_intro" from the selected company, followed by the description and ending with the address.

Is that possible?

At first you need to make a relation between Product and Company . to do that you have to install a reference module , Entity References or References .
After enabling the module (No different which one you install) you need to modify your product content type , remove your company field and add a new field of type reference to a node , then refer it to your Content type Company .

till now you have made a relation between Product and Company , now to do the rest of the job you can use Panels and Page Manager (included in CTools) .

Check this tutorial if you are not familiar with panels : Learning Panels and Page Manger


How to split Webform in multi menus/tabs? Is it possible to split my webform into several menus/tab?
Note: aim is not to obtain a multi step webform but a webform with several sections reachable easily by selecting a tab.

There's the Webform Navigation module which allows you to let users navigate back and forth between steps of a multi-step form via the progress bar. How you design these steps in the progress bar is up to you. If you want them look like tabs, style the steps to look like tabs. That's all.

The goal of this module is to provide the ability to navigate forward
and backward through a web form using the Webform Progress tracker
(aka wizard progress bar) supplied by the webform module on multi-page
web forms. It also allows for the ability to bypass validation when
the user presses the "next" button as they navigate through the form.

Alternatively use collapsible fieldsets to contain sections of your webform.


What's the equivalent of cache_clear_all()? What's the equivalent of cache_clear_all() in Drupal 8?

You can use Cache api. It would be somthing like

\Drupal::cache('bin')->invalidateAll();

Or if you want to remove the entries and not just invalidate them:

\Drupal::cache('bin')->delete('variables')

where bin is a valid cache bin such as menu, render, page ...etc.


"No Drupal site found" -- Windows and SQL Server So I'm trying to upgrade our system from using Drush 6 to Drush 8, as that is the currently supported version of Drush that supports Drupal 7. I have managed to get drush working, however it does not recognize any of our environments as a Drupal environment.
If I run drush cc all I get back:

No Drupal site found, only 'drush' cache was cleared.

If I run any other Drush command (from my sites directory) I get back:

Command 'command' needs a higher bootstrap level to run.

Running drush status returns no DB information at all.
Now there seems to be quite a few questions out there like this, and lots of recommended solutions, but nothing is pertinent to my environment. I'm using IIS on a Windows Server machine, with SQL Server (not MySQL), so none of the solutions are applicable. I'm wondering if anyone has any ideas for solving this within my current environment?

Keeping in mind, all of these environments worked fine with no issue prior to upgrading to Drush 8 (using Drush 6).
Output of drush -v status:
Loading outputformat engine.                                 [notice]
 PHP configuration      :  "C:\Program Files (x86)\PHP\5.6.26\php.ini"
 PHP OS                 :  WINNT
 Drush script           :  location/of/drush
 Drush version          :  8.1.13
 Drush temp directory   :  temp/location
 Drush configuration    :
 Drush alias files      :
Command dispatch complete                                    [notice]

settings.php file database settings:
$databases['default']['default'] = array(
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'hostName',
  'driver' => 'sqlsrv',
);

Executing drush sql-connect command returns:

Unable to load class Drush\Sql\Sql.
Unable to find matching SQL Class.
Drush cannot find your database connection details.

I should also mention that drush site-install works fine, it's just running Drush inside a newly created area that doesn't work.

To clarify, I am using a multi-tenant install, so I have multiple tenants such as sites/tenant, sites/tenant2, sites/tenant3, etc.
For example I am running drush from the sites/tenant directory and Drush doesn't recognise my Drupal installation. Traditionally, before updating, I could run drush from inside any of those and everything would work.

You should perform the following checks:

For SQL Server, review README file of SQL Server driver for Drupal 7 to confirm the right requirements and installation steps. See also: Can I use MS SQL with Drupal.
Make sure that your database client (such as sqlcmd) command exists globally (from the command-line). Otherwise make sure its path is added into your PATH system variable. See: Sqlsqlsrv.php.
Clear Drush internal caches and try again:

drush cc drush

If you're using a multisite environment, make sure to specify the right Drupal site to use, e.g.

drush --uri=http://site1.example.com status

or:

drush -l http://site2.example.com status

Note: By default Drush uses sites/default unless you will run the command in specific sites/ folder.

Note: To define URI of the Drupal site, set $base_url in your settings file per given site (or drushrc.php).
Run drush status (add -d for debugging output) to check whether Drupal root, Database name and Database driver has been detected correctly. If not, run the command again, but in the same folder where is your settings.php file and verify that Drupal Settings File has been recognized. Verify it has the right read permissions
Check the output of drush sql-connect command whether it returns the right command and there are no errors.

If there is no matching SQL Class, this suggests drush can't detect the db driver from your settings file. So confirm the following command returns the current site path (folder containing settings.php):

drush ev "echo drush_site_path();"

If it's empty, make sure you're running drush command in the right folder and your settings.php exists.
Check whether Drupal bootstrap object is properly loaded by:

drush ev "print_r(drush_get_bootstrap_object());"

If so, check whether your settings file is readable:

drush ev 'echo file_get_contents(drush_get_bootstrap_object()->conf_path()."/settings.php");

Otherwise if your bootstrap object is EmptyBoot, please review how Drush defines Drupal root as valid (candidates are: DrupalBoot6, DrupalBoot7, DrupalBoot8), for Drupal 7 the logic is as below:

function valid_root($path) {
  if (!empty($path) && is_dir($path) && file_exists($path . '/index.php')) {
    // Drupal 7 root.
    // We check for the presence of 'modules/field/field.module' to differentiate this from a D6 site
    $candidate = 'includes/common.inc';
    if (file_exists($path . '/' . $candidate) && file_exists($path . '/misc/drupal.js') && file_exists($path . '/modules/field/field.module')) {
      return $candidate;
    }
  }
}

So make sure that you've the following files present: includes/common.inc, misc/drupal.js and modules/field/field.module in your Drupal root (where $path is your Drupal root, but it can be specified manually by --root=path/to/drupal). Also make sure the files are readable by the user (in case of symlinks, they're pointing to the right files; right permissions in case of network share or Linux file system). Otherwise edit Drupal boot class file (e.g. DrupalBoot7.php, part of Drush) and try to debug the above valid_root() method by checking which condition exactly fails and why.

Example Drush command to verify whether index.php exists:

drush ev '$path = drush_get_context("DRUSH_SELECTED_DRUPAL_ROOT"); var_dump(file_exists($path . "/index.php"));'

Finally check whether SQL class can be loaded by:

drush ev 'var_dump(drush_sql_get_class());'

You may consider re-testing in different PHP versions, e.g.

Debugging

Assuming drush status doesn't return the right details, here are the suggested steps to debug drush (shell commands).

Install and enable PHP xdebug extension. Verify by php71 -i | grep xdebug.

Consider these xdebug ini settings: xdebug.ini for better visibility.
On empty folder, install clean Drupal, e.g.

drush -y qd --no-server --core=drupal-8
cd quick-drupal-*/drupal*

Verify Drupal root, Settings File and Database are present in drush status.
Generate trace file for the working bootstrap process:

drush ev "xdebug_start_trace(); print_r(_core_site_status_table()); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

If xdebug is enabled for different PHP version, specify with DRUSH_PHP=/path/to/php.

If successful, trace output file should be printed at the end, so take a note of it.
Generate another trace file for the same command above, but in the location which doesn't work.
Now compare these two trace files (working with non-working) using some diff tool (Meld, DiffMerge, opendiff, etc.) and check the differences. For better format, remove first 40 columns from these files (e.g. ex +'%norm 40dl' -scwq file.xt).

If you believe you found a Drush bug, please report it with details at GitHub issue page.


theme content type with image from within paragraph I'm trying to create a twig layout for a Person content type that is be used within Paragraphs.
My twig file is paragraph--person-profile--default.html.twig.

I can get the Person name with {{ content.field_person[0]['#node'].title.0.value }}

I cannot get the image. I've tried the following:

{{ content.field_person[0]['#node'].field_image.0.value }}

and {{ content.field_person[0]['#node'].field_image.0 }}

The following error is reported.

  Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter()

The end game is to have a taxonomy term and a person content type within a paragraph type. The taxonomy term will be used to to style the person.
The same person may be styled differently on different pages.

To get the url from an image field you have to go one level deeper, .entity gets the file entity where the URI of the image is stored:

{{ file_url(content.field_person[0]['#node'].field_image.0.entity.uri.value) }}

But digging through multiple levels of nested entities is not good practice, because this produces code hard to debug and maintain. You should look for a  better place to theme the image, for example node--person.html.twig, where you can print the image field, formatted how it is configured in UI:

{{ content.field_image }}


Node access depending on boolean field in user profile I would like to control access to specific articles or categories of articles depending on a boolean variable in a user's profile.

For example, this would be on a site where a user gets access to all kinds of data about their product after they purchase it. I would like to manually enable or "tick" a boolean field on their profile which then allows them to see the corresponding information when they browse the website.

I hope you understand what I'm trying to say.

I have already set up a few fields on the user profiles and I'm trying to make it work using the Rules and Content Access modules but I'm not sure if I'm heading in the right direction. I have thought about just setting this up with a "View" but I think the content would still be accessible to everyone by default if they have a link or through Google?

If someone could point me in the right direction, that would be great.
Thanks in advance!

I got it working, for the sake of anyone ever needing this functionality and stumbling upon this thread:

You'll need the Access Control and ACL modules. The combination of these allows you to set "per user" access for each individual node. For the checkboxes on a profile or page, you'll need to use the Entity Reference module and create a field on the profiles for that type of content. You can then set that field up as checkboxes.

For the final part, you'll need the Rules module and set up two rules: one to "Grant Access per user" and grant view access when a specific value of the checkboxes is true and one to "Revoke Access per user" when values have changed. You'll need to play around with the rule's conditions to make it suit your needs.


IE8 is detecting the pages as mobile media I am trying to workout why http://www.tradecarsspain.com/ is loading as a mobile page when viewed in IE8 ...

As you haven't provided any information this is a complete guess, based on the assumption that you're using the Omega 3 theme with respond.js.

There's a known issue with IE8, respond.js and CSS aggregation. To fix it, you can implement hook_css_alter() in your theme like so:

function MYTHEME_css_alter(&$css) {
  // Enable respond.js to work with Omega.
  foreach ($css as $key => $value) {
    if (preg_match('/^ie::(\S*)/', $key)) {
      unset($css[$key]);
    }
    else {
      $css[$key]['browsers']['IE'] = TRUE;
    }
  }
}


How to block users to accessing Drupal website if javascript is not enabled? I checked many pages in Drupal Answers, which didn't have the answer of the following question:

Consider a case that I need javascript to be enabled for visual effects in drupal design.

How can I stop my website and show a message , if javascript is not enabled in user's browser?

Stop means to block the access of user to the website and showing a message like:

Please enable JS in your browser!

(I use Drupal 7.x)

It is not possible, not in the way you think of. Workflow is:

Server gets HTTP request.
Drupal process that request and returns HTML.
Browser runs JavaScript, or does not.

As you can see, server never knows if JS is there. If JS is on, you can send AJAX request, but if it's not, you can't do anything at this point.

You have three options:

Graceful degradation - this is what I would recommend. Use modules and write code that will simply not fail if JS is not there. It may look differently, that's OK, but should look good and work all right. I recommend these articles: Fault tolerance, Unobtrusive JavaScript
Use HTML <noscript> tag. It will not hide the rest of your site, but it will tell your users what is happening. This method can be used together with 1st one. Related Q&A: How to Add noscript in head tag (Thanks Wtower for link)
Output a page with "Please enable JS in your browser!" message and immediately load real content with AJAX. That's the only way I can think of to make your site work like you want it to, but it is so wrong, on so many levels... Remember, some bots may be unable to index your page if you don't have JS enabled, your users with JS on would see message while waiting for real content anyway, and so on. And while Google can read JS-generated content now, Bing and other search engines apparently still cannot.


Change user roles based on profile field I have an field role_type with values - 0,1,2...

And I need to add role X to all users who have role_type = 2?

How can I do that? Rules? SQL?

Thanks for your help.

I think you could write a little module.

db_select() all users with that role_type entry
user_load() them and user_save() them with updated $user->roles[]

Maybe this thread HOWTO assign a user to a role programatically on drupal.org can give you a deeper insight.