how to retrieve password from within hook_user_presave() I am trying to catch the inputed password on the user registration page from within the hook_user_presave(). I want to send this password out to an external database for storage. However, when I analyzed the $edit variable, I found that the password field was returning an encrypted password.

Is there any way for me to retrieve the actual password?

It us not advised not to use the user's password as a raw value, however if you still want to access the password field value in unencrypted form than try the following:

<?php
/**
 * Implements hook_form_alter().
 * Alters user_register_form.
 */
function MyModule_form_alter(&$form, $form_state, $form_id) {
  // Add the additional validation callback for the user registration form.
  if ($form_id == 'user_register_form') {
    $form['#validate'][] = 'MyModule_user_register_form_validate';
  }
}

// Callback function for Validation handler of user_register_form.
function MyModule_user_register_form_validate($form, &$form_state) {
  if (isset($form_state['values']['pass'])) {
    // Here you will get the value of password.
    $password = $form_state['values']['pass'];
  }
}
?>


Suggested way to setup drupal to handle multiple subsites / subdomains? Looking for some examples of folks successfully using Drupal on multiple subdomains. Is there a good way to go about using a single drupal install to manage multiple subsites like so:

Siteone.domain.com
Sitetwo.domain.com
Sitethree.domain.com

Etc….

All of these subsites have separate information, but some of it could be related here and there, so having it available to each subsite would be a benefit... thinking Entities here I suppose. One database and one core to update would be ideal. Any issues with setting it up? Problems with content types or entities?

I've seen:

http://www.aegirproject.org/ However, this is multiple drupal sites as far as I can see...
https://www.drupal.org/project/domain This seems like a near perfect fit. Anyone successfully utilizing this?

Have you considered using the multisite setup?

  This is particularly useful for managing the code since each upgrade
  only needs to be done once. Each site will have its own database and
  its own configuration settings, so each site will have its own
  content, settings, enabled modules, and enabled theme. However, the
  sites are sharing a code base and web document root, so there may be
  security concerns with multiple administrators

I've used this for setting up one codebase and then creating multisite installs of the codebase for clients who want similar websites. Multisites can be done as either subdomains (ie subdomain.domain.com) or subsites (ie domain.com/subsite). Each multisite install has its own database, and can have its own modules or theme even, but if there is core functionality you can put it in the root codebase and it will be shared across all multisites.


duplicate order_number in commerce/orders I have a shop implement with drupal commerce, I have a problem, I have 2 method on payment method1 and method2,
in payment step, when user select method1 and go to bank to pay,it has a order record in commerce/orders , when the payment with method1 not  successful in commerce/orders  ,status is processing, after payment with method1 not successful drupal come back to payment step and if user select method2  I see another record with same order_number in commerce/orders,
The problem is here when the  user accomplish payment with method2 ,  the 2 record status field will set to "completed" and manager of site dont understand finally by which method payment finished,

anybody know where is the problem and how can correct it?

Finally I found the solution for my problem, the problem came from relation of views to product_order table, I just go to that views and revert views.
and worked


Download post as text file I wanted to provide functionality in which where user decides to cancel his account, he can download all the post that he has created as txt file. Is there any drupal module that helps to achieve this, or at-least that allows to export node as txt file in Drupal 7.

I have gone through Print module, but it does not support txt file and I can not use PDF option, as this will take long time to generate PDF of all usaer created node upon cancellation of account.

Please suggest how can I proceed.

-- Many thanks for your time.

try the views_data_export ....  it can export to CSV or basic text format. and you could select a users Nodes: title and body at least ... and any other fields you want...

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV

  Microsoft XLS

  Microsoft DOC

  Basic TXT

  XML


Conditional Flags in Panels I have created two flags using the Flag module and they are placed on my custom content type, 'Challenge'. Both the flags can only be flagged but not unflagged. The first flag is "Accept". The second flag is "Complete". These two flags i have created normally through the UI. However to display them in panels, i have used the following code in a custom text area in panel as flags are not displayed automatically there.

<?php
   print flag_create_link('flag1', %node:nid);
?>

<?php
  print flag_create_link('flag2',%node:nid);
   ?>

This displays both the flag on my Panel Page. However, my use case is something different. At first only, the "Accept" flag should be visible. Then, when the user clicks on "Accept", then only the other flag, "Complete" should appear. Any hints on how to achieve this. I have also tried using Rules, giving the event: A node has been flagged and then the action for a new flag. It does not work. Then i tried using flag actions as well, i.e., on flagging of first flag, display another flag.It does not work. Any ideas, suggestions are appreciated.

Thanks

Edit

i thought of a way to do this using JavaScript and css. When the first flag is visible, the second wont show. The code i am using is :

if($("#accept-flag").is(":visible")){
    $("#complete-flag").css('display','none');

This i have placed inside js/script.js in my theme folder.

(function ($, Drupal, window, document, undefined) {

if($("#accept-flag").is(":visible")){
    $("#complete-flag").css('display','none');
}

})(jQuery, Drupal, this, this.document);

When i view the page source, the script is loading however both the flags are still showing.

Please advice

Thanks again

Since you are using Panels, you could create two variants. One of them would have a selection rule that says only select this variant if "accept" is flagged, and in it your display only the complete flag. The other variant wouldn't need selection rules (but would need to be placed under the first one in the variants order) and it would display only the complete flag.


dpm does not display form return values I just enabled the devel module on Drupal 6 and using dpm($form) was showing values for me but  it does not show values any more. What would mostly the issue here? Is there a way to see those values?

Thanks

In say a validation function, to see both the $form structure and what the user has entered, use a devel debug statement like:

dpm(array('$form' => $form, '$form_state' => $form_state), "Validation debug");

The $form_state['values'] array will contain the raw user entries you can then access and validate.


How to autofill webform from GET vars? I need to make a form that autofills itself with some values that I give from the GET or POST params

I have an emailing that is personalized for each user so when they click on a link or a submit form they will view that webform autorefilled with their data

I'm using Drupal 6.19 and Webform 6.x-3.4

Webform has GET support built-in, see: Setting Default Values from the URL.

For POST you have access to %post[key] or you can retrieve $_POST and set your values using hook_form_alter().

  Webform allows several special values to be used as defaults when
  configuring a component. The special placeholders are commonly called
  tokens. The tokens Webform supports include:
  %username
  %useremail
  %site
  %date
  %server[key]
  %session[key]
  %get[key]
  %post[key]
  %request[key]
  %profile[key]

Working with Default Values


How do I set the value of a date and time field with Behat? I am trying to test my site with Behat.
On my entity edit form, I have a Datetime field that uses the Date and time widget.  I want to use the Date and time widget because I need to set the time in increments of seconds, which I cannot do with the Select list widget.
I want to set the value of this field with a step like this:
And I assign the date "yesterday" with timezone "Asia/Tokyo" for "edit-field-datetime-MYFIELD-0-value"

To do so, in FeatureContext.php, I wrote the following code.
  /**
   * @Then I assign the date :date with timezone :timezone for :field
   *
   * Assign the specified date to the element with the given CSS.
   */
  public function assertEnterDateForField($field, $timezone, $date_string) {
    $date_field = $field . '-date';
    $time_field = $field . '-time';
    // Drupal stores timezones as UTC so we need the base time in UTC.
    $datetime = new DateTime($date_string, timezone_open('UTC'));
    // We need to convert the UTC time to the user's timezone.
    // This is because when saving the entity,
    // Drupal will convert the value to UTC.
    $datetime->setTimezone(timezone_open($timezone));
    $date_output_string = $datetime->format('mdY');
    $time_output_string = $datetime->format('hisA');
    $datetime_debug_string = $datetime->format('Y-m-d\TH:i:sO');
    $this->fillfield($time_field, $time_output_string);
    $this->fillField($date_field, $date_output_string);
    echo "Datetime $datetime_debug_string
    Field set to
    date: $date_output_string
    time: $time_output_string";
  }

On my local environment (lando, running the Standalone Chrome container), this code works as expected; the date/time is set correctly for the field.
However, on my test server (Pantheon/CircleCI, running the Behat Chrome Extension, it doesn't work.  The debug information is correct; for example:
  │ Datetime 2020-08-13T09:00:00+0900
  │     Field set to
  │     date: 08132020
  │     time: 090000AM

However, the date/time is not actually filled in, so when the entity is saved, the date/time has not been updated.
How can I set the value of a field that uses the Date and time widget with Behat/Mink/Drupal Extension?

I haven't been able to find a way to do this, so for now, I rewrote my CI configuration so that I can use Standalone Chrome with Pantheon/CircleCI instead of the Behat Chrome Extension.


How to display multiple default items for field collection with unlimited cardinality? I have used following code and it works fine i.e 3 items are displayed, but the issue in my code is add another item button remains inactive on click.

<?php

function two_form_alter(&$form, $form_state, $form_id) {

  if($form_id == 'product_culinary_node_form') {
    $field_language = $form['field_tabs']['#language'];
    $items_count = 3;

    $field_name = 'field_tabs';
    $form_theme = $form[$field_name][$field_language]['#theme'];

    // Remove delete and add more buttons
    // $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
    $form[$field_name][$field_language]['add_more']['#access'] = TRUE;

    $items = &$form_state['field'][$field_name][$field_language];

    // Generate required number of fields collection
    if ($items_count > 1 && $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;

      // $items['field']['cardinality'] = $items_count;
      $wrapper = $form[$field_name][$field_language]['add_more']['#ajax']['wrapper'];
      $field_parents = $form[$field_name][$field_language]['#field_parents'];
      $language = $form[$field_name][$field_language]['#language'];
      $after_build = $form[$field_name][$field_language]['#after_build'];
      $form[$field_name][$field_language] = field_multiple_value_form($items['field'], $items['instance'], $field_language, array(), $form, $form_state);
      // Reset theme function, as field_multiple_value_form hijacks it
      $form[$field_name][$field_language]['#theme'] = $form_theme;
      $form[$field_name][$field_language]['#after_build'] = $after_build;
      $form[$field_name][$field_language]['#language'] = $language;
      $form[$field_name][$field_language]['#field_parents'] = $field_parents;
      $form[$field_name][$field_language]['add_more']['#ajax']['wrapper'] = $wrapper;
    }
  }
}

1 solution to this is https://www.drupal.org/node/1337804#comment-6326678. I will post another solution if found without form rebuild.


How can hook some code before deleting a comment? How can I add few lines of code before comments get deleted. there must be some hook or something by which we can do this. I am getting nothing relevant by Googling.

Any help appreciated.

Strange enough, but there is no predelete hook present with Drupal 7 core, or even not provided by the entity module.

However the good news is Drupal 8 has this feature!


drupal template files in different folders for different content types I'm trying to get Drupal to scan multiple directories to find template files for pages and nodes. I have a content type called "contest". I have a node with the path of "http://mysite.com/contest/test
I'd like to have a folder structure like:

templates
    page
        page.tpl.php
        page-front.tpl.php
    node
        node.tpl.php
    contest
        contest.tpl.php
        contest-test.tpl.php

Drupal is not finding contest tpl's.

See http://drupal.org/node/1089656 for more information on the possible file names that Drupal will recognize by default.

Drupal will not recognize contest.tpl.php as it is not one of the patterns that it recognizes.  If contest.tpl.php is an override of node.tpl.php then you should name it node--contest.tpl.php

If you want to override a page template in the same manner, see this previous post: https://stackoverflow.com/questions/5194109/drupal-7-candidate-page-tpl-name-for-particular-custom-content-type-entry/5194364#5194364


Using Drupal 7 Rules, how to react to a file upload and change a node field? I have spent hours/days trying to figure out how to accomplish this in Drupal 7 using the Rules module, so I will greatly appreciate any help anyone can provide.

What I am trying to do:

When a user re-uploads a file to a node, the node should rollback from an Approved status to Pending Review. This requires some kind of automated rule that checks for when a file was updated.

Here's what I have:

A node called Data_set with a File field called data_set_file.
Data_set nodes also have a field called Status (e.g., Pending Review, Approved).

My problem:

When a user uploads and overwrites an existing attachment in the data_set_file field, I want the node's Status to change back from Approved (if already) to Pending Review. I am able to use Rules to check for when a user uploads a new file, but there are no rules conditions to check for which file or node file has been updated.

What I tried:

I created a "NOT Data Comparison" condition between node-unchanged:field-dataset-file:file:fid and (Equals/Negate) node:field-dataset-file:file:fid However, when updating the file, it did not register a change to the fid field (because it keeps the same fid). I also tried the file size field with no effect as well. When I tried the file's timestamp, it appeared to work at first until I realized that the timestamp updates every time, no matter what, that a user saves a node, regardless of whether or not a file was re-uploaded.

I may be going about this the wrong way. Anyone know what's the easiest way to accomplish this? Thanks a million!

Workflow

  This module allows you to create arbitrary Workflows, and assign them
  to Entities.

  Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).

How we use workflow module

Creating a Workflow

Editorial workflow with Rules


Drupal 7 image styles ignored by theme preprocess function I want to display images at the proper image style-defined size, but there's a problem being caused by a preprocess function written by the person who built this site before I came onto the project.

function abc_field__field_video_thumbnail($variables) {
    $output = '';

    // Render the items
    foreach ($variables['items'] as $item) {
        $output .= "
\r";
        $output .= 'field_video_width['und'][0]['value'] . '" data-popup-height="' . $variables['element']['#object']->field_video_height['und'][0]['value'] . '">';
        $output .= '' . "\r";
        $output .= '' . "\r";
        $output .= "\r\r";
        $output .= "
\r\r";
}

    // Render the top-level div
    $output = '
' . $output . '
';

    return $output;
}

This seems to assume the image style processing would occur before this function happened, but unfortunately it doesn't, and I get a full-size image regardless of image style.

By taking over the display of that field you're actually bypassing all the field system would usually do to apply the custom display settings; it basically passes off the responsibility of creating the field HTML to you, and provides you with the raw values you'll need to build it up.

So if you want to output a style based image, you'll need to do it manually using theme_image_style():

$args = array('style_name' => 'thumbnail', 'path' => $item['#item']['uri'], 'alt' => 'Alt text');
$image = theme('image_style', $args);

// Append $image to your output...


Use custom form submit function inside class In my controller I am loading a form and including one custom submit handler. However the submit function is not called. I think that it's either not found or not accessible as it is inside the controller class:

class MyController extends ControllerBase {

  //...

  public function myProfile() {
    $user = User::load($this->currentUser->id());
    $form = $this->entityFormBuilder()->getForm($user);

    $form['actions']['submit']['#submit'][] = '::_custom_submit_form';
  }

  protected function _custom_submit_form(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form_state->setRedirect('<front>');
  }

}

If I use hook_form_alter it works, but I don't want to use a hook as I can directly manipulate the form.

To understand why your code is not working, you need to understand how the form API works:

The form definition is called
Any form alter hooks are executed, altering the form
The render array is cached
The form is rendered as HTML and sent to the browser
The user submits the form
Drupal checks that the submitted values match the cached form. If values do not match, the values are rejected by Drupal's security system

When you call this code:

$form = $this->entityFormBuilder()->getForm($user);

The caching mentioned in step 3 above has already happened. So when you do this after that line of code:

$form['actions']['submit']['#submit'][] = '::_custom_submit_form';

The submit handler is never called, since the form was cached before this line of code, and therefore your submit handler does not make it into the cache.

To add a submit handler to a form, you need to implement hook_form_alter() (or a variation), which will add the handler before the caching happens. Or, you can extend the form class you are working with, add your own ::submitForm() handler, then call the parent submit from that.


Drupal 6 Views "No result behaviour" use a view With the Views module for Drupal 7 you can set a "No result behaviour" that uses another View rather than just text. I can't see the same functionality in Views 2 for Drupal 6. Is it possible to extend Views to do this?

The motivation for this is that we have a home page driven by a View that displays the recent contents from a user's groups; if the user hasn't joined any groups yet then we want to display a different View using content from all groups.

You can simulate this if you instantiate the view in code.  The general steps are

Make a custom block.
In the block view callback, instantiate and execute the view you want, but don't generate output.
Check the number of rows.  If zero, then repeat #2 with your alternate view.
Generate the output for the view, and add to the block output.
Use the block in place of the view where you need to.

If you do everything properly, all of your view templates will be used, so you aren't really losing anything.

All of the views related function are documented at drupalcontrib.org, but I think that is the Drupal 6, Views 3 version.  Googling on views_get_view will also get you started and should lead to examples of generating views with code.  If you have Advanced Help installed, you will also see some information there.

I have done something similar before, but I can't find the code.  I can remember, I will update the answer with some stubbed out code.


Is having a routing.yml file necessary? I'm new to Drupal 8, and was curious why some modules have a *-routing.yml file, while others don't.

Why is this the case? Does this mean that modules lacking in a *-routing.yml file don't have any routing URLs?

*.routing.yml is used to define custom endpoints and their receiving controllers. It's the config version for hook_menu in D8. If the module does not introduce custom paths, then it will not need one.


Change the default "Create new account" title on the User registration page I would like the change the default title (and probably also the meta title) of the User registration page, currently "Create new account".

I tried the Static and Dynamic page title method described here, as well as a couple of other suggestions, but none of them worked...

Anyone?  I added a print screen of the route (registration_link.register), the URL is user/register.

You can add the following two hooks to your theme's *.theme file or your module's *.module file. The first to alter the title that's displayed in the page title block. The second to alter the meta title.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'user.register') {

    $variables['title'] = t('New Title');
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_html(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'user.register') {

    $variables['head_title']['title'] = t('New Title');
  }
}


How do I restrain domain names of e-mails in the Drupal registration form? On the registration page, I want to restrict the domain of the e-mail adress only between a few choices (to limit the use of the site to internal company use only) through a list of choices. The user, upon registration, would therefore only have to write the characters before the @ sign ; and then choose the correct domain name he uses (for instance yahoo.fr).
The final value of the email registered by Drupal (and thus registered in the database) should be like this one: [User_entry]+[@]+[chosen_domain_name].
I found some functions to verify the e-mail spelling, but I really want users only to have the choice between shown domain names.

I've read some answers talking about hook_form_user_login_alter(), but I still don't get how I could make it...

Thks for your replies !

I'm not sure if you have any experience in PHP or custom module development but I don't have time to give you a working example.  However I will point you in the right direction.

• Create a custom module

• Use hook_form_alter to alter the form with the form id user_registration

• In your hook_form_alter add a custom validation function and ensure it is the first validation function that runs

• In your hook_form_alter unset the mail element and add two elements for the two parts of your form (the text input and the dropdown list of domains)

• In your custom validation function, use the submitted values of your form elements to create an email address and assign it to the element you unset before, mail

• Make sure that in the validation function, you don't allow users to submit blank values

Edit for a fuller answer to be added

Ok, apologies for taking my time.  This code is untested but should hopefully work for what you want to do.  First of all, try to avoid doing things like this in the theme layer.  The theme layer should be for themes only, so you want to create a custom module.

To create your module you need to create a .info file.  Alter the following code and paste it into your text editor and save it as example.info.  Remember that you can change the names of the files etc to whatever suits you, just replace the word "example" with whatever name you want to give it.  Please note that Drupal deliberately omits the closing ?> PHP tag.

name = "Example module"
description = "Gives an example of a module."
core = 6.x
package = Other

Next, you want to save a file called example.module.  Inside this file, you will want to copy the following code.  This code follows the instructions that I gave you in my previous answer.  I have tried to comment this code as well as possible in order to try to show you what is being done and why.  This should do what you want it to do.

<?php

/**
 * Implementation of hook_form_alter()
 */
function example_form_alter(&$form, &$form_state, $form_id) {
    // If the form is the user_register form
    if ($form_id == 'user_register') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_example_user_validate');
        // Hide the email address field
        $form['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 60,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#prefix' => '@',
      '#options' => array(
              // These are the possible email address domains
              'yahoo.fr' => 'yahoo.fr',
              'yahoo.com' => 'yahoo.com',
              'example.com' => 'example.com',
            ),
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _example_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['values']['mail'] = $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'];
    }
}


Proper way to alter field value from submit handler I added extra field "field_password_changed" to user account and I want to store there time of latest password change (simple input field).
Now, I added custom submit handler to catch user account edit action and currently it looks like this:
function user_form_submitted(&$form, FormStateInterface $form_state) {

  $form_state->set('field_password_changed', 'test22');

  $form['field_password_changed']['en'][0]['value']['#value'] = '54321';
  $form['field_password_changed']['widget'][0]['value']['#default_value'] = 'My new value';
  $form['field_password_changed']['widget'][0]['value']['#value'] = 1;

  $form["field_password_changed"]["#default_value"] = 'ffff';

}

Basically I tried every suggestion from this page:
https://www.drupal.org/forum/support/module-development-and-code-questions/2013-08-01/using-hook_form_alter-to-set-a-field
And not even one is working form me.
What is the proper way to change form field value in custom submit handler?

Consider using the Force Password Change module which can already keep track of that.

First, add your custom submit handler to the beginning of the submit handlers array and not to the end, to ensure you "inject" the data before the user entity gets saved.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  array_unshift($form['actions']['submit']['#submit'], 'user_form_submitted');
}

Second, depending a little bit on what field type exactly you added to the user entity, the form value needs to be an array of values. In the sample below I used a simple plain textfield to store the data.
function user_form_submitted(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setValue('field_password_changed', [['value' => 'test22']]);
}

Third, you somehow need to check if the password got changed at all or if just the user form got submitted. Again, have a look at the force_password_change.module to get an idea of what exactly you may need to check for.


Using Drush To Download Modules When You Dont Really Know The Name Hello im a drush newbie and im enjoying ints functionality. Years ago i saw a video of someone using drush to download modules and if he got the project name slighly wrong t would show him some alterntives in his command line interface.

Did i imagine this or is it possible?

Thanks

ps i just use drush dl modulename at the moment

Well I think your imagination did the trick! but the closest thing I can imagine is to use this sandbox module

  Allows you to search for modules from drush


How can I get the language name of the current node? I'm trying to figure out how to get the name of the language of the current node in display suite.  I find a language option under one of the node categories in the dynamic field content selector, but that outputs the language code, not the name.  Do I need to handle this in a preprocess function or is there some way of getting this that I've not managed to find?

I didn't find anything there available for clickers. I could suggest the following alternative:

Activate the "Display Suite Format" module
Create Display Suite "Code field" with following content:

<?php
  return t(locale_language_name($entity->language));
?>

Don't forget to activate the "Display Suite code" text format for this code field.
Add this code field to your content type's display!

Hope this helps!


How to disable the submit button after clicking? Drupal doesn't seem to prevent multiple form submits, even on node pages. This QA suggests fixing it on the server side.

How could I disable the submit button after clicking?

Any other solutions?

It's only in dev but the Hide Submit module would do the trick. One of the features is:

  Hide (or disable) the submit button after it has been clicked

I've just installed it on a dev site and it seems to work well for node add forms; when you click the submit button it's hidden and replaced with a loading image and a 'Please wait...' message, before the form is finally submitted. I haven't tried it on any other forms though.


PDO exception for Entity Reference Module I have 2 custom content type 'Movie' and 'Director';

In the Movie type there is a field that refers to some Director type.

Now , when i try to create a Movie content type it generates the following error.But the site admin can successfully create Movies.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'nid' in where clause is ambiguous: SELECT DISTINCT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type AS entity_type FROM {node} node INNER JOIN {node_access} na ON na.nid = node.nid WHERE (nid IN (:db_condition_placeholder_0)) AND (type IN (:db_condition_placeholder_1)) AND(( (na.gid = :db_condition_placeholder_2) AND (na.realm = :db_condition_placeholder_3) )OR( (na.gid = :db_condition_placeholder_4) AND (na.realm = :db_condition_placeholder_5) ))AND (na.grant_view >= :db_condition_placeholder_6) ; Array ( [:db_condition_placeholder_0] => 2 [:db_condition_placeholder_1] => writer [:db_condition_placeholder_2] => 0 [:db_condition_placeholder_3] => all [:db_condition_placeholder_4] => 32 [:db_condition_placeholder_5] => user_relationship_node_access_author [:db_condition_placeholder_6] => 1 [:entity_type] => node ) in EntityFieldQuery->execute() (line 1136 of /home/mysite/public_html/includes/entity.inc).

I solved the problem .In /public_html/includes/entity.inc I changed

$this->addCondition($select_query,$sql_field, $this->entityConditions['entity_id']);

to

$this->addCondition($select_query,"$base_table.".$sql_field, $this->entityConditions['entity_id']);

this statement should be somewhere near of line 1207

The reason is here:

[…] ON na.nid = node.nid WHERE (nid IN (:db_condition_placeholder_0)) […]

Can you see the nid after the WHERE keyword, it has no identifier and therefore PDO does not know how to handle it. You must prefix it with the correct table name (or assigned shortcut). Either na.nid or node.nid should do the trick.


Not Letting Me Turn On Registration When I try to change my ACCOUNT settings at admin/config/people/accounts

The new state (visitors) doesn't stay checked at Who can register accounts. It reverts just back to admin.

Does anyone know why?

Note:  I had a look in settings and all the files around it (D8). But I cannot see anything similar.

The config variable might be hard-coded in your codebase.

You could look for the string:

$conf[ or $conf['user_register'] = 0

For example, in settings.php or elsewhere.

The exact string may vary depending on your codebase, e.g quotes, spaces etc..

That would override the variable configuration setting in the UI.


shadowy images question http://themeforest.net/item/converge-the-best-premium-drupal-theme/full_screen_preview/405072

I am trying to make a d7 version of this slider.  I have enabled KWICKS VIEWS but I cannot seem to get a 3d effect, like it has here.  Does anyone know what kind of css this uses?  what i create and list class and enable it in VIEWS?

I used firebug to inspect but didnt see anything obvious.  THANK YOU

--newbie

It's using a transparent png to fade out the background and give that box shadow type effect on the right.  Look at class fade-bg and you'll see how.


Current page url token not using https I have the following token set up: [current-page:url:absolute] in metatag settings.

If I visit my site: https://www.example.com it displays http://www.example.com where I used the token.  Everything else (css,js,etc..) uses https.

Turns out there was a home page rule set up in metatag configuration that had the url hardcoded. Didn't see that at first.


8 - How do a get a view then save it with a new value In an update_hook() I need to search all views' displays for a value, then resave them with a new/extra one.  How do I go about this?  What command can I use?

$views = Views::getEnabledViews();
foreach ($views as $view) {
  $source_value = '';
  $config = \Drupal::config('views.view.' . $view->id());
  $rawData = $config->getRawData();

  $master = FALSE;
  // Get the display with the draggableviews field.
  // It is a little tricky because the 'default' display is the master.
  foreach ($rawData['display'] as $display_key => $display) {
    $field = isset($display['display_options']['fields']) ? $display['display_options']['fields'] : [];
    if ($display_key == 'default' && array_key_exists('draggableviews', $field)) {
      $master = TRUE;
    }
    if ($display_key != 'default' && array_key_exists('draggableviews', $field)) {
      $source_value = $view->id() . '|' . $display_key;
    }
    if ($master && empty($display['display_options']['fields'])) {
      $source_value = $view->id() . '|' . $display_key;
    }
  }
  if ($source_value) {
    // Save the view with the source value in the sort handler.
    foreach ($rawData['display'] as $display_key => $display) {
      $sorts = isset($display['display_options']['sorts']) ? $display['display_options']['sorts'] : [];
      if (array_key_exists('weight', $sorts)) {
        // **************
        // SAVE VIEW HERE
        // **************
      }
    }
  }
}

Replace

// **************
// SAVE VIEW HERE
// **************

with

$view_exec = Views::getView($view->id());
$view_exec->setHandlerOption($display_key, 'sort', 'weight', 'source', $source_value);
$view_exec->save();

When you call Views::getEnabledViews() it gives you an array of View classes.  What you need is the ViewsExecutable class.   Views::getView($id) returns this.

ViewsExecutable

  An object to contain all of the data to generate a view, plus the member functions to build the view query, execute the query and render the output.

Views vs ViewsExecutable

Another good example of using setHandlerOptions is in the TestCase

FieldGroupRowTest


How to exclude all blocks on a specific page? I have a website that uses themekey to display a different theme for one page. I use the context module to display blocks across the site (*). I tried to exclude the page I don't wish to display blocks on using ~, but it didn't work.

Essentially I followed this answer for my path setup: Exclude a block from specific parts of the website with the Context module

So in my path setting I have

*
~my-page-to-exclude-all-blocks

That did not work as all the blocks listed in the context are still present.
I even went so far as to create a second context with no blocks added for the path in question, but that didn't work either.

Edit: I also tried ~/my-page-to-exclude-all-blocks, but that didn't work either.

You could use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is not shown on that page on which you want to hide that block).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

{ "rules_block_visibility_exclude_a_page" : {
    "LABEL" : "Hide block for a specific page",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "my-page-to-exclude-all-blocks"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

Adapt the value of my-page-to-exclude-all-blocks to fit your needs. Obviously, you can reuse the same Rules Component for all blocks you want to hide on that specific page.

Should you want to further enhance the above Rules Component (to make it more generic), just replace the Rules condition in it with something using an appropriate regular expression (related to the current path also).

Note: yes this requires (at least) 1 more module (Rules block visibility, and Rules which it depends on). I also always try to avoid modulitis (= way too much modules) in any Drupal site. However adding Rules to any site seems to me like a no-brainer, because you can avoid/eliminate dozens of other modules that do only 1 thing. And by using the (tiny) Rules block visibility module, you can potentially replace modules such as the Context module and/or reduce the need for custom modules and/or using the (dangerous) PHP filter.


Adding contacter's email to reply field in contact form email In Drupal 7, when someone used our contact form, we would receive an email and could click "reply" in the email we received and have their email be in the "to" field. Since upgrading to Drupal 8, our own email shows up in the "to" field when replying to people who sent us an email through the contact box. Can anyone shed some light on how I can get the contacter's email to show up in the "to" field?

Can I set a "reply-to" field in the email to get this to work? I am using the core contact module, not webform but I am open to using the webform module if it can allow me to fix this.

You can do that with the Webform module. For a better explanation check out this: https://www.ostraining.com/blog/drupal/how-to-create-a-contact-form/


Calculate shipping based on square meters (m2) I have lengths of material as products in Ubercart, 3 and I need to be able to calculate shipping of them based on their length x width. Plenty of options for shipping based on weight but that's not what is needed here. I've got width and lengths fields in my product type already plus I have created one called "m2" to enter the square meters manually in case that is easier. Just a bit stuck as to what I should do next. Could rules help me? Maybe modifying the flat rate module or would a custom module be needed?

I'm struggling with a a similar problem.

From what I can see, the only way to do it with Ubercart is to connect to the API of an appropriate shipping company that supports volumetric shipping calculations. The availability of this (in terms of an existing module) will depend on which country you're working in, plus it will depend on whether there is an existing module that supports the specific carrier you've chosen.

The US is obviously well-served in this regard. Outside the US, support can be patchy, to say the least.


Link which leads to comments I simply wish to put a link at the head of node, which leads at the beginning of comments.

I did not find clear answer on this subject.

I try this, but does not work :

<?php print l('
title
', '#comments', array('html' => TRUE)); ?>

Is there a solution under drupal?

Creating a link like this will not create the desired output. When looking at the l() function comments on the Drupal API page, the following is suggested to make internal anchors work:

l(t('Comments'), $_GET['q'], array('fragment' => 'comments'));

What happens is you tell Drupal to create a link to the current page, and add #comments as an anchor (fragment).

This means you can also link to the comments from other pages, by simply changing the $_GET['q'] parameter to the desired path.


Export all views on a site to csv, json, spreadsheet etc The Question.

How do I export a spreadsheet documenting all the views from a drupal site?

More info:

Say you want a summary of all the views on a site, perhaps you are going to rebuild them - maybe there is some iffy php_views in there. Maybe you are simply documenting a messy site that you've inherited.

While there is support for exporting individual views to various formats it is not as easy to export a comprehensive list of all your views to a spreadsheet.

The Answer.

views_get_all_views()

The Script (save this as views_summarize.php or similar):

<?php
$views = [
  [
    'view machine name',
    'view name',
    'view desc',
    'base table',
    'display machine name',
    'display title',
    'display plugin',
    'php field the first',
  ]
];
foreach (views_get_all_views() as $view) {
  foreach ($view->display as $display => $data) {
    $views[] = [
      // 'view machine name'
      $view->name,
      // 'view name'
      $view->human_name,
      // 'view desc'
      $view->description,
      // 'base table'
      $view->base_table,
      // 'display machine name'
      $display,
      // 'display title'
      $data->display_title,
      // 'display plugin'
      $data->display_plugin,
      // 'php value in default field'
      $view->display['default']->display_options['fields']['php']['php_value'],
    ];
  }
}
$fp = fopen('views-summary.csv', 'w');
foreach ($views as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

Notes:

The returned $view object has properties nested within arrays and objects, make sure you shift gears accordingly in your query:

e.g.

$view->display['default']->display_options['fields']['php']['php_value'],

You can run this script with:

drush php-script views_summarize.php

Inspect the $view objects returned by views_get_all_views()

drush ev "print_r(views_get_all_views());"

Alternative uses

Site documentation is a tricky task, this approach is useful when documenting any pre-existing site configuration or content like rules, contexts etc...

A few hours later

Refined version of above script - outputs marker to indicate presence and location of php in views - yikes!

https://gist.github.com/gl2748/313b19bce1a99e42d94f


Pauthauto breaking for one specific page I have a Drupal 8.7 site with a content type for which I have just activated automatic URLs via pathauto.

We have a number of pages using this content type, and all of them worked perfectly when I activated the alias... except for one, which remained stuck as /node/9669.

I investigated this, and it turned out that the content editor who created the page had unticked the 'Generate automatic URL alias' checkbox on this particular page, hence why it didn't pick up the new pathauto alias.

So I thought it would be a simple thing to tick the box and it would work.

I ticked the checkbox and saved the page, but what actually happened is that it now gives me a browser error saying "page isn't redirecting properly" (Firefox) or "too many redirects" (Chrome).

I have tried regenerating the aliases, manually changing the alias, deleting the alias, recreating it... but nothing I do is getting the page back.

My guess is that there's something that's gotten saved in the pathauto database tables for this which is broken, but isn't showing up in the admin panel.

Can anyone please help me understand what's going on under the hood here and fix this alias.

Thank you.

The redirect issue described here is pretty common for sites where the Redirect module (drupal.org/project/redirect) is enabled. The module has a default config setting that creates a redirect anytime the url on the node is edited (this includes through bulk operations such as a pathauto alias generation process).

This setting can lead to the infinite redirect issue when a user changes an alias and then changes it back, resulting in a circular reference/infinite redirect.

I highly recommend disabling this setting for sites under construction (where urls are in flux) and enabling once deployed to production.  You can toggle it at /admin/config/search/redirect/settings (it's the very first setting on the page, shown in the partial screenshot below)

For production sites, be wary of changing a url multiple times- check/manage the list of redirects associated with the node on the node edit form as shown below

You can also check/manage redirects from the full list of redirects assigned in Drupal at /admin/config/search/redirect


Ajax ignoring my default_value I have a drupal form that contains a select box. Next to the select box is a link that pops a ctools modal up with an inner form that adds a value to the database table that drives the original select box. When someone clicks submit on the modal form, I would like to rebuild the select box on the original form and set the new value to the default. I've had success with adding the new elements to the select box by doing some ajax in the form_submit hook for the modal form, but it seems like Drupal ignores the value in #default_value in my render array. I have the following in my form_submit hook after the database update and after getting the render array from another function:

if(isset($id)) {
   $newdata['data_source']['#default_value'] = $id;
}
$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', drupal_render($newdata));
print ajax_render($commands);
exit();

Again, the select box is getting the new value, and my render array seems fine. I just can't get it to select the new value by default.

Alright, so this is slightly hackey, but I got this to work. I totally gave up on trying to set a default value in the render array, and instead did the drupal_render and set it to a variable. I then modified the html directly in the variable. The code I originally posted now looks like this:

if(isset($id) && is_numeric($id)) {
  $newrender = drupal_render($newdata);
  $newrender = str_replace('value="'.$id.'"', 'value="'.$id.'"  selected="selected"', $newrender);
}

$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', $newrender);
print ajax_render($commands);
exit();

If anyone on here has a more elegant solution, I'd be happy to know the "correct way" of doing this, but this produces the desired result.


Which contributed modules are being moved into Drupal 8 core? There were a significant number of D6 modules (or versions of) that were pulled into D7 core. I am wondering if there are any for D8?

Modules brought into core
Entirely:

Breakpoint
CacheTags
Content Translation
Email (simple field, HTML5 validation only)
Entity API
Entity Reference
Entity view modes
File Entity
Link (simple field, HTML5 validation only)
Phone (simple field, HTML5 validation only)
Picture
Quick Edit
Transliteration
UUID
Views
RESTWS (Renamed to REST module)

Partially:

Admin Views (reworked)
CKEditor
CTools
Date (all except recurring dates)
Display Suite (view modes)
Internationalization
Migrate
Views Bulk Operations (reworked)

Removed

Blog (moved to contrib)
Dashboard (moved to contrib as Homebox)
Open ID
Overlay (fundamentally reworked to not provide an "overlay")
PHP Filter (moved to contrib)
Poll (moved to contrib)
Profile (Use Profile2 now)
Translation (replaced by Entity Translation)
Trigger (use Rules now)
Signature (functionality provided by User moved to contrib)
XML-RPC (moved to contrib)

Modules fundamentally changed by Drupal 8:
Deprecated (you won't need these anymore)

Admin
Administration Language
Bean
Boxes
Caption Filter
Computed Field
Ctools exportables
Fallback Language Negotiation
Field Hidden
Fieldable Panels Panes
Float Filter
Hidden Field Widgets
History
IMCE
Localization update
Localized Drupal Distribution
Menu Block
Menu Trails
Module Filter
Node Reference
Placeholder
Profile2
RSS permissions
Services
String overrides
Strongarm
Token
Transliteration
User Picture Field
User Reference
Vertical Tabs
Wysiwyg * (the module and everything related to it)

Reduced (these will have less work to do)

Backup and Migrate
Context
Custom Breadcrumbs
Features
Feeds
Menu Breadcrumb
Service Links
Rules
Views * (every module related to views)


Selective caching - by user Is it even possible to do this?

The goal is to group our visitors:

Group A sees Theme A
Group B sees Theme B

I am able to achieve this goal through cookies. But when caching is enabled (i.e. Site config > Performance > On), things are messed up. This is what happens:

1) Group A visits Page-1
-- Page-1 is not cached yet.
-- Cookies are properly checked.
-- Page-1 is displayed using Theme A

2) Group B visits Page-2
-- Page-2 is not yet cached.
-- Cookies are properly checked.
-- Page-2 is displayed using Theme B

3) Group A visits Page-2
-- Page-2 is already cached.
-- Cookies are ignored
-- Page-2 is displayed using Theme B (when it should be displayed using Theme A)

So now what I am thinking is, instead of using cookies, I'll use separate cache for each group.

Is this even possible? :S If not, any recommendations are welcome.

Inputs will be highly appreciated. Thanks!

Checkout Cache page based on cookie value and URL

Long story short what you want can be done. Depends on how you want to do it :)


How to update route cache when saving an entity? I have added a custom access check to the /user/{user} route:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.canonical')) {
      $route->setRequirement('_profile_access', '\Drupal\mymodule\Access\ProfileAccessCheck::access');
    }
  }

}

with some starter checks:

/**
 * Determines access to user profile based on conditions.
 */
class ProfileAccessCheck implements AccessInterface {

  /**
   * Checks if this profile is publicly visible.
   *
   * @param \Drupal\Core\Routing\RouteMatch $routeMatch
   * @return \Drupal\Core\Access\AccessResultAllowed|\Drupal\Core\Access\AccessResultForbidden
   */
  public function access(RouteMatch $routeMatch) {
    $requested_profile = $routeMatch->getParameter('user');
    $show_profile = (bool) $requested_profile->field_show_profile->value;

    if ($show_profile === TRUE) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }

}

This appears to work fine, although it seems that the "View" tab does not hide/show in the admin when saving a user. If I clear the site cache, the tab is there on a user edit (or not, depending on value). Is there a way to get it to bind to the user or is it not worth while?

Turns out I just had to chain it to the AccessResult like so:

AccessResult::allowed()->addCacheableDependency($requested_profile);

Same for forbidden(). Now the 'View' tab is visible appropriately.


Separate Display for Start date and End date using Date module I have a date field which collects both start date and end date. I would like to display start date and end date as seprate in the display.

I don't see any options in the display page. I am sure I am missing some basic setting. Any ideas?

Note : I am not using views and I would like to do it using the field display options only.

There a few options. If you're comfortable with code you could add a preprocess hook to duplicate the date field and manipulate its configurations. That is a little heavy-handed and hard to maintain.

With the Panels suite of modules (particularly panelizer module) you get the ability to do things like take over entity view modes. Then you can place fields as "panes" as many times as you want with different configurations.


Don't allow users to create nodes until they have at least one comment I'm trying to create a community website using drupal where users can create accounts, login and create nodes but i don't want them to create a node until they have at least one comment on a node. I heard rules will be able to accomplish this but I don't know hw to set it to disallow users from creating a node until they have a content

You can do this is with the Rules module.

Remove the permission to create nodes from authenticated users.
Create a new role (e.g., one_comment) and give this role the permission to create nodes.
Create a rule that is triggered when a comment is posted and gives the user who posted the comment the one_comment role.


Unable to override default translation publishing status using entity_translation module We are using the entity_translation module in a large site, and we have 57 defined languages. We have some custom date fields in each locale, and we are using some custom code to only publish the locale when the current date is within the specified date range. However, one problem we are running into is that when an entity (node, taxonomy term) is created, the Published status for the default language (en-us in our case, defined at admin/config/regional/entity_translation) is automatically set to Published, which we don't want, so I need to override that value and set it to 0.

After delving into the module code, I found the hook_entity_translation_insert hook, which is called from EntityTranslationDefaultHandler:saveTranslations():

  foreach ($translations->hook as $langcode => $info) {
    $translation = isset($translations->data[$langcode]) ? $translations->data[$langcode] : $langcode;
    $data = isset($info['data']) ? $info['data'] : NULL;
    module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);
    // Provide Rules events integration if available.
    if (module_exists('rules')) {
      // Pass the entity as a wrapped one since rules can't do it for us
      // when using the variable type 'entity'.
      rules_invoke_event('entity_translation_' . $info['hook'], $this->entityType, entity_metadata_wrapper($this->entityType, $this->entity), $translation, $data);
    }
  }

where $op = 'insert'. I tried implementing my hook like so:

function mymodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
  }
}

but that doesn't change the status that gets passed on. If I try passing $translation in by reference:

function fluke_staging_entity_translation_insert($entity_type, $entity, &$translation, $values = array())

krumo gets into a huge recursive loop, and my computer maxes out the CPU.I can return a value like so:

function mymodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
    return ['translation' => $translation];
  }
}

but that's worthless, too, because the hook invocation doesn't do anything with it:

module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);

as compared to

$new_data = module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);

or something like that.

So my question is, how can I override the translation status in this hook, since it doesn't seem that it's a) passable by reference, or 2) it accepts any data from the hook_entity_translation_insert implementation?

I ended up posting this to the module issue queue and got this suggested code:

function MODULE_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
    $handler = entity_translation_get_handler($entity_type, $entity);
    $handler->setTranslation($translation);
    // Important: Avoid infinite loops by firing the insert hook again and again.
    $handler->getTranslations()->hook = array();
    $handler->saveTranslations();
  }
}

which was pretty close to what I had come up with on my own:

function mymodule_entity_insert($entity, $type) {
  // We don't want to do this for field collections.
   if (in_array($type, array('node', 'taxonomy_term'))) {
    // Attempt to unpublish the en-us translation that is set to published by default.
    $handler = entity_translation_get_handler($type, $entity);
    $translations = $handler->getTranslations();
    $enus_translation = $translations->data['en-us'];
    // Set the status = 0.
    $enus_translation['status'] = 0;
    $handler->setTranslation($enus_translation);
    // Save the translation.
    $handler->saveTranslations();
  }
}

And since it's not part of the saveTranslations() hook firing logic, no infinite loops should occur.


Can I truncate users table? For some reason, I need to truncate the users table, but I don't want to remove the user with ID equal to 1.

Is there any way to do it?

No, you can't truncate a table and leave data in it at the same time. That would be a contradiction in terms.

You'll need to do a standard delete

DELETE FROM users WHERE uid NOT IN (0, 1)

(it's important to make sure the anonymous user, ID 0, remains there too).

If you use the direct approach, be 100% sure that you know what you're doing. Unless you know different, there will probably be related data that doesn't get cleared out by simply removing an entry from the users table.

The best way to delete users is through the API: user_delete_multiple()


Multiple node references using url-widget I am trying to set up a structure of three content types where two references to one or more parents.

The main content type is assignment
The second is assignment_image that references the assignment content-type, this I have solved using the node references url widget.
The third is assignment_vote. This content-type needs to reference both the assignment and the assignment_image.

I can't figure out how to use the node reference url widget to reference two values. I don't want the user to be able to change these values so the autocomplete/selectboxes are not viable options.

I have thought about doing this using hidden-fields and jQuery but I really would like to be able to use existing modules/code.

Does anyone have any ideas?

You can put in the number of values that goes into the reference field, i.e. number of references to other nodes, as part of the content type definition (manage fields). That is at least the case Node Reference. You can also select which content types that can be selected. So pick the content types you need and select how many that the users should be able to pick.


In views, how do I show posts from this calendar day, ten years ago? I have a view in which I want to display posts that I made on this date 10 years ago. I can get close but not exactly what I want by setting the view's filter  to the following:

"Authored On is between: (offset) -10 year and -10 year +1 day"

My problem is that if it's currently 1pm on Dec. 17, 2019, I want to see all posts from the Dec. 17, 2009, regardless of hour posted. Instead I am seeing posts from Dec. 16, 2009 1pm to Dec. 17, 2009 1pm. I don't care what time the post was authored at, I just want it to show if the calendar day from 10 years ago is the same.

How can I set up my filter to do this?

Like you did, create two filters for the date range and then use the following values

-10 years midnight
-10 years +1 day midnight

Remember to select

An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

If you want to do this programmatically you can create a date filter and set the actual date values from code for the filter range.

You can create the date filter and set the filter value programmatically like the following

How do I programmatically render a view that has exposed filters?


Debug "Access Denied" Is there a way for debugging "Access Denied" errors in Drupal 8? I'm having some routing/permission issues, and I would like to be able to debug why i'm getting "Access Denied".

Install the devel module and then Web Profile module which is bundled with it. You will then see the Symfony web profiler bar below the browser screen. Click on a Request gear icon, and it will show you the route and the controller class. You can start there.

You can also search your code base for that route name and see, if there are additional cases when it is handled.


Issue with CSS on Home Page I have a vexing issue. I'm using the equal heights module to ensure two blocks are of equal height on the home page of my site. Inside each block, at the bottom of each block, is a read more link. I need the read more links to be spaced so that they are both at the bottom of each block, positioned identically on the page (within their respective blocks). When I'm logged in to the site as an ADMIN the CSS I'm using is working fine (see first screenshot below for the orange read more links showing on each side). However, when I log OUT of the site (or login as another user) and view the home page the 'read more' links are collapsing together at the top of the page in the middle for some reason (see the second screenshot). They are using the exact same CSS so I don't know why it's doing this.

Note: I tried giving another user all the same permissions as the admin to see if that fixed it and it did NOT fix the problem, so I don't think it's a permissions issue.

Ok, so here's the CSS (for one of the blocks - they are the same) I'm using to position the elements:

#block-views-featured-resource-block .views-field-view-node {
position: absolute;
margin-bottom: 8px;
padding-bottom: 5px;
text-align: center;
left: 20%;
width: 50%;
bottom: 0;
@media screen and (max-width: 959px) {
    position: absolute;
}
}

And here's the page--front.tpl.php file:

<?php if ($logo): ?>
    <a href="<?php print $front_page; ?>" title="<?php print t('Home');
?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>
<?php print render($page['top_navigation']); ?>
<?php print render($page['user_menu']); ?>

  <?php /** print $breadcrumb; */ ?>

  <?php print render($page['pathfinder_header']); ?>
  <?php print render($page['introduction']); ?>
  <?php print render($tabs); ?>
  <?php print render($page['help']); ?>

  <?php if ($action_links): ?>

<?php print render($action_links); ?>

  <?php endif; ?>

  <?php print render($page['featured_resource']); ?>
  <?php print render($page['hp_video']); ?>
  <?php print render($page['whats_new']); ?>

  <?php print render($page['find_your_path']); ?>
  <?php print render($page['search_library']); ?>
  <?php print render($page['browse_library']); ?>

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

  <?php print $feed_icons; ?>

The items in question are within the 'feat-container'  in the page.tpl above.

Anyone have ideas why when I'm logged in as an admin user they work but not for any other user? It makes no sense to me. I tried clearing the cache...that didn't help. I flushed with drush. That didn't help either.

Have you tried disabling the equalheights module, perhaps it maybe causing this issue? You don't need a module to give blocks equal heights, when you can easily do that with css.

I noticed on the top screenshot there is no video, while the bottom has a video.

Anyhow, based on your screenshot, it seems that you can fix this by adding a position: relative; to the div id or class that is wrapping the blocks. Which would be #block-views-featured-resource-block and what ever the name the Grand station Resource block id is.


drill down taxonomy node count using views I don't know if I'm the only one having this issue but my problem seems to be common. I just could not find the solution here and Google.

My site have the taxonomy menu:
Classifieds
  Electronics
  Autos
Jobs
  Accounting
  Information Technology
I just want to show a summary for every term that has children on it. E.g., When you click on Classifieds it should show like this:
Electronics(160)
Autos(310)
And when you click on Autos(310) it should show for example:
Aston Martin(200)
Toyota(110)
And then drill down to the last child item with node count. (e.g. DB9 Coupe (xx) etc..)
When I use the views default summary display and you clicked on 'classifieds' it will show:
Free Stuffs(xx)
DB9 Coupe(xx) <-- this should should first as 'Autos' and not show the last child in the hierarchy!

Basically, it's just a page with summary counts of terms being used in nodes and count them by level in the taxonomy hierarchy. So, from clicking a parent term, the first child terms will only show with node counts, then when clicking on one child only the children of this child will show with node counts etc..

Thank you in advance!

FYI. For those who have the same issue above. I managed to do this in Drupal 7 and it's called facet search primarily using Apache Solr or without Apache Solr here


Combine own stream with flagged user I am using follow flag latest version and edited the view fbss_ur_stream. I also created a following and followers view with the help of this tutorial Twitter style follow following

I took the idea from it and implemented it in fbss_ur_stream view. I deleted the relationships and contextual filters and added the new ones. Relationship: Flag follow (current user) and (user) flag user & Cont. filter: (flag user) User: uid. I unchecked "only flagged content" as well as "require this relationship"

Now I am able to see the posts from the person I am following, but my posts are not showing. Why?

Do I have to clone it and create a new view within this master view? how?

The problem lies with your contextual filter. It is set to filter the uid of flag user. This means it will limit the selection to only flags made by the current user (who did not flag himself, thus the user's own content is not selected).

You can probably solve this by having each user flag himself (automatically), but that is kinda ugly.

The alternative would be to use two regular filters and an OR group (remove the contextual filter). You might have to add some additional relationships if below steps do not work, but we basically want to have relations from the content to the user (author) and from the flag to the user (I believe you added that one already).

Add the filter user: current and select yes twice! For the first dialog, make sure you select the author relationship from content to user. For the second dialog use the flag to user relationship.

Finally, from the dropdown button above the filters section, select And/Or Rearrange and Create two groups with Or between them:

Now make sure to place one of the filters in each group.

This should show all content where the author is the current user, or content where the author has been flagged by the current user.


How to import nodes with custom fields using Feeds module and Feeds JSONPath Parser I've got a content type called 2Wd-Tractor with this structure :

Model (node title)
Engine
Transmission
Operational
Hydraulic System

Engine field is a custom field implemented using Field Api and it does have these subfields :

Make
Model
Net Power
PTO Power
Aspiration
Power Measured At
and ...

After that to make this field visible in feeds mapping hook_feeds_processor_targets_alter was implemented.

Here is the code :

foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance)
{
    $info = field_info_field($name);
    unset($callback);

    if ($info['type']=='uceen2wdtractor')
    {
        //The callback for this field type goes here.
        $callback = 'TARGET_SETTER_FOR_en2wdtractor';
    }

    if (isset($callback))
    {
        $targets[$name] =array(
            'name'=>check_plain($instance['label']),
            'callback' => $callback,
            'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
        );
    }
}

Data is imported to Feeds using json files , An importer is provided with these settings :

finally this is my json file :

The Problem is no data is stored in Engine field . this is the dsm($node) in hook_node_presave :

There are 3 places where the problem could lie:

Data not being correctly parsed by feeds
Data not being correctly saved by feeds
Problem with the field definition itself

Number 3 is ruled out since fields save correctly via the UI.

Troubleshooting Number 1.

Add a hook_feeds_after_parse to your module and either step through with a debugger or dump the $items array to the dblog:

function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  if($source->id == 'ENTER YOUR SOURCE ID HERE') {
    watchdog('My Module', '<pre>' . print_r($result->items, TRUE) . '</pre>');
  }
}

Question: is there a value in the items array for your engine field?

If no: there is a problem in the JSON parser definitions and feeds is not extracting the data correctly.

If yes: if the information exists that you require, i.e. every sub field value exists then the problem is not with the feeds parsing.

Troubleshooting Number 2

This points to an issue with your implementation of hook_feeds_processor_targets_alter.  Most likely, the data is not in the correct format for saving.  Add some watchdog statements in this function to determine:

Is the callback being fired?
If the callback is being fired then there is an issue with your hook_feeds_set_target implementation.  It isn't providing the correct data format to allow the field to be saved.  You could add a dpm() statement to hook_node_update and then save a node via the UI. This will show the correct format.


How to configure Context to set active on Menu item This other SO post says that Context provides this functionality out of the box, but when I add settings which seem reasonable, the active and/or active-trail classes are not set on my menu items.

How am I supposed to configure Context to set the active and/or active-trail on my menu items?

Here is my set up:

I've added some terms to the standard Tags taxonomy. For example: Surf, Skate, Volleyball.

I've used Pathauto to set dynamic paths for my taxonomy terms. blog/Surf, blog/Skate, etc.

I created a Menu with an item called Surf with a path of blog/Surf, as well as for Skate and Volleyball, etc.

I added that menu to the Highlighted region of my site.

When I browse to blog/Surf, my menu item does not receive the active nor the active-trail class so that I can style it appropriately to show the user that is where they currently are in the site.

I tried creating a Context for it and guessing at how it should be configured.

How do I get the active and/or active-trail classes on my blog/Surf menu item?

The only reason I can think of is that the context modules is actually adding the trail classes but the theme that you are using is not using them.

You can verify this in two ways,

Change the theme back to Bartik and see if it works.
Checkout the template file of your theme, print the variables that are passed to theme_menu_item in your template.php file

If the problem is your theme, then you will need to override the theme_menu_item accordingly in your theme.


Remove "Revision Information" Section? For my use case, I don't need this Revision information section to appear on my page. (I am using revision, so it has to be enabled on the content type).

What options are there to 1) disable this seciton , or to 2) hide it?

This can be done with the Simplify module. Here is a quote about it (from its project page):

  Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


How can I build the results of a view in code then send them to the view? Say I have a content type, nodes, that I want to serve through a view.

The problem is, the results are based on a series of complex requirements and conditions that aren't easily controlled through the Views UI. That is, I would like to determine which nodes to output in the view in code - is there a hook I can use to effectively build up the results, which are then fed through to the 'dumb' view?

In this way, I can do all my complex querying and calculations in code, then simply provide an array or similar of objects that the view will treat as its results, and simply spit them out?

EDIT: This doesn't necessarily have to be mediated through views, it's just I can't build the query I want in views easily because it's got a lot of moving parts.

Use hook_views_query_alter().

Alter the query before executing the query.
This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified


using ajaxComplete with drupal quicktabs I am trying to use .ajaxComplete() on my quicktabs but i cant seem to get it to hit. Would anyone have any ideas?

jQuery('#quicktabs-tab-find_a_doctor-1').click(function(){
  console.log('CLICKED');
  jQuery('#quicktabs-tab-find_a_doctor-1').css({
      "float":"left",
      "padding-right":"5px"
    });
  jQuery('#quicktabs-tab-find_a_doctor-1').parent().append('

');

  //jQuery('#loading-icon').ajaxComplete(function(){
     // jQuery(this).hide();
    //});

  Drupal.behaviors.LoadingIcon = {
    attach: function() {
      jQuery('#loading-icon').ajaxComplete(function() {
        jQuery(this).hide();
      });
    }
  }
});

I have tried both ideas, but i still cant get it to hit. Any help would be much appreciated!

Of course after posting on here I was able to figure out my mistake.

jQuery('#quicktabs-tab-find_a_doctor-1').click(function(){

  // Making room for loading icon
  jQuery('#quicktabs-tab-find_a_doctor-1').css({
      "float":"left",
      "padding-right":"5px"
    });

  // Adding the loading icon to tab
  jQuery('#quicktabs-tab-find_a_doctor-1').parent().append('

');

  // Once ajax is complete remove loading icon from page
  (function($) {
    Drupal.behaviors.LoadingIcon = {
      attach: function() {
        $(document).ajaxComplete(function() {
          $('#loading-icon').remove();
          $('#quicktabs-tab-find_a_doctor-1').css({
            "padding-right":"0px"
          });
        });
      }
    }
  }(jQuery));
});

According to http://api.jquery.com/ajaxcomplete/
You need to attach the .autoComplete() onto the document as stated right here:

  As of jQuery 1.8, the .ajaxComplete() method should only be attached to document.


How to resolve composer autoloader not found error? So, I'm running a D7 site with composer manager. I have successfully run the composer install command from inside the /sites/default/files/composer directory. The libraries appear to be successfully installed, but my watchdog is loaded with RuntimeException: Autoloader not found: /var/www/html/psrlivetoupdate/sites/all/vendor/autoload.php in composer_manager_register_autoloader() (line 173 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).  and there's also a notice in the site's status report that composer's dependencies haven't been installed. Any idea what's going on and or how to address it?

So, this is something that is a little bit wonky in the user interface for composer manager. The file path to where the autoloader should be gets generated automatically in reference to the drupal root of where you configure composer. If your live and development environments have different doc roots, as is likely with a shared host (e.g. /var/www/html/mysite vs /yourhost/public_html/blahblah, your path will be different and drupal won't know where to look. To solve this problem you have to modify the composer manager file directory variable to reflect where the file actually is. You can't change this through composer manager's settings tab, because it will generate a site error that prevents navigating to the tab and editing it there. You can most easily edit this variable with the devel module's variable editor function.


How to display content type name on related image? I have create one content type[article] with two by default field i.e. title and body.
In body summary part we have contain one image on left side and description on right side.

I want display the content type name on that image which is show in summary part.
Please help

1) In FIELDS add Content Type as a field and check mark exclude from display.

2) Make sure Content Type is ABOVE Body field, other wise you will not get Content Type token as a replacement pattern.

3) Click on your Body field and in REWRITE RESULTS, checkmark override output of this field.

Then use the replacement patterns.

The above is for Drupal 8, in Drupal 7 it would be [type_1] [body__summary]

You can add html if you need ex:
[type_1]
 [body__summary]

  Bonus: You could remove the image from Summary Part and instead add an image field to your content type. Then add your image as a
  field to your view. Then when you REWRITE RESULTS you can add the image there
  [type_1][field_image][body__summary]

PS: Next time tell us which Drupal version you are using!


Services: which hook to use for altering node field values before calling the node retrieve service? I have a custom formatter for a field
http://drupal.org/project/custom_formatters
but this seems to be ignored during node retrieve.

I also tried altering field value during hook_node_view, but no luck.

Do you have any tips on which hook node could I use to change the display of a field before retrieve?

Actually I think it's only hook_node_load() that can be use. As I understand Services module send just data and doesn't do any HTML render of the node and the hook_node_view is actually done only for it : change the HTML render.


Using a module controller to create a page that is more than just a div from the twig template? I am using a custom module to create a new page on my Drupal 8 site.

My routing.yml file is configured like this:

mymodule.print:
  path: '/print-mymodule'
  defaults:
    _controller: \Drupal\mymodule\Controller\MymodulePrintController::content
  requirements:
    _permission: 'view mymodule entity'
  options:
    _auth: ['basic_auth']

MymodulePrintController::content is as follows:

public function content() {
    return array(
        '#type' => 'page',
        '#theme' => 'mytheme'
    );
}

mytheme is used everywhere else on my site.

In mytheme.theme, I also have a mytheme_preprocess() function which is adding some blocks to the page. I am guessing the theme is being detected properly because this function is executing just fine. The template I am using is named according to twig's suggestions and is loading fine.

The problem is that the content() function is not really outputting a "page". Using Postman, I see that the entire contents of the response is just a div, there is no <html> tag, no <head>, no <body>, nothing else except what is defined in the one twig file and mytheme_preprocess. I need this page to be using this theme's css styles like the rest of my pages are.

How can I accomplish this? Every guide/question I've seen on the topic so far either is just returning a render array in the content() function like I already am doing, or is suggesting to use Response classes without enough detail for me to really understand.

When you generate an entity with drupal console you get a twig template for the content of the entity. This is not a page and not a theme. If you want to use a page template, that is specific to the entity, then you use a template name suggestion, for exampe page--myentity.html.twig. The content from the entity controller will end up like any other content inside of this page in the region content if you use the standard block layout, where the block "Main page content" is placed in this region.

You can remove anything else from the page template what you don't need and replace this with static html.


Is it possible to alter the behavior of the Ajax pager? I have a problem with the way the Drupal 7 Ajax pager works on my website: when looking into the code, it creates links, then when one clicks on one of these links, the ajax.js catches this event and replaces "going to another page" with "loading a block with Ajax-retrieved content".

This causes an SEO problem. In fact, as the links for the Pager are declared like following:

1

... it is therefore understood by crawlers as links to another page, even though they're not; during SEO analysis of my website, I get a Duplicate content between page "A" and page "A?page=1" notice.

Is there is a way to alter this behavior?
For example, how could I replace these links with elements that would have a dedicated attribute? I thought of replacing "a href=" with "span data-target=", for example, but I have no clue how to do this and didn't find any easy solution yet.

Would the amount of work be worth the gain in SEO?

~Stéphane

The way I fixed this was to take advantage of the way the Drupal/jQuery script for the "Views PHP" module's Ajax loading is working:

It looks for elements in the DOM with such structure : ul.pager > li > a
it listens to a click event and calculates the data to be retrieved based on the "href" tag.
It operates its magic on the DOM.

My tweak is to modify line 8 of the "ajax_view.js" file so it also looks for ul.pager > li > span elements. Then, I add a hook in my theme's "template.php" file with the following code:

function THEME_pager($variables) {
  $output = "";
  $items = array();
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total;

  $pager_middle = ceil($quantity / 2);
  $pager_current = $pager_page_array[$element] + 1;
  $pager_first = $pager_current - $pager_middle + 1;
  $pager_last = $pager_current + $quantity - $pager_middle;
  $pager_max = $pager_total[$element];

  $i = $pager_first;
  if ($pager_last > $pager_max) {
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  $li_previous = ($pager_current > 1) ? '' . (isset($tags[1]) ? $tags[1] : t('previous')) . '' : NULL;
  $li_next = ($pager_current < $pager_max) ? '' . (isset($tags[3]) ? $tags[3] : t('next')) . '' : NULL;
  if ($pager_total[$element] > 1) {
    if ($li_previous) {
      $items[] = array(
        'class' => array('prev'),
        'data' => $li_previous,
      );
    }
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '…',
        );
      }
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'data' => '' . $i . ''
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('active'),
            'data' => l($i, '#', array('fragment' => '', 'external' => TRUE)),
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'data' => '' . $i . ''
            );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '…',
        );
      }
    }
    if ($li_next) {
      $items[] = array(
        'class' => array('next'),
        'data' => $li_next,
      );
    }
    return '
' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pagination')),
    )) . '
';
  }
  return $output;
}

It works perfectly for my usage.

Note : I know a "href" tag is technically illegal in a "span" element, but I didn't want to dig too deep in Drupal's JS ;)

~Stéphane


Remove drupal message "field is required" from webform validation So when a webform is validated it sends a drupal message "X field is required", and creates a red border around the field.

For our project the red border is enough, how would I go about removing Drupal messages from triggering during validation?

You can remove it using CSS in that particular page !

Check for specific div's the page body is using and set the div.error to display:none;

OR

Override theme_status_messages to exclude or alter the status messages.

In your case,

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

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        if (strpos($a,'required') === false) {  // Check for any other conditions here
          $output .= '
' . $message . "
\n";
        }
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}


Cron task with Elysia cron module run only manually? Im using the cronapi coming with Elysia cron module and here is my code :

function MYMODULE_cronapi($op, $job = NULL) {
  $items['example_news_cron'] = array(
    'description' => 'Send mail with news',
    'rule' => '*/5 * * * *', // Every 5 minutes
    'callback' => 'example_news_fetch'
  );
  return $items;
}
function example_news_fetch() {
  // Do something here
}

the cron works only when I run it manually in the admin section(Elysia cron configuration), but I need it to be runing every some specific periode !

Is there some configuration missing, or system requirements

As you said "the cron works only when I run it manually in the admin section (Elysia cron configuration), but I need it to be runing every some specific periode !", it tells your codes are working fine.

By default Drupal cron runs when site is accessed and it evaluates when was the last time cron ran, so if the prescribed time is passed cron will run again, but for that site needs to be accessed, so you have a task which is supposed to run at fix period, you can not wait for Drupal site to be accessed by some one, instead you need to set a crontab on your server which means your server will ping your cron.php at the scheduled time.

Check How to setup cron tab on Linux based system or as an alternate option you can use drush while setting up cron tab (see: cron.html).


how to index unpublished nodes to apache solr I want to display unpublish nodes to some of the user roles.

The apachesolr by default index only publish nodes.

Is there a way of indexing unpublished nodes to the apache solr index?

By default, with the Search API, it indexes unpublished nodes unless you specify it not to. There is a patch to change the behaviour in the workflow tab of the search api: https://drupal.org/node/1507882

Can you please clarify your setup? Are you using the Search API?


How can I replace an image using a Form API? I have a form that works great for adding fields, including and image, to a node and saving it.

I want to allow users to edit their fields and change the data, including their image.  I figure there is some way to retrieve and display the current image and then allow the user to upload and save/replace the image with a new one.  I can't figure out how to show a preview of the existing image on the Edit form.  I assume somewhere I should use File_Exists_Replace, but the rest is an overwhelming mystery.

Here is the code I use for the original form:

  $form['logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('Only image files will be allowed.'),
  '#default_value' => variable_get('logo', ''),
  '#upload_location' => 'public://misc/media',
  '#upload_validators'  => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(2*1024*1024),
    )
  );

And the submit function:

    // Load the file via file.fid.
    $file = file_load($form_state['values']['logo']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    // Record that the module (in this example, cformtwo module) is using the file.
    file_usage_add($file, 'cformtwo', 'node', 1);
...
    node_submit($node);
    node_save($node);

I have spent days trying to figure out how to do this.

Your 'logo' variable will be a file id, referring to a row in the file_managed table, so you can use the file_load() function to load the file object, create an image with the details, and attach it to your form field.

This is a (very) basic example:

$logo = variable_get('logo');

$image = '';
if ($logo) {
  // Load the file object
  $file = file_load($logo);

  // Get a thumbnail of the image (just an example)
  $args = array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => 'Alt text');
  $image = theme('image_style', $args);
}

// Prepend it to your field
$form['logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('Only image files will be allowed.'),
  '#default_value' => $logo,
  '#upload_location' => 'public://misc/media',
  '#upload_validators'  => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(2*1024*1024),
  ),
  '#prefix' => $image
);


How do I fix a ReflectionException error (class doesn't exist)? I'm new to drupal 8. I would like to extend the user login form by deleting the username field and adding the email field. So I created a custom module, I implemented an Event Subscriber and declared it as a service :

services:
    mdmuser.route_subscriber:
        class: Drupal\mdm_user\Routing\RouteSubscriber
        tags:
             - {name: event_subscriber }

And here's my class RouteSubscriber

 <?php

 /**
 * @file
 * Contains \Drupal\mdm_user\Routing\RouteSubscriber.
 */

 namespace Drupal\mdm_user\Routing;

 use Drupal\Core\Routing\RouteSubscriberBase;
 use Symfony\Component\Routing\RouteCollection;

 /**
 * Listens to the dynamic route events.
 */
 class RouteSubscriber extends RouteSubscriberBase {

 protected function alterRoutes(RouteCollection $collection) {

     if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\mdm_user\Form\UserLoginForm');
      $collection->add('user.login', $route);
    }
  }
}

I have this error when I want to install my new module :

ReflectionException: Class Drupal\mdm_user\Routing\RouteSubscriber does not exist in ReflectionClass->__construct() (line 31 of core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterEventSubscribersPass.php).

Any idea is appreciated !

Thanks

It has to be the file structure.  Check again that it's at /modules/custom/mdm_user/src/Routing/RouteSubscriber.php

Also, in your class, you don't need to add the route again, it's passed by reference.

You can remove

$collection->add('user.login', $route);


Taxonomy per-node theming This is something I don't even think Drupal has built-in features for. I'm trying to theme taxonomy term page's nodes. The actual major problem is, I want to theme them per item. This for the actual HTML hierarchy (this is only a representation of the semantics I want, this is not to be interpreted as a visual representation):

+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 2    ||
|+---------------+|
+-----------------+

+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
+-----------------+

+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
+-----------------+

I really need this setup and can't be bothered with using complex CSS selectors (eg. :nth-child(odd)) this due to browser compatibility.

The only way I can imagine (and read on some places on the interwebs) is creating views as a workaround and theme that. But I would like not to make these excessive measurements just to workaround the lack of theming abilities of the taxonomy module.

Any thoughts? I thank you in advance!

This is the listing page for the taxonomy items, correct? the node page would be after you click on one of these to see the full content of that particular piece of content? And, if I understand correctly, you want a two column layout of this list? Here is a site I did recently that does that very thing.

http://noboribetsu-spa.jp/en/stay

This is very easy to accomplish. Just float left the class that wraps the item and all of them will fall into place. Let me know if I am not understanding what you are asking.


2 different views page per Node I have a content type "X", and would like to have 2 different view mode per node(I guess it should be 2 different url per node: /node/1 & node/1/summary). I'm not sure is it possible, but I want to make a view that list node of content type "X", each node has 2 links(2 fields), they are link to view mode 1(some fields) and view mode 2(full).

I have been searching this for day with no luck, and hope someone have done this before.

-- update my question for the confusion : Aug 5, 2015 at 5:pm --
What I really need is to have 2 different views mode pages per node(2 actual page per node), so each node can have their summary page(not a list of teaser mode) and full content page.

you Could create your own display mode using see this Then you create a menu route using hook_menu, similar to this:

function yourModule_menu() {
$items = array();

$items['node/%node/viewmode2'] = array(
'title' => 'Test',
'page callback' => 'yourModule_page_callback',
'page arguments' => array('node', 1),
'access arguments' => array(1),
'type' => MENU_CALLBACK,
);

return $items;
}

function yourModule_page_callback($node) {
 // here you render the node with the view mode 2
 $node_view = node_view($node, 'view_mode2_key');
 $rendered_node = drupal_render($node_view);
 return $rendered_node;
}

for the other view mode you could use the default display mode on  node/node_id or you could create extra one with same approach


Fancybox module error messages I enabled the fancybox module, but since doing so am getting the following error messages:

Notice: Undefined index: options in _fancybox_filter_settings() (line 559 of /home/mysite/public_html/sites/all/modules/fancybox/fancybox.module).
Warning: Invalid argument supplied for foreach() in _fancybox_filter_settings() (line 559 of /home/mysite/public_html/sites/all/modules/fancybox/fancybox.module).

Any advice as to how to fix them?

I guess you have a solution available in the following bug report filed at http://drupal.org/node/1904006

You have two possible options available.
1. There is a patch available in that post, use that.
2. Download development release, which already has that path applied in it.