"An illegal choice has been detected" error on user creation When creating a new user, I got this error:

  An illegal choice has been detected. Please contact the site administrator.

I'm sure I entered all the required information. This is when I am logged-in as administrator.
I'm using drupal 7.10.

[Edit]
I have a few lines of code in my hook_form_alter() which alters the user registration form :

if($form_id == 'user_register_form'){
    $form['profile_main']['#weight'] = 10;
    # Password and Confirm password
    $form['account']['pass']['#weight'] = -9; # move above E-mail address
    # User role
    $form['autoassignrole_user']['#weight'] = 2;
    $form['autoassignrole_user']['user_roles']['#attributes'] = array('onclick' => "Drupal.mymodule.toggleProfile(this)");
    if(in_array('administrator', $user->roles)){ # if master administrator, hide it
        $form['autoassignrole_user']['#required'] = FALSE;
        $form['autoassignrole_user']['#type'] = 'hidden';
    }
}
elseif($form_id == 'user_profile_form'){
    if(!in_array('administrator', $user->roles)){ # if not administrator
        $elems[] = 'timezone';
        $form['timezone']['#required'] = FALSE;
        $form['timezone']['#type'] = 'hidden';
    }
}

When you submit a form Drupal checks the integrity of it, i.e. it checks that the submitted values fall in line with the list of possible values for each element in the original form definition.

So, if you've got a select/checkboxes/radio buttons element on the form and you change the possible options for this using javascript on the client side, the new options won't match up with the ones Drupal knew about when the form was built. In this instance Drupal will rightly inform the user "An illegal choice has been detected.", because it has. This is an excellent security feature and is the default behaviour. It can't be switched off without some serious effort.

I would take a guess in your case that this problem is happening in the JS you're attaching to the autoassignrole_user element.

If you want to change a form's structure using JS you need to do it the 'Drupal' way, using AJAX to update the form on the server-side:

function MYMODULE_my_form($form, &$form_state) {
  // If the checkbox is ticked, load one set of options
  if (isset($form_state['values']['check']) && $form_state['values']['check']) {
    $options = new_options();
  }
  else {
    // Otherwise load the default options
    $options = default_options();
  }

  $form['check'] = array(
    '#type' => 'checkbox',
    '#title' => 'Click to change options',
    '#default_value' => isset($form_state['values']['check']) ? $form_state['values']['check'] : 1,
    '#ajax' => array(
      'wrapper' => 'options-wrapper',
      'callback' => 'my_form_ajax_callback'
    )
  );

  $form['options'] = array(
    '#type' => 'select',
    '#title' => 'Options',
    '#options' => $options,
    '#prefix' => '
',
    '#suffix' => '
'
  );
}

function my_form_ajax_callback(&$form, &$form_state) {
  // Return the options element which will have been changed in the re-build of the form
  return $form['options'];
}

The above is a very simple AJAX example that uses a checkbox change event to change the values in a select list on the form. Doing it this way will keep the internal structure of the form intact and you will no longer get the error message you're currently getting.

Have a look at the Form API documentation and AJAX framework documentation for a lot more information on this.


How do I correctly implement hook_bootstrap_colorize_text() to alter button colors in a Bootstrap sub-theme? I have read similar questions on here, but I'm still struggling for an answer for this.

I'm trying to implement hook_bootstrap_colorize_text() to alter button colors in a Bootstrap sub-theme.

I would like to add some specific text items to the array that dictates how the buttons are colorizes. For example, I have some buttons that have the  "btn-default" class, and I would like to indicate specific texts to which should have “btn-success" or "btn-warning" instead.

The bootstrap.api.php describes this process:

/**
 * Allows sub-themes to alter the array used for colorizing text.
 * …
 * @see _bootstrap_colorize_text()
 */
 function hook_bootstrap_colorize_text_alter(array &$texts) {
   // This matches the exact string: "My Unique Button Text".
   $texts['matches'][t('My Unique Button Text')] = 'primary';

  // This would also match the string above, however the class returned would
  // also be the one above; "matches" takes precedence over "contains".
  $texts['contains'][t('Unique')] = 'notice';

  // Remove matching for strings that contain "apply":
  unset($texts['contains'][t('Apply')]);

  // Change the class that matches "Rebuild" (originally "warning"):
  $texts['contains'][t('Rebuild')] = 'success';
}

Therefore, I have attempted to implement the following code in my sub-theme (methodsTheme) template.php file without success.

<?php
// Implements hook_bootstrap_colorize_text_alter() to alter button colors.
  function methodstheme_bootstrap_colorize_text_alter(array &$texts) {
    $texts['matches'][t('Request Rotation')] = 'success';
    $texts['contains'][t('Notify')] = 'success';
    $texts['contains'][t('Set')] = 'success';
    $texts['contains'][t('Mark')] = 'success';
    $texts['contains'][t('Assign')] = 'success';
    $texts['contains'][t('Report')] = 'warning';
    $texts['contains'][t('Request')] = 'info';
  }
?>

I've also tried:

<?php
// Implements hook_bootstrap_colorize_text_alter() to alter button colors.
  function methodstheme_bootstrap_colorize_text_alter(&$texts) {
    $texts['matches'][t('Request Rotation')] = 'success';
    $texts['contains'][t('Notify')] = 'success';
    $texts['contains'][t('Set')] = 'success';
    $texts['contains'][t('Mark')] = 'success';
    $texts['contains'][t('Assign')] = 'success';
    $texts['contains'][t('Report')] = 'warning';
    $texts['contains'][t('Request')] = 'info';
  }
?>

And, I've also tried:

<?php
// Implements hook_bootstrap_colorize_text_alter() to alter button colors.
  function methodstheme_bootstrap_colorize_text_alter(&$texts) {
    $texts = array(
      'matches' => array(
        t('Request Rotation') => 'success',
      ),
      'contains' => array(
        t('Notify') => 'success',
        t('Set') => 'success',
        t('Mark') => 'success',
        t('Assign') => 'success',
        t('Report') => 'warning',
        t('Request') => 'info',
      ),
    );
  }
?>

And, yes, after each attempt, I'm clearing the caches to see if the changes to the code are implemented to the desired result. However, I'm still emptyhanded. I'm placing the template.php file in my sites/all/themes/methodstheme/templates folder. The sub-theme was already established and working well (i.e., it is set-up properly, I believe).

I'm using Drupal 7.64 (with install profile varbase, but I've mostly removed all usage of the varbase profile and modules) and latest version of Bootstrap 3 theme as the base theme.

Can anyone offer some help or suggestions on what the issue may be?

Well, I really thought I had tried everything before posting. I didn't think I'd be answering my own question, but I'll put it up here in the case it is helpful to others. Here is what eventually worked for me:

<?php
  //Implements hook_bootstrap_colorize_text_alter() to alter Bootstrap button colors.
  function methodstheme_bootstrap_colorize_text_alter(&$texts) {
    $texts['matches'][t('Request Rotation')] = 'success';
    $texts['contains'][t('Notify')] = 'success';
    $texts['contains'][t('Set')] = 'success';
    $texts['contains'][t('Mark')] = 'success';
    $texts['contains'][t('Assign')] = 'success';
    $texts['contains'][t('Report')] = 'warning';
    $texts['contains'][t('Request')] = 'info';
  }
?>

I had tried this earlier, and had no result after clearing caches. I had tried  placing the template.php file in my sites/all/themes/methodstheme/templates folder as well as the sites/all/themes/methodstheme (not the templates sub-folder) folder.

Regardless of the folder I placed it in, it was still not working - I had no result after clearing the caches initially.

Placing the file in the sites/all/themes/methodstheme (not the templates sub-folder) folder was part of the solution. I had brushed up on the Bootstrap Starterkit file structure, and I was fairly certain the template.php file should not be in the templates sub-folder, so I started trying other things. Using Drush I cleared the theme-registry cache, the theme list cache, then cleared all caches. I cleared those caches again a second time, and viola! My site is now functioning as expected.

Lesson learned - clearing caches multiple times is sometimes necessary/helpful!


How to give a user the rights to "clear cache" I need to give a user the ability to "clear cache" since he sometimes does some changes to the menus, etc...  How can I give him a right to do that, or can I just send him a URL or post something on his admin toolbar?  With the roles and rights I've given him so far he can only go to one thing on the Configuration page and that's "URL aliases."  I recall that I used to have a way to accomplish this for the authenticated users with a little block at the bottom of the footer, but I can't find it or remember how I did it..

Help please, and thanks in advance.

Dave N

You may try UI Cache Clear.

Project page says:

  Clears specific cache bin without flushing the whole site cache.
  Allows to clear cache without full administrator permissions.
  Provides setting to clear current page cache automatically when    clearing Block, Views or Panels cache.
  Admin menu and Shortcut integration


How to render a views title in .tpl file? I embed a view in a .tpl file but it doesn't show the title. It only shows the content.

How to render the title of the view?

I'm using the code below:

<?php
print views_embed_view('dummy');
?>

Try following way :

$view = views_get_view('view_name');
$view->set_display('display_id');
print $view->get_title();
print $view->preview('display_id');


How to make a view table row clickable I was trying to make a row of the table I created using Views into something that was clickable. I'm really not finding anything online and everything I try doesn't give me the effect I'm looking for. I'm hoping someone here could share some insights. Thanks.

Pardon my neanderthalic jQuery skills here, but if you add a CSS class to your view via the UI, let's all it clickable-row, you could then do something like this in a JavaScript file that basically looks through the HTML and, if it finds a link inside your views row, it makes the surrounding div clickable to that link. So, just as long as one field in your view is a link, you'd be all set.

$('.clickable-row .views-row').each( function() {
  if ($(this).find('a').length) {
    $(this).click(function() {
        window.location=$(this).find('a').attr('href');
        return false;
    });
  }
});


How to transfer a panel variant from one site to another? Is there a way to do this with Features? I can't download and install any additional plugins to do this on this site.

Would anyone know if this is possible?

Yes, Panels and panel variants can be exported using the Features module. If you are using the panel variant as a part of page manager the option to export variant is shown in the features UI under page_manager_handlers.

Check the screenshot below to see how sample variants of the node view (node/%node) page can be exported via features:


context path and subpaths I have a problem with Context path condition. I would like on the conditions region to assign something like path/* where * indicates all its subpaths. For instance, if we have path/subpath1/subpath2 the context condition should match on path, subpath1 and subpath2.

Is it possible to do that on Context?

Thanks in advance!

I'm pretty sure that just checking it against path* should work.

So rather than path/* or path/*/* just run it against path*.


Some menus not showing in Menu Settings drop down when editing page I'm working on a website in Drupal 7.

I have the following menus in admin/structure/menus:

About Us Menu (added)
Get Connected Menu (added)
Main Menu (default)
Management (default)
Navigation (default)
User Menu (default)

Behind each menu in the list above, I have included "default" if it was included in the Drupal install, or "added" if I have added the menu myself.

I can add any page to any of these menus by using structure/menu/manage/[MENU NAME]/add, but I would like for my client to be able to select the menu from when adding or editing a page.

By default, I was able to add pages to the the Main Menu menu from the Menu Settings when adding or editing a page, and after adding the About Us Menu, I was able to add pages to same from this dropdown. However, I added another menu - Get Connected Menu, but I do not see it in the dropdown.

Adding additional test menus, I am still able to see only those that are in bold above - About Us Menu and Main Menu.

Has anyone ever seen this or know of a reason why this is happening and how to fix it?

Go to admin/structure/types/ and click the edit link next to your content type. In the Menu settings tab select the menus you want to be available in the content creation page.


Programmatically created content type module title not working I created a module with a .info, .module and .install file that can be installed by customers. This module file to create content types from node consists basically atm of:

/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
        'name' => t('My content'),
        'base' => 'mycontent',
        'description' => t('You can define your objects here'),
        'has_title' => TRUE,
        'title_label' => t('Object title')
       )
    );
}

/**
* Implement hook_form()
*/
function mycontent_form($node, $form_state) {
   return node_content_form($node, $form_state);
}

The problem is as follows:

I want to use entity translation. This works fine but the title module. It ist automatically installed, so the standard title of nodes can be replaced by clicking 'replace', but the default language is not filled.

E.g. if default language is German, the title is not saved. When I translate in English, the English title is saved. When I debug I can see that the complete (German or English) form is taken, the value of the form state are identical except the content itself and the language values 'de' and 'en'.

If I change en as default language then english title is not saved.

Because i can not see anything in the issue tracker of the title module I hope that I have to add anything to my code.

Thx in advance

maen

Ok, I BELIEVE that this is a drupal core issue:

I thought I can create a module with another name as the node bundle I made.

/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
      'name' => t('My content'),
      'base' => 'mycontent',
      'description' => t('You can define your objects here'),
      'has_title' => TRUE,
      'title_label' => t('Object title')
     )
  );
 }

 /**
  * Implement hook_form()
 */
   function mycontent_form($node, $form_state) {
     return node_content_form($node, $form_state);
   }

This is correct! But my module and hence my hook_node_info function had another name than my bundle.

So admin/strucure/types didn't show the bundle and the module title didn't recognize the bundle property.

So this is solved!


How to go about creating and formatting a custom HTML/PHP table to display SQL data I am new to drupal and basically I made a database within drupal and filled it with some dummy data. I want create/format/populate a table that looks like on one of my drupal pages:

+-----------+-------------------------+---------------------------+---------------+
| Resource  |          Week1          |          Week1+7          |    TOTALS     |
+-----------+-------------------------+---------------------------+---------------+
| resource1 | Hours(Week1, resource1) | Hours(Week1+7, resource1) | totals across |
| resource2 | Hours(Week1, resource1) | Hours(Week1+7, resource2) |               |
| TOTALS    | totals above            | totals above              |               |
+-----------+-------------------------+---------------------------+---------------+

I understand that you do it through views and I was trying to do it by creating my own module using the views_data() hook to try to create it (using http://mydons.com/how-to-expose-custom-module-table-to-views-in-drupal/ as a base/resource). I am kind of stuck though and I have no idea what the best approach would be to start to create a table that looks like the above. I am not sure this is the correct way/best way to do it and any direction/tips you guys can help me out with would be great.

Thanks!

You can create a custom table to display whatever data you want in a custom module by building the information output in a function, first you have to implement HOOK_menu for defining you path for the page containing the table and afterwards implementing the callback function for that page. I'll give you a real example here:

/**
* Implement hook_menu().
*/
function HOOK_menu() {
  $items = array();

$items['admin/config/my_table'] = array(
      'title' => 'My Table Page',
      'description' => '',
      'page callback' => 'my_table',
      'access arguments' => ....,
    );

 return $items;
}

As you can see i have my path and the callback is defined to the function my_table. Let's create that as well

function my_table {

    // Create table header
    $header = array(
        array('data' => t('COLUMN 1')),
        array('data' => t('ANOTHER ONE')),
        array('data' => t('COLUMN EXAMPLE')),
        array('data' => t('BLA BLA'))
    );

   .... // create table rows

    $output = '
';
    $output .= '
' . t('Say whatever you want to appear'). '
';
    $output .= '
';

    // here we render the actual table
    $output .= theme('table', array('header' => $header, 'rows'=> $rows, 'attributes' => array('id' => 'something') ));

    // and return the html output to our page
    return $output;

}

Hope this helps! Cheers!


Image Display (Content) View Drupal 7

I created an Image Display (Content) View for a different image to display on each page of my site in the second sidebar. When I created the view and uploaded an image to Basic Page...the photo now appears on every page of my site.

How do I modify the view that each page (Basic Page) can have a unique image?

very block has a "visibility setting". Select "Only the listed pages" and enter the pages where you want this block to show.


Set a Document File in a webform submission programmatically I have writen a PHP class that saves a pdf file programmatically. The class contains a function that returns the Drupal path private://documentA.pdf

I would like to attach the file to a webform submission:

$webform_submission = \Drupal\webform\Entity\WebformSubmission::load(ID);
$data = $webform_submission->getData();
$data['file_attachment'] = //retrieve the file
$webform_submission->setData($data);
$webform_submission->save();

Webform element type of file_attachment is Document file.

To attach the file to a webform submission, you should get the file id first, and then set the file_attachment to file id.
Try this out.

  $webform_submission = \Drupal\webform\Entity\WebformSubmission::load(1);
  $data = $webform_submission->getData();
  // Get the document file object from uri.
  $document = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => 'private://documentA.pdf']);
  // Get the file Id.
  $doc_id = reset($document)->id();
  // Set the file_attachment to fid.
  $data['file_attachment'] = $doc_id;
  $webform_submission->setData($data);
  $webform_submission->save();


Send form contents to the admin's email I have created the form using custom module, and it is working fine now. In this case, when I submit the form it simply sends the mail to the particular person from particular id. For this what i did is,

function custom_form_my_form_submit($form, &$form_state) {
$valid_email = $form_state['values']['email'];
$from = 'karthik.k.siva@gmail.com';
$body = 'Email: '.$valid_email.'<br />URL: '.request_uri();
$to = 'karthikeyan.ameex@gmail.com'; // Set this email address - emails will be sent to this email address!
$params = array(
'body' => $body,
'subject' => 'Website Information Request',
);

if (drupal_mail('custom_form_my_form', 'some_mail_key', $to, language_default(), $params, $from, TRUE))
{
    drupal_set_message('Thanks, we will be in contact with more information soon.');
} else {
    drupal_set_message('There was an error subscribing you. Please try again later');
}

}

And now I want to receive the submitted form contents through email, for that what I have to do.

You need to implement hook_mail too and define some_mail_key in your hook_mail :

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  if ($key == 'some_mail_key') {
    $message['subject'] = $params['subject'];
    $message['body'][] = $params['body'];
  }
}

Then you can use drupal_mail function like :

drupal_mail('mymodule', 'some_mail_key', $to, language_default(), $params, $from, TRUE);

Change mymodule with your module's name.


How do I change the site mail address? I want to change my site-wide email address. To do this, I changed the settings on admin/config/system/site-information. However, when I send an email from rules, it still uses the old email address.

How can I get the new email address to be picked up?

Based on the comments, and narrowing down the problem to the Rules module itself, or its integration with the mail system:

Tokens work elsewhere
Tokens within the body of the message work but not the from field
No templates are used
Core mail as well as third-party mail are affected
Clearing the cache, including the rules one, had no effect

It would appear to be a bug in the Rules module or the mail delivery part of it. I would suggest adding an issue to the Rules issue queue and see if they can further explore options for correcting the problem.


How to translate facet filter view search assertions/statements into Russian? How to translate facet filter view search assertions/statements into Russian? See the attached image. Want to write these statements in pure Russian to make friendly for the local shop customers. Thank you.

I think you can just import your own translations, creating a simple *.po file.
The structure of that file you can get from https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/PO-Files.html (or just google the example).
Import your own translations available by uri [yoursite]/admin/config/regional/translate/import


How do I change my blog title font size and serif typeface in views? I have tried to changed the title formatting with CSS, without success. I may have done something incorrectly. I also downloaded an module that has the ability to format titles in views, but that also failed.

You can see the list of titles I would like to change here: http://www.thepoliticus.com/

You may need to add a class name to the view to make it easier to specify the view
at admin/structure/views/view/[view-name]/edit -click-to- advanced click-to- CSS and create a name for the view, this will help to label the CSS.

Then:

If your theme has the option to change the font size and typeface, just change it in the theme. Adaptive theme can do this, https://drupal.org/project/adaptivetheme , for instance. If you only want one view to be different, this will not work.
Otherwise create a new subtheme and modify CSS as needed to change your view font-face and size. https://drupal.org/node/225125
An easier option: using the Sweaver module to interactively change CSS often without having to resort to editing any files, uses a GUI. https://drupal.org/project/sweaver . Be careful to only select that view.
Another easy option can use the CSS Injector, to create specific CSS to override existing CSS: https://drupal.org/project/css_injector and again, select the specific view element for title.


How to add js code in the head using a function? For a single page How can I add a js code in the <head> for a single page using a function?

I found this module https://www.drupal.org/project/js_injector but it seems overkilling just for this.

Please consult function drupal_add_js

  $options: (optional) A string defining the type of JavaScript that is being added in the $data parameter
  ('file'/'setting'/'inline'/'external'), or an associative array.
  JavaScript settings should always pass the string 'setting' only.
  Other types can have the following elements in the array:

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults
  to 'file'.
  scope: The location in which you want to place the script. Possible values are 'header' or 'footer'. If your theme implements
  different regions, you can also use these. Defaults to 'header'.

Note scope option in the text above.

Consult this post: Load JS & CSS Files on Specific Pages in Drupal 7 for direction on using a template preprocess function wherein to add the js.


Set default country for the Address type element (Webform) I'm using the webform module (8.x-5.0-rc12) and I've used the Address type element to store my addresses.

I'd like to set the Country field to default to United Kingdom when the form is displayed.

Does anyone konw if I can set that within the user interface?

Thanks.

Under the 'Address' element's 'Advanced' tab, you can set the 'Default value' via the UI.


How to let admin upload background image for view page and webform page? I would like admin to upload background image for each and every different pages in my drupal 7 site.

For normal content type like basic page, BackgroundField module works perfectly where admin can upload images in the file field.

But in webform pages and pages created by view, BackgroundField module can't be used.

Is there any way admin can upload their background image for both webform pages and view pages? As currently I'm using css to set the background images for these pages.

This module can do it for you Background Images.


How can I make a view that shows users all the who have flagged a single user? Background

I want to add a tab to the user profile that shows the logged in user which other users have viewed his/her profile.  I want to control this list in Views.

Until recently, I have been using the User Visits module.  However, this module does not integrate with Views and is no longer actively maintained.

I started building this using Views, Rules, and Flag.  Specifically, I created a flag Viewed profile, and then made a Rule to automatically flag a profile when a user visits another user's profile.

I then created a view of users with two displays.

My View

The first display, Profiles I visited, has a relationship to the Viewed profile flag and simply lists all profiles flagged (visited) by the current user.  Easy.

Now I want to create a second display, Users who have visited me.  In this case, I want to display all the users who have flagged the  current user.  However, I can't figure out how to do this.

I can add a relationship, Flags (by any user), but there could quickly be 10,000+ such flags on my site, so I am worried about the performance implications of loading all the flags like that.  Also, even if I load all the flags, I don't see how to easily filter them to users who have flagged the current user.

Instead, it seems like it would be easier to create a second flag, User who viewed me, and attach both flags (Viewed profile and User who viewed me) with a rule at the same time when a user visits a profile.  However, this seems like unnecessary duplication of information to me, since both flags link the same two users at the same time.  Is there a more elegant way to display this data in Views that will not lead to performance issues down the line?

Add a relationship, Flags: User's flaggings for your flag.  Uncheck Include only users who have flagged content.
Add a contextual filter, Flags: Content ID and set Provide default value to User ID from logged in user.

This was not intuitive, but it appears to do the trick.


Drupal Sending tons of Spam email Apparently one of the modules installed on my drupal site has been sending SPAM emails from my server as in (name)_(lastname)@(myservername).com , it managed to send 1000 email and queue 97,000 emails only in the first day..

At first, based on the email details, I figured it was being sent from a PHP page called diff.php under /sites/all/modules/contrib/libraries/tests/libraries/diff.php, so I deleted the whole tests folder, but now the emails are heading directly from my root site..
I have installed Hacked! to a development copy, and here's a copy of the results:

Does it seem like a module issue? should I re-install the changed modules?

The version of core you're running - 7.30 - is extremely vulnerable.  As long as you're running any version of core prior to 7.32, your site will remain vulnerable.  The vulnerability will allow changing modules (which can be discovered with the Hacked! module), putting executable PHP in the database (which can not be discovered with Hacked!), and injecting malicious shell scripts (which can not be discovered with Hacked!).

Simply replacing Drupal core and modules with non-hacked versions will not remove backdoors.

Just going through the changed modules and reinstalling them will not do.  At this point, even if you replace everything, the intruder have probably infected your database with exploits, as well as having installed several well-hidden backdoors to your site at shell level.

The best recourse is to delete your entire site an rebuild it from scratch on a clean vhost, then restore its contents from a backup made prior to Oct. 15, 2014.

Read this SA to understand the severity of this vulnerability: https://www.drupal.org/SA-CORE-2014-005. Also read:

https://www.drupal.org/node/2357241
http://www.linuxjournal.com/content/drupageddon-sql-injection-database-abstraction-and-hundreds-thousands-web-sites

If you're unable to delete the site and restore from backup, read this about recovering: Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?.

After you have cleaned up your site, to be alerted if this happens again, consider installing File integrity check. This module will monitor the integrity of almost all files on your site and send you an email if it detects that file integrity is breached.


How to handle ajax wrapper id for list of similar ajax forms? Consider a Drupal 7 page with a list of same-type entity forms: formA, formB, formC. The entity form uses ajax to replace part of itself.

Is there an established way to manage the wrapper id's so that an ajax call for formA knows to replace the wrapper div in formA? If I don't change the wrapper id's, I would have three divs on the page with the same ID.

You can use drupal_html_id() which:

  Prepares a string for use as a valid HTML ID and guarantees uniqueness.

e.g.

function my_form($form, &$form_state) {
  $id_string = 'my-element-id';
  $unique_id = drupal_html_id($id_string);

  $form['element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => $unique_id,
      // ...
    )
  );

  $form['output'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => 'Some markup'
  );
}

That should guarantee that the AJAX will work no matter how many different instances of the same form you create.


How to Add product type donation into cart programmatically with custom amount(100 or 200 or something)? I am using commerce_donate module and I want to add a product (type=donation) into cart programmatically with the amount set as per the user has already selected on some other page. On some custom form submit, I want to add this donation type product into cart in order to process the usual commerce order / checkout.

How can I achieve this ?

Thanks.

No code needed, just watch the video about "Donations with Custom Line Item Types in Drupal Commerce". Some more details about it (= quote from that link):

  This screencast shows how to use a custom line item type to allow your customer to specify a user-defined amount to donate. The line item has a Donation Amount field on it, and we then create a product display node that uses that custom line item. Finally, we use a custom rule to update the "price" of the donation product to the amount the customer has chosen.


CCK to Fields: content_migrate says missing widgets (image, matrix), but modules enabled I am attempting an update from D6 to D7 on a site with multiple CCK types (yes, optimist me after reading lots of horror stories), I am following the CCK migration guide and have installed the cck module for D7. When accessing admin/structure/content_migrate to migrate cck to fields, I get the following warnings for all image and matrix type fields.

This looks like a bug in the migration code, but where to report to, CCK content_migrate, image or matrix module?

This is somewhat urgent as it affects the migration from d6 - d7 so I would be very grateful for any pointers.

Details below:

field_image   image
RNAi
Changed field type: The 'field_image' field type will be changed from 'filefield' to 'image'.
Missing widget: The 'image' widget is not available for the field_image field, it will be set to the default widget.

Edit: the same for the matrix module: "Missing widget: The 'matrix' widget is not available for the field_primer_group field, it will be set to the default widget."

But the image and matrix modules are both enabled:

 Core        Image (image)                      Module  Enabled   7.41
Fields       Matrix Field (matrix)              Module  Enabled   7.x-2.4

-- php is 5.3.3 (centos) and postgres is 8.4 if that matters.

I can ignore the warning, it does not influence display or upload of images.


How to properly create an alias to a content When I create a content from Dashboard, I assign it an alias, to be exact I assign it:

  offers

But the route I'm getting is:

  http://example.com/?q=offers

How can I make it to be just:

  http://example.com/offers

Welcome to Drupal Stack Exchange :-)

You need to Enable Clean URL's .. Find more information regarding Clean URL's in D.O here

Go to  "admin/config/search/clean-urls" and enable clean URL's


Drupal.behaviors, attach and origin of it The structure of Drupal.behaviors is rather similar in Drupal 7 and Drupal 8. Where do attach() and detach() come from?
Thid code is from drupal.js , still wondering where attach method in this.attach is defined?

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

The attach() and detach() methods are part of the Behaviors interface defined by Drupal:

  Any object defined as a property of Drupal.behaviors will get its
  attach() method called when the DOM has loaded both initially and
  after any AJAX calls.

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How to print product ID in commerce-product.html.twig template I am not able to figure out how to print the product id in my commerce-product.html.twig for display on the product detail page. I tried different combinations of { product.field_id }} { product.id }} and can't find it.

You need to retrieve it from product_entity

{{ kint(product_entity.product_id.value) }}

  Search "Available Variables" for more information here
  https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product


Unable to add list items in item-list.html.twig I need to display some links in a list and I'm using item_list theme for this:

$ii = array(
  'id-1' => array('name' => 'name1', 'class' => 'class-1'),
  'id-2' => array('name' => 'name2', 'class' => 'class-2'),
);
$iii = array();
foreach ($ii as $key => $value) {
  $iii[] = array('#value' => ''.$value['name'].'', '#wrapper_attributes' => array('class' => 'class-id'));
}

$aa = array(
  '#theme' => 'item_list',
  '#items' => $iii, //list of items to be displayed
  '#list_type' => 'ul',
);
print_r(drupal_render($aa)->__toString());

But on running this, I got an output of:

where
 tags are empty and 2 empty bullets are displayed on the front-end.

What I'm doing wrong?

There is no such thing as #value, you want #markup instead, There are also better ways to create links, although I'm not 100% sure right now if you can provide #wrapper_attributes then, but you can call getRenderable() on the link, then you get a render array and should be able to it on that.:

\Drupal\Core\Link::fromTextAndUrl($value['name'], \Drupal\Core\Url::fromUri('http://test.com'))


How to make drush un-install modules without confirmation I want to create a drush command that reinstall some modules.
I've done something like this:

  $modules_to_uninstall = array("my_module1", "my_module2", "my_module3", "my_module4", "my_module5");
  foreach($modules_to_uninstall as $name){
    $args = array_merge(array('pm-uninstall') ,array($name));
    call_user_func_array('drush_invoke', $args);
  }

but, when I run the command in drush, it always asks me if I want to uninstall that module.

The following modules will be uninstalled: my_module1
Do you really want to continue? (y/n): y
my_module1 was successfully uninstalled.                                                                                [ok]
The following modules will be uninstalled: my_module2
Do you really want to continue? (y/n): y
my_module2 was successfully uninstalled.

[ok]
    The following modules will be uninstalled: my_module2
    Do you really want to continue? (y/n): y
    my_module3 was successfully uninstalled.
....

$modules_to_uninstall = array("-y my_module1", "my_module2", "my_module3", "my_module4", "my_module5");
  foreach($modules_to_uninstall as $name){
    $args = array_merge(array('pm-uninstall') ,array($name));
    call_user_func_array('drush_invoke', $args);
  }

I've try those but it's useless.

Some suggestion?

Drush has a -y option, that accepts all questions with a yes. Use that.


Add conditions on Where in Views 3 How can I do to add more conditions on WHERE, like this
WHERE view conditions ... AND ( (sentence 1 AND sentence 2) or (sentence 3 AND sentence 4) or ... )
This view is in a user profile and this conditions depens on profile data.

Thanks

I guess the option you need is in the "Filter Criteria" section, in the dropdown next to the "Add" button. If you fold down that menu you will see the "And/Or, Rearrange" option in which you can create sets of conditions.


How do I access values using kint()? I am porting a module from Drupal 7 to Drupal 8. I was debugging using kint().

I am using hook_user_presave($account) and trying to access the values of $account using kint($account).

kint() is very confusing, compared to dsm() in Drupal 7.

How do I access values using kint()?

You can get the user entity from the proxy with AccountProxy::getAccount:

$entity = $account->getAccount();

And then the roles with User::getRoles:

$roles = $entity->getRoles;

If you don't need the entity for anything else in that method, it turns into a one-liner:

$roles = $account->getAccount()->getRoles();


Redirect to external url adds external url to current url instead I'm using wampserver and I'm trying to redirect a visitor to an external url (which in turn will eventually send them back to another page on my drupal-site).

My site on wampserver is called localhost/testing and I use

drupal_goto(www.example.com, array(
  'external' => TRUE,
  'absolute' => TRUE,
  ));

However, the url I get redirected to is localhost/testing/www.example.com instead of www.example.com

You need whole URL like http(s)://www.example.com


Load Pages Using AJAX to Allow for a Continuous Music Player I'm looking to create a music player that will play continuously between page loads. After some research, I've decided AJAX is the best way to do this.

I'm looking to load all the site content using AJAX (minus the music player) in one container  and place the music player in a separate container div at the bottom of the page.

How would this be done? Thanks is in advanced!

To quote my answer to the same question at StackOverflow:

  Ajax pages makes it possible to load every page via Ajax with minimum effort. A player can be put in a region outside of the Ajax-loaded area, making for continuous playback. There are demo links on the project page, check them out.


Modules to create submenu with custom markup I have a question about how to create menu with full custom markup. Custom markup is applied not to menu items, but to entire submenu.

An example of such menu is provided below:

As you can see, submenu items have different visual attributes. And they are arranged like in a grid layout.

I think, it's possible to catch mouse over events and show html element with the submenu content, when user points cursor at submenu.

But, if you know any Drupal modules, that allow to implement such a feature, or simplify this task, it will be great.

Thanks in advance.

Check Out these two modules..: TB Mega Menu and Nice Menus

Here is a post which lists some of them  Mega Menu modules for Drupal


updating drupal core only without drush I'm trying to update drupal core on a large multisite version of drupal. He only wants core updating for a security update. However, I can't see any instructions out there on just updating core without updating all the modules, unless you have drush installed. (I tried updating all of them anyway on my dev box and the update failed because of duplicate entries in the nodewords table).

He doesn't have drush and I don't have the ability to add it. Is it possible without drush?

Thanks
Alex

This is in the docs  with every download  of  Drupal...

http://api.drupal.org/api/drupal/UPGRADE.txt/7


Drop down menu without any module Hello is it possible to create drop down menu without using any plugins at all?
In general the structure of menu is as follows for drop down.

Top1

drop1

drop2

I have create new menu and placed menu parents and children accordingly. Now I need to know if it is possible to show the menu in structure as above without using third-party modules.

You can do it with pure CSS, here is a tutorial: http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/ You can find several more if you google for CSS dropdown menu.

You will need to set up your menu, clicking on the "expanded" checkbox for any submenus you want to render.


displaying updated time in aggregator block I'm trying to add a line showing the last updated time for my RSS aggregator feed block (essentially the checked timestamp field from the aggregator_feed in a formatted manner).

I'm not able to find a preprocess function that lets me get this value.. the closest i got was implementing

function mm_theme2_aggregator_block_item($item, $feed = 0) {

  if($item->fid) {
    $fetch_modified_time = "SELECT `checked` FROM {aggregator_feed} WHERE `fid` = %d";
     $feed_last_modified_time = db_result(db_query($fetch_modified_time, $item->fid));
    }
    $last_modified = 'Last Modified time is ' . date('D M d h:i:s T Y', $feed_last_modified_time);
  $output .= 'link) .'" target="_blank">'. check_plain($item->title) ."\n";
  return $output;
}

where i'm not sure how to pass on this value to my $block or to $variables. Also this method iterates for each feed item and it'd be unwise to get the same value executed multiple times.

I'm pretty certain there's a drupal based way to get what i desire and am missing something.

Any help/support on this would be really helpful.

Thanks in advance

I implemented the above requested functionality by using a template_preprocess_block and adding the fetched variable to the $variables['block']. Code for the same as below:

    function my_theme_preprocess_block (&$variables) {
      // fetch last updated time for feed 1 only other feeds don't need this value
      if (($variables['block']->module == 'aggregator') && ($variables['block']->delta == 'feed-1')) {
        $last_updated_timestamp = db_result(db_query("SELECT `checked` FROM {aggregator_feed} WHERE `fid` = 1"));
        if (!empty($last_updated_timestamp)) {
          $variables['block']->last_updated_time = 'Last updated on ' . date('D M d g:i:s T Y', $last_updated_timestamp);
        }
      }
}

but this seems to look bad as i'm hardcoding my feed id in the query besides the fact that i'm using a query in template.php but it works.

Leaving this question hoping someone could top with a better solution.


How can I get translated path aliases for a custom language switcher? The Drupal 8 standard "Language switcher" dropdown does not give me what I need.
What I need is to break everything apart into groups and subgroups, in a div, and have custom text for each Language, some of which are custom languages.

As ugly as my code is, I'm almost there, but I'm getting a node, instead of the actual page.

if I click on U.S. Spanish, I get:
http://website.com/es-us/node/123
but I want:
http://website.com/es-us/contactenos

if I click on U.S. English, I get
http://website.com/en-us/node/123
but I want:
http://website.com/en-us/contact-us

(note the difference in URL alias, by language)

I've found this page, and used it as my starting point: https://www.drupal.org/docs/8/multilingual/enable-language-negotiation

As I attempt to understand how I might do it, I have in my themename.theme:

<?php

/**
* Implements hook_preprocess_page().
*
* @param $vars
*/
function themename_preprocess_page(&$vars) {
 $current_path = \Drupal::service('path.current')->getPath();
// not used yet...
$language = $vars['language']->getId();

  $fr_ca = '';
  $en_ca = '';
  $en_us = '';
  $es_us = '';
  $en_gb = '';

  $vars['en_us'] = '/en-us' . $current_path;
  $vars['es_us'] = '/es-us' . $current_path;
  $vars['en_ca'] = '/en-ca' . $current_path;
  $vars['fr_ca'] = '/fr-ca' . $current_path;
  $vars['en_gb'] = '/en-gb' . $current_path;
 }

Then I was going to hardcode into the page.tpl.twig (for now, while I learn) something similar to:

Americas

U.S.

      English
      Español

Canada

      English
      Francais

Europe

I'm sure there are better ways to do this for a more experienced coder. But for now, I'm hoping I can get the alias in there.

I can't use "$current_uri = \Drupal::request()->getRequestUri();"

Because that is different for each page... For example, "contactenos" in Spanish versus "contact-us" in English

Seems you can do what you want with Url options and a language object like following.

// Get all activated languages.
$languages = \Drupal::languageManager()->getLanguages();

foreach ($languages as $language) {

  // Get the current URL in each language.
  $url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $language)->toString();

  // And add it to a custom array.
  $variables['my_langswitch'][$language->getId()] = $url;
}

But as I already said in the comments to your question, this should actually be put in a custom block. And since it's all just about a little bit of changing markup I'd even go for JavaScript here and stick to the built-in language switcher. Also as I'm not sure how above works with caching enabled.

If you prefer getting the paths one-by-one, get a language object first and then use that to get the path alias.

// Get Swedish language
if ($sv_language = \Drupal::languageManager()->getLanguage('sv')) {

  // Get Swedish URL.
  $sv_url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $sv_language)->toString();

  // Add it as custom variable.
  $variables['sv_url'] = $sv_url;
}


Webform / add hidden field with token When adding a hidden secure field to a webform it does not show up in markup. Both for default value and tokens.

  Secure value (allows use of all tokens)

If I choose a hidden element it is present in DOM.

  Hidden element (less secure, changeable via JavaScript)

I have cleared cache several times, rearranged elements with both text fields and normal hidden fields. Those show up, but not the hidden secure ones.

What am I not doing right?

Here's what I'm referring to:

Fields with Secure value (allows use of all tokens) won't appear in your markup (that's why they are secured). They are 'created' on server side and are not available on Client Side. So nobody can't change their value (f.x. via XSS)

Hope it helps.


Drupal CKEditor module remove line breaks I have legacy content that has line breaks as paragraph separator. When trying to deal with them using CKEditor module 7.x-1.16 and CKEditor 4.5.4 library, all line breaks  are removed and the text turned into an ugly mass of text.

I tried disabling some filters from the Full HTML input format:

Limit allowed HTML tags
Convert line breaks into HTML
Correct faulty and chopped off HTML

I also tried to use custom formatting options and disabling _Advanced content filter. In any case, I didn't achieve my purpose.

The solution is simply in two points:

Adding the following config to in the advanced option tab of the desired profile:
admin/config/content/ckeditor/edit/Full

config.protectedSource = [/\r|\n/g];

This will keep the source of the content with new lines as it is and forget about its shape in the wysiwyg.

In for the container that holds your content, use the following css rule:

white-space: pre-line;
This will keep lines separated as paragraphs.

checkout those screen shots:

Add the protected source config:

Don't worry about it in wysiwyg:

Just look at the source:

It will look like the following on the frontend:

  Don't forget to flush cache specially if you optimized and aggregate
  js and css, also remove your browser cache or enabling remove cache
  during using dev tools (chrome)


How can I check in Rules if the number of members is below 50 or not? I need to add some user points to users when they signup to the site. Using the Rules module I already provided that functionality. But problem is to add some less points after 50 members have signed up.

So how can I implement a condition to differentiate the people that are registered:

first 50 members means Sign-up (first 50 = 20,000).
after 50 members add 3000 points to user signup .

Anyone suggestions?

You need get the count of the total users so far from the users table.
To do that, you can use a condition with php code where you have to write a db_query("SELECT COUNT(*) FROM users"); //[not tested]

if result gets number of existing users. you can return true/false to go to the action in order to assign points.

Let me know if you got it working.


Taxonomy import via csv? Is there a way to quickly create taxonomy categories by importing a csv file?

If so would it preserve any hierarchical relationships?

I've explored the taxonomy_csv project just not totally sure if it does what i wanted.

this is a Module Drupal 6 to import nodes from CSV, but acording their description, you can import taxonomy with its hierarchy: http://drupal.org/project/node_import

to Drupal 7 exist an alternative: Feeds http://drupal.org/project/feeds


how to write a post-save trigger The node_api hook provides a bunch of triggers which allows you to customize what might happen on, for example, a presave. The node_api presave opcode triggers an action to occur after clicking on the node 'save' button but BEFORE the information in the node form is inserted into the database. I would like to create a trigger which will be a post-save trigger, to trigger my custom code after clicking the save button but AFTER the node info has been saved into the database. Does anyone have any ideas of how I might create such a trigger?

(I have read the documentation about how to create a trigger, I just don't know to code the trigger I am describing above.)

Just to break the process down a bit (based on your other questions:1,2); when you submit a node form:

node_form_submit() calls node_save().
node_save() immediately calls node_invoke_nodeapi($node, 'presave'); to inform other modules about the presave.
node_save() then sets up a few properties on the node object, and the node record is written to the node table in the database using drupal_write_record().
At the very, very end of the function (after the data has been written to the node table), node_invoke_nodeapi() is called again with either 'insert' or 'update', depending on the current operation being run.

If you look through those functions, and the summary above, you'll see that the node data is 100%, definitely committed to the database before the 'insert' or 'update' operations are run for hook_nodeapi().

If that's not happening for your installation I would strongly recommend replacing core with a fresh version, as it sounds like something's gone horribly wrong!

Getting to the actual question; the only way you can add a post-save hook is to add another line in the core node_save() function to invoke it. But you would be adding it immediately after the call to node_invoke_nodeapi($node, $op); (where $op is 'insert' or 'update') anyway, so I'm not sure that would help.


Omega - Debugging blocks only for specified role Is it possible to see debugging blocks only for specified role?

IDEA
I made special role "theme developer" to see debugging blocks of Omega only for this role. When I check in *admin/appearance/settings/my_subtheme -> Debbugging* options:

Enable the debugging (placeholder) blocks for the selected roles.
Enable the grid overlay for the selected roles.

and select "theme developer" role debugging blocks will be seen by granted users only.

PROBLEM
If I am an administrator I can see debugging blocks even if I'm not in "theme developer" role. Why?

After documentation http://drupal.org/node/1298690 it should work as I wrote in idea but it is not.

If you're user uid=1 (administrator), you'll see everything regardless of role. You may be confusing it with the "administrator" role, which is not the same as the admin user.


Dynamic field based on nid I'm building a website for ads. Every ad will have an option to become a VIP ad and will be displayed in a blocks with better position.
The users will be able to make their ad into VIP ad by sending an SMS with prefix and their ad nid.

The idea is when a user clicks on the link "Make this ad VIP" will be displaying a field with details how to make the regular ad into VIP content. Let's say the ad node has nid 100, so when the user clicks on "Make this ad VIP" a info will be displayed like this: Send a text message "Prefix100" to the number 2xxx..where 100 will be the node id. On other ad if the node ID is 200, after clicking on "Make this ad VIP" the display text should be: Send a text message "Prefix200" to the number 2xxx.
The module for SMS service is already created.

The field with details will be hidden and "Make this ad VIP" will be a toggle, so I'll use jQuery for that, but how can I set the node id on every node?

OK, I've just figured out how to achieve this. I'm using Display suite and I've created a custom field like this: Send a text message SPORT[node:nid] to number 2xxx .... The key was the token [node:nid]. It's working great.


What is the template file for node add/edit page? I need to add extra CSS styles for a set of fields in the node add page for the jobs content type, but I don't know what template file should I use. I enabled Twig debugging, and I tried the following options.

page--node--add--jobs.html.twig, but it shows all regions
hook_theme(), but the custom template is not getting applied

My code for hook_theme() is the following.

 function custom_module_theme() {
  //  dpm("node:".drupal_get_path('module', 'comp_jobs'));
  return [
    'node-jobs-form' => [
      'render element' => 'form',
      'template' => 'jobs',
      'path' => drupal_get_path('module', 'comp_jobs') . '/templates',
    ],
  ];
}

What template file should I use, and how do I tell Drupal to use that?

The template for the node add form is node-edit-form.html.twig. But adding attributes to form fields is not an easy task in twig. You probably are able to do this more efficient in a form alter hook.


Why would one use Field Collection Having come across the Field Collection module (FCM) on Drupal, I would like to know why one would use the FCM. I appreciate one may need to create different profiles for users (i.e. Teacher, Student, Campus) that may have cross-linked data, but I'm a little stumped in my mind why the FCM can help.

Can someone elaborate on what benefits the module can have, prior to me doing a fair amount of 'trial and error' work to find out how it can benefit. Anything to enlighten us on Field Collection would be most welcome.

There are several uses of field collection, but as the name implies, it's all about "Collecting fields" into groups.

I have a personal use case where I have a content type called "Project". Each project, can have several "subtask"s, and each subtask has a boolean, "completed".

If I have a normal multi-value field for "subtask", how do I conveniently stick a "complete" checkbox on to them? That would be it's own multi-value field, and there would be no connection between the data points, nor any easy way to theme the edit page to make them look like they belong together.

However, since "subtask" is actually a field-collection with a "name" and a "checkbox", they are logically grouped together, both in storage and in rendering.

If one want's a "quick" solution to a similar problem, then FC is an excellent module. However, if I were to build something serious, I would first consider if Relation can solve the problem instead. This will probably not always be the case, but with a bit of extra work, using relation instead of FC will yield a more flexible solution.


Giving Add and remove option to select and deselect from one list to another I want to make user able to chose from one list of select options to another . A good example is in the picture here .

. Could you please tell me if there is a module to achieve this?
I tried using two select elements in the form and some jquery . But that is not working perfectly .
The problem is when user once select the options and visit next time , the previously chosen list does not appear . Thank you .

I think you're probably looking for the Improved Multi Select module.

The Improved Multi Select module replace the default multi-select boxes with two pannel list and search.
The first panel holds the options that are available, and the second panel holds the options that have been selected.
Two panels are separated by "add" and "remove" buttons. You can select an item from the first box, click the "add" button, and add it to the second box. Likewise, you can select an item from the second box, click the "remove" button, and it goes back into the unselected box.

The screenshot from the module page looks pretty similar to the screenshot in your question, except there's no drag-and-drop re-ordering built in (you would need to implement that yourself I think):


Get current language in template In Drupal 7 the current language is a global variable we can access with

global $language;
$langcode = $language->language;

I want to know how can we access the current language in a Twig file in Drupal 8 (in page--front.html.twig for example)?

I found my answer and post it here so maybe it helps others later.

First, in MYTHEME.theme:

In Drupal 8.2 language got added to page the variables in template_preprocess_page. But in my current version 8.1 it didn't exist so I added it with:

function MYTHEME_preprocess_page(&$vars) {

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['language'] = $language;
}

Then in my Twig file I use {{ language }}. Also I can get the language name with {{ language.getName() }}.

Update

After Drupal 8.2  a global variable language exists and now there's no more need to add it first.

{% if language.getId() == 'en' %}
  Do something
{% else %}
  Do something else
{% endif %}

Update
Thanks @Lucas for his comment

on Drupal > 8.7.5

{% if language.getId() == 'en' %} should be {% if language == 'en' %}


Can a coupon be programmatically added to an order using the add to cart subscriber? I'm attempting to add a coupon to an order when an item is added to the cart.  I've added an event subscriber for commerce_cart.entity.add. Within the subscriber, I use $to_apply->getPromotion()->apply($event->getCart());.

This does end up in Promotion::apply() and does call $offer->apply(), but the coupon doesn't seem to actually get applied.  I've tried to see if, once we arrive at /checkout/{order_id}, the promotions/coupons are reset. AFAICT, they are not.

I have confirmed that I can manually apply the coupon once on /checkout/{order_id}.

What am I missing?

Got an answer via Slack.  You only need to update the OrderInteface and set the coupons property, then resave the order.  PromotionOrderProcessor handles applying the coupon to the order.

Something like this should work within your event subscriber:

  /** @var \Drupal\commerce_promotion\Entity\Coupon $to_apply */
  $to_apply = $coupon
  /** @var OrderInterface $cart */
  $cart = $event->getCart();
  $cart->set('coupons', $to_apply);
  $cart->save();


Rules replacement pattern for image type field I am using Rules and HTML mail module to send HTML email on various events. It is working fine, but I am getting problem in rendering image field(ie image) in email template.

I have field field:cover-photo which is of type image. This field appears under
 Replacement Pattern token section. But when I include it, in the email it shows

Property field_cover_photo

and not the image. Any idea how can I show image in email.

-- Many thanks for your time.

Found the solution as follows:

To get the proper selector I switched to Data Selection mode.Then through hierarchy I got proper sector as [comment:node:field-photo:file:url], which is URL of image. By using img tag, I am able to display image.


Multiple content types from Views module, not old nodes from one of them I use the famous Views module to show nodes of different content types. One of these content types has a field called "final date". If a node has an old date, smaller than today's date, I want it to disappear from the start page so it's always up to date. How do I solve this problem?

To filter out content that has a "final date" that is in the past, you can set up a filter as follows on the view for this content type.

Filter on "final date" "is greater than or equal to" an offset date of "+0 minutes".

Screenshot below shows the final setting (in the screenshot example I used the "Post date" as the date field to filter on, but in your case it should be "Final date.")

Alternately, you could look at the Scheduler module and instead of using a "Final date" field, schedule these nodes to unpublish at a certain date. Depends on your use case.


Why doesn't the field table in the Drupal database use entity_id as a primary key? I'm working on trying to optimize a View SQL query and I noticed that the query being executed is using a join on a the entity_id field of a field table. I noticed that for some reason unbeknownst to me the entity_id field is not a primary key. The delta field is a primary key.

Can anyone enlighten me as to why this is the case? Can I safely tag entity_id as a primary key without incurring a wrath of unintended consequences? Thank you for your help.

The primary key for a field table is compound, consisting of:

entity_type
deleted
entity_id
language
delta

It's probably just the way your GUI is displaying the data that's confusing. This is Navicat's representation, for example:

If not, then something fishy has happened. Since the entity_id is supposed to be part of the compound key, if it isn't, it should be safe to add it to the rest. Take a backup first just in case.


Grouping Exposed Filters I am working with the module Better Exposed Filters (BEF) within my view. I have about 12 exposed filters, some of theme are select lists and some are range sliders. Some filters thematically belong together which is why I try to visually group them under a headline. Unfortunately, this can't be done using BEF.

I also tried Views Exposed Groups but this module can only be used instead of BEF, not together (I need BEF because of the slider funcionality). Besides I tried MEFIBS (More Exposed Filters in Blocks) which isn't suitable for me too.

Does somebody know of another module that helps me to accomplish this problem?

PS: I am no coder so editing the exposed-form.tpl.php is the last option for me.

Thanks,
Thomas

if you get the filter slider effect how you want save the view and disable the BEF module then go back to the view it can work. I remember I tried something like this before. It might break if you go back and mess with the filter and not just grouping.


Fusion Accelerator Skins windows are blank after core upgrade to Drupal 7.1.9 I just upgraded my Drupal core to 7.1.9, and now my Fusion Accelerator settings are not being applied. When I try to edit a skin (for a block), the pop-up window is empty except for the "save" button. Also, the front-end "Edit Skin" link (under the gear icon) is missing. Does anyone know what might cause this kind of issue, and how I can get my settings back so I can reapply those skin settings?

It was a cache issue. I cleared my cache and that fixed the issue.


Drush does not acknowledge release of new core update I am trying to update my drupal 7.31 core to 7.32 via Drush.

I ran the following commands

$ drush pm-releases

Project  Release  Date         Status
drupal   7.x-dev  2014-Oct-15  Development
drupal   7.32     2014-Oct-15  Supported, Recommended, Security
drupal   7.31     2014-Aug-06  Security

After the above command i ran the following:

$ drush pm-update drupal

Update information last refreshed: Thu, 10/16/2014 - 07:33
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.31              Unknown

No code updates available.

so i ran the following command:

$ drush pm-update drupal-7.32

Update information last refreshed: Thu, 10/16/2014 - 07:33
 Name         Installed Version  Proposed version  Message
 drupal-7.32  Unknown            Unknown           Specified version not found

No code updates available.

Here are the versions for drush and composer. Both are to the latest versions.

$ drush version

 Drush Version   :  7.0-dev

Composer version 1.0-dev

drush rf
will refresh the available releases and at that point you should be able to run
drush up
or
drush up drupal.


Remove tabledrag statuses on Ajax submit and display status message after Ajax submit I've added drupal_add_tabledrag() on one of my custom forms, it enables the users to drag to reorder the elements' weights, which then gets submitted via ajax to a callback function that saves the weights.

It's all working and the weights get saved, but after the save, the asterisks that indicate the weights have been changed, and also the message "Changes made in this table will not be saved until the form is submitted" won't go away.

What's the best way to let the dragtable know that the weights have been saved?
What's the best way to display status messages from an ajax callback function? I'd like to say "Weights saved successfully" after the callback function gets called. Currently I'm using drupal_set_message and return true from the callback function. This works as theme_system_messages() get prepended to the responses (see #ajax['callback']), but I'd like to know if there's a better way to achieve this.

I managed to solve this finally. My answer to both questions was Ajax Commands.

To anyone looking for the solution, here's what I did:

Question 1:

Instead of messing around with Dragtable, it's easier to just re-create the form and pass it back so it replaces the original form. I had to rebuild the form in my ajax callback function, then return it with an ajax command. To rebuild the form, you needed to create a new form_state variable and use drupal_rebuild_form function like so:

function my_ajax_form_callback($form, &$form_state) {
  $new_state = array();
  $new_state['build_info'] = $form_state['build_info'];
  $new_state['rebuild'] = TRUE;
  $new_state['values'] = array();
  $new_state += form_state_defaults();

  $new_form_array = drupal_rebuild_form('my_ajax_form_id', $new_state);
  $new_form = drupal_render($new_form_array);

  $commands = array();
  $commands[] = ajax_command_html('#form-container-element-id', $new_form);

  return array('#type' => 'ajax', '#commands' => $commands);
}

The original form button that submits to this callback also should have the form-container-element-id in the wrapper element of the #ajax array (it should always be a CSS ID so it shouldn't have the # to indicate it's an ID):

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_ajax_form_callback',
    'wrapper' => 'form-container-element-id',
    'method' => 'html',
    'event' => 'click',
  ),
);

Here's the API documentation link for ajax commands: Ajax framework commands (Drupal 7)

Question 2:

The best way to display status messages after an ajax callback is to use theme_status_messages() function. The snippet below also goes in the my_ajax_form_callback function before returning from the function:

drupal_set_message('This is a status message', 'status', FALSE);
$messages = theme_status_messages(array('display' => 'status'));
$commands[] = ajax_command_html('#status-message-container', $messages);


Downside of not rendering a region in twig template? Suppose we want to use a different layout/blocks in front page. I know there is a page visibility restriction feature in block configuration, and also  Page Manager and Panelsmodules exist, but what's the downside of this solution?

Define a specific region content-front in theme
Place some blocks in this this region
Render this region only in page--front.html.twig template

The above solution has some advantages: front-page blocks are listed separately from other blocks, no need to configure each block to be in <front> page (preventing a O(n) task), using native UI to arrange the blocks.

Edits:

hooks like hook_block_access or hook_preprocess_block will not be called for a block not being rendered.

Drupal won’t care and it won’t have any side effects other than the contents of a region not being rendered to a page whose template doesn’t render it

It's not quite that simple.

The problem with dynamically not rendering a region is that Drupal doesn't know about that. It will still load, check and prepare those blocks on every page, which means it is unecessary overhead compared to defining visibility rules to only have it shown on the frontpage. You can also do an empty check of the region in the template and as a result, only have it printed if there are blocks inside (this doesn't work reliably with blocks that might be shown but might be empty but it should work if they are configured to not be shown).

You could also implement a hook_block_access() implementation and deny view access for all blocks in a certain region, then you don't need to manually configure them all, but it does need to be in a module.


Drupal 8 problem to list taxonomy word of unpublished content in a view I made a view for the backend. Something like we know from backend for listing content. I want to list the taxonomy term for all content. No matter whether content is published or not. But the view only shows content, if content is published. What do I have do to show taxonomy terms for unpublished content?

An old question, but it's an issue I've been struggling with, too, so I thought I'd post an answer. Turns out there's a known issue (feature request, actually) with the taxonomy module going back to D7. You can get all the details at https://www.drupal.org/project/drupal/issues/962664.

There are patches there for 8.2, 8.3 and 8.4 that might solve your problem until the fix/feature makes into a stable release.


How to include IP address Token with Rules? I would like to track IP address and User Agent when Rules sends out a email. How can I include the [current-user:ip-address] token and %server[HTTP_USER_AGENT] in „Send email“ rule?

Unfortunately Rules (7.x-2.10) ignores both tokens.

IP Address: [current-user:ip-address]
User-Agent: %server[HTTP_USER_AGENT]

I’ve tried to create a rules Replacement tokens, however I am not able to create a new entity with Data selector site:current-user:ip-address
How can I create a Replacement tokens to show the current-user ip address?

Option 1: Create new Rules variables

Have a look at this prototype of a custom rule (in Rules export format):

{ "rules_send_email_with_user_agent_and_ip_address" : {
    "LABEL" : "Send email with User Agent and IP Address",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "\u003C?php print ip_address(); ?\u003E" },
          "PROVIDE" : { "variable_added" : { "useripaddress" : "User IP address" } }
        }
      },
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003C?php print $_SERVER[\u0027HTTP_USER_AGENT\u0027]; ?\u003E"
          },
          "PROVIDE" : { "variable_added" : { "useragent" : "User Agent" } }
        }
      },
      { "drupal_message" : { "message" : "User Ip Address is [useripaddress:value] and User Agent is [useragent:value]" } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "User [account:name] performed a login from Ip Address [useripaddress:value]",
          "message" : "User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value]).",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some details about this rule:

Rules Event: User has logged in (replace with whatever event fits for you).
Rules Conditions: none (add whatever conditions you want).
Rules Actions:

Add a variable, with label "User IP address", machine name useripaddress and with initial value the result of this PHP evaluation: <?php print ip_address(); ?>.
Add a variable, with label "User Agent", machine name useragent and with initial value the result of this PHP evaluation: <?php print $_SERVER['HTTP_USER_AGENT']; ?>.
Show a message on the site, with a message value like User Ip Address is [useripaddress:value] and User Agent is [useragent:value] (just for QA testing, remove this Rules Action after you're convinced it works OK).
Send email, with an eMail body like User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value])., and a similar eMail subject (replace with whatever eMail subject/body that fits for you).

If you have the Rules UI enabled (and the dangerous PHP filter ...) you should be able to import it in your own site also.

Attention: this rule requires the dangerous PHP filter to be enabled (which personally I try to avoid at any cost ...). But if anything else fails, this is "a" solution to get it to work. As an alternative, you could create a custom module in which you create your custom Rules Actions for creating such eMail, and in which you'd include some PHP code similar to the PHP code in the rules Actions shown in the above Rules Actions. Refer to my answer to "How to create custom rules action event conditions?" for more details about that. Or refer to this part of the Commerce Google Analytics module which adds 2 Rules Actions related to User Agent and User IP address.

Option 2: Use the Message module

If you're willing to also use the Message module (and have sufficient experience in using it ...), you could implement a rule like so:

Create an appropriate message entity, which refers to a "message type" in which you can refer to token [current-user:ip-address] (= The IP address of the current user). This token comes, out of the box, with the Message module.
Include some type of pointer/reference to the created message in your eMail, or use the Message Notify module to get the created message entity delivered as an eMail.
For your User-agent token their might be a similar token available already in the Message module also. Though so far I've not found / discovered that one. However, using the technique of "replacement tokens", you should be able to create such token (via Rules), and then include that in your Message type also. For an example to see those replacement tokens at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

Refer to this question for a zillion of other samples/cases about the amazing Message module.


How to "use Search by Page as its own entity"? Can someone clarify what sort of menu item is needed for my D6 site to be able to "use Search by Page as its own entity"?  I have SBP working -- in the sense that /search/search_by_page/keyword does a search and returns results, but I'm having trouble getting rid of the "Content" and "Users" tabs.  I've tried a couple of different entries in some_random_module_menu(), but haven't found the right one.  Any advice out there?  Thanks!

If it suits your workflow you could just deny access to those two search pages using hook_menu_alter():

function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = FALSE;
  $items['search/user']['access callback'] = FALSE;
}

If you still need to provide access to those paths under normal circumstances, and just hide the tabs on the search-by-page page, you can provide a function for the access callback that does a quick check on the current URL:

function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = 'MYMODULE_search_page_access';
  $items['search/user']['access callback'] = 'MYMODULE_search_page_access';
}

function MYMODULE_search_page_access($name) {
  // Deny access when on a search-by-page page
  if (arg(0) == 'search' && arg(1) == 'search_by_page') {
    return FALSE;
  }

  // Otherwise return the default access callback
  return _search_menu($name);
}


How to theme webform elements (radio buttons etc.)? I would like to know how to theme Drupal 7 Webform elements?
I want to change the HTML structure of every element, not just wrap form with div or something like that. And I want to leave theme's elements as they were.

EDIT:
I would like to add class to label and input type radio button.

Each webform element has it's own file in the "components" sub-directory of the webform module folder.

If you look in those files there is a _webform_theme_COMPONENTTYPE() function, for example _webform_theme_date() for the date fields.

This function defines the theme functions for that field type.

These theme functions are what you can use to override the themeing of the fields.

For exmaple theme_webform_date() can be overridden as THEMENAME_webform_date(&$variables) and you can change the output.

If it is things like the field wrappers or labels you want, then look at overriding the theme_webform_element() function.

That will let you do things like change where the label is printed in relation to the field.

You can use $element['#type'] to single out specific field types in that theme function.

Note: Webform components are a special case. Normally you can find themeable things by looking in the MODULENAME_theme() function. In this case webform_theme().

Specifically, to set classes on radio button fields:

You requirement of adding the class to a radio button is unfortunately a bit different.
This is because webform doesn't use it's own themeing, it uses drupal core's

So what you want is theme_radios() and/or theme_radio() and/or theme_form_element_label().

Something like these (there are comments to tell you what has changed):

/**
 * Theme a set of radio buttons.
 */
function THEMENAME_radios($variables) {
  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }

  // Add custom classes.
  // To target specific elements you can use the $element variable.
  // You can target the label using:
  // .your-custom-class label
  $attributes['class'] .= 'your-custom-class another-custom-class';

  return '
' . (!empty($element['#children']) ? $element['#children'] : '') . '
';
}

/**
 * Theme a single radio button.
 */
function THEMENAME_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  // Set custom classes.
  // Use $element to target specific fields.
  $element['#attributes']['class'][] = 'your-custom-class';
  $element['#attributes']['class'][] = 'another-custom-class';

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

Unfortunately it is not possible to add classes to a label except for overriding theme_form_element_label() because of this bug.

The are two possible ways to address this in the theme layer.

One is to add the class to the field wrapper and then target the labels via that in your css or js.

The other is to override theme_form_element_label() like this:

/**
 * Theme a form element label.
 */
function THEMENAME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    // Changed to make class an array.
    $attributes['class'][] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    // Changed to make class an array.
    $attributes['class'][] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // Add your classes here.
  // If you are using variables to make the class use the drupal_html_class()
  // function.
  // To target specific elements you can use the $element variable.
  // For example, based on field type:
  if ($element['#type'] == '') {
    $attributes['class'][] = 'your-custom-class';
    $attributes['class'][] = 'another-custom-class';
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' ' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "\n";
}


Reusing drupal forms in a profile installation? I've setup a custom installation profile, and of my installation steps is setting up Google Analytics.  I've downloaded the Google Analytics module and enabled it in my site profile.

What I'm doing in my install step is as follows:

hook_install_tasks()

$tasks['site_google_analytics_form'] = array(
  'display' => TRUE,
  'type' => 'form',
  'display_name' => st('Google Analytics Configuration'),
);

site_google_analytics_form()

/**
 * Configure google analytics.  The only required field is the tracking code.
 */
function site_google_analytics_form() {
  module_load_include('inc', 'googleanalytics', 'googleanalytics.admin');
  return drupal_get_form('googleanalytics_admin_settings_form');
}

The probelm I'm having is that, even if I enter a valid web property ID, the form always comes back saying that an invalid ID was entered.  I checked to make sure the validation function is firing (which also is in googleanalytics.admin.inc), and it is, but the $form_state variable doesn't have any of the form values preserved.

So, I guess my question is this - why is the $form_state variable being passed into the validation function not storing the values I specified in the form during the install step?

The problem

A bad implementation of your code is causing the confusion. The input data is not stored in the $form_state variable, but in $form_state['input'] initially.

Once the user submit a form, Drupal will build the form again and process the values. In this step, the system make some checks. You can take a look of functions that have been called.

The function _form_builder_handle_input_element($form_id, &$element, &$form_state) is the one that set the values in $form.

The previous function is called in the middle of form_builder().  At the end of same function, drupal will fill the values in '$form_state' variable .

Why the function is not filling the values?

Because the next code is checking the input form:

// Set a flag if we have a correct form submission. This is always TRUE for
// programmed forms coming from drupal_form_submit(), or if the form_id coming
// from the POST data is set and matches the current form_id.

if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  $form_state['process_input'] = TRUE;
}
else {
  $form_state['process_input'] = FALSE;
}

The result is FALSE because $form_state['input']['form_id'] != $form_id.

'site_google_analytics_form' != 'googleanalytics_admin_settings_form'

So, the input finally is not processed for security reasons

Solution

Your code should be implemented like this:

/*
* hook_install_tasks(&$install_state)
*/
function hook_install_tasks(&$install_state){

$tasks['site_google_analytics_form'] = array(
        'display' => TRUE,
        'type' => 'form',
        'display_name' => st('Google Analytics Configuration'),
);

return $tasks;

}

/**
* Configure google analytics.  The only required field is the tracking code.
*/
function site_google_analytics_form($form, &$form_state){

    module_load_include('inc', 'googleanalytics', 'googleanalytics.admin');
    return googleanalytics_admin_settings_form($form, $form_state);

}

The run_task() call itself the drupal_get_form(), so it was no necessary call yourself in your code.


Getting views data as a REST service I need a way to get the output of a view as a REST service in JSON format.

I read about the RestfulWS and the Services modules, but I didn't find enough documentation.
Are these straight forward, or should I just go with a custom module?

Perhaps Services Views module could be of interest here:

  Views support for the Services module version 3.x and later.

  It has currently two features:
  - Create view based resource creating Services display in a view
  - Execute any view of the system via views resource call

  After enabling "views" resource in your services endpoint you can do
  GET request to:

http://example.com/<endpoint path>/views/<view name>

  This will execute a view and pass results.


Total indexed is zero with 302 status I'm using Google Webmaster Tools to manage my site SEO; even with 600 articles my total indexed pages is zero.

When I use "Fetch as Google" I get the following.

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    <title>302 Found</title>

Found

The document has moved here.

My site is made with Drupal 7, and the Boost module.

Is that caused by a wrong configuration? If so, how can I fix it?

It looks like you have a different domain either registered or for testing with Google Webmaster Tools.

e.g example.com vs www.example.com

When the bot requests example.com, it is redirected to www.example.com with an HTTP 302 Found reponse.

The solution would be to register the same preferred domain with Google Webmaster Tools that is used for regular site visitors.

As for 0 pages of a new site being indexed in Google, give it time. If you've registered the sitemap, and signed up for Google Analytics, the googlebot will arrive soon. It can take a couple of weeks.


How to change the autocomplete for a user reference to show First/Last name instead of username? I want to add a user reference field to an "event" content type, and reference the user who will present.

But I wonder how to change the entity reference - I've tried using the "filter by an entity reference view" with a view I created, but it still only shows the username.

Similar to Show node IDs along with titles in Entityreference Autocomplete list except in the rewrite of your user name field use {{field_first_name}} {{field_last_name}} and you need to add those fields ABOVE your user name field, in order to get access to those replacement patterns.


An illegal choice has been detected. Please contact the site administrator.in dynamic select list dependent dropdown using hook_form_alter and custom form elements below

$form['get-quotes-shipping']['country'] = array(
      '#type' => 'select',
      '#options' => array('_none' => '- None -') + country_get_list(),
      '#multiple' => FALSE,
      '#weight' => 3,
      '#title'=>t('Country'),
      '#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
      '#ajax' => array(
          'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => '_get_state_field',
            'method' => 'replace',
       ),
    );

    $form['get-quotes-shipping2']['actions']['get_quotes'] = array(
      '#type' =>'submit',
      '#value' => 'Get Quotes',
       '#submit' => array('custom_changes_get_quotes_submit'),
      '#validate' => array('custom_changes_get_quotes_validate'),
      '#weight' => 1,
    );

  $squadron_options = array();
   if (isset($_SESSION['selected_country'])) {
       module_load_include('inc', 'location');
       $states = location_get_provinces($_SESSION['selected_country']);
       $squadron_options =  $states;
   }
   $form['get-quotes-shipping0']['states']['#type'] = 'select';
     $form['get-quotes-shipping0']['states']['#title'] = t('State/Province');

   $form['get-quotes-shipping0']['states']['#prefix'] = '
';
   $form['get-quotes-shipping0']['states']['#suffix'] = '
';
    $form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
    if (isset($squadron_options[0])) {
      $form['get-quotes-shipping0']['states']['#default_value'] =  $squadron_options[0];
    }

Callback function as given below.

function _get_state_field(&$form,&$form_state) {
  module_load_include('inc', 'location');
  if ($form_state['values']['country'] == '_none') {
    unset($form['get-quotes-shipping0']['states']['#options']);
    $form['get-quotes-shipping0']['states']['#default_value'] = '_none';
     return $form['get-quotes-shipping0']['states'];

  }
  else {
      $states = location_get_provinces($form_state['values']['country']);
 $form['get-quotes-shipping0']['states']['#options'] = $states;
     return $form['get-quotes-shipping0']['states'];

  }

}

When I select Country and then state at first it gives proper values
but when I select country again it gives
An illegal choice has been detected

What is the issue with the above code?
can anyone point out?

i recently made a 3 level dependent dropdown and had the same issue with some of the problems i found on the way. First you need to re-organize your code a little bit more. have in mind that the callback function should normaly look something like this:

//callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}

Any code inside the callback has the potential to intervene with the proccess, with some exceptions.

Without taking a longer look to your code i think it should look somethink like this:

<?php

 module_load_include('inc', 'location');
  if ($form_state['values']['country'] == '_none') {
    unset($form['get-quotes-shipping0']['states']['#options']);
    $form['get-quotes-shipping0']['states']['#default_value'] = '_none';
     return $form['get-quotes-shipping0']['states'];

  }
  else {
      $states = location_get_provinces($form_state['values']['country']);
 $form['get-quotes-shipping0']['states']['#options'] = $states;
  }

$form['get-quotes-shipping']['country'] = array(
      '#type' => 'select',
      '#options' => array('_none' => '- None -') + country_get_list(),
      '#multiple' => FALSE,
      '#weight' => 3,
      '#title'=>t('Country'),
      '#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
      '#ajax' => array(
          'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => '_get_state_field',
            'method' => 'replace',
       ),
    );

    $form['get-quotes-shipping2']['actions']['get_quotes'] = array(
      '#type' =>'submit',
      '#value' => 'Get Quotes',
       '#submit' => array('custom_changes_get_quotes_submit'),
      '#validate' => array('custom_changes_get_quotes_validate'),
      '#weight' => 1,
    );

   $form['get-quotes-shipping0']['states']['#type'] = 'select';
     $form['get-quotes-shipping0']['states']['#title'] = t('State/Province');

   $form['get-quotes-shipping0']['states']['#prefix'] = '
';
   $form['get-quotes-shipping0']['states']['#suffix'] = '
';
    $form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
    if (isset($squadron_options[0])) {
      $form['get-quotes-shipping0']['states']['#default_value'] =  $squadron_options[0];
    }

    //callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}
?>

This is the code i wrote, try to follow the same structure it's working for me perfectly.

Tell us how it went, have a good coding!


Including a different jQuery version only on specific page jQuery update module is including this script.

<script type="text/javascript" src="/sites/all/modules/jquery_update/replace/jquery.min.js?6"></script>

I need this on every page, except a certain template file which I am using fancy box, and need a later version of jQuery.

I need to exclude jQuery update from putting the above script in the $scripts variable ONLY on page-media-photos.tpl.php. How can I achieve this?

Here are your options:

Use jQuery Multi, as mentioned in another answer. It can be configured to load the higher version of jQuery just on that page and just for the fancy box. It won't interfere with Drupal's jQuery or with jquery_update's jQuery.
In Drupal 7, you can use hook_js_alter(), which will let you swap out jquery_update's version with whatever you want.
In Drupal 6 with jQuery Update, it provides a hook that lets you alter the JS after it's done doing its thing. You can look at the jQuery Multi 6.x code to see how it uses this hook.
In Drupal 6 without jQuery Update, you can do this using a preprocess_page hook. The $scripts variable will be available there, and you can change it. This can get a bit tricky. You can also see how qmulti does this. jQuery Update also does this in a similar way.

Remember that swapping to a higher jQuery version can break some things in Drupal core and contrib, which is the problem jQuery Multi solves. So if you do this make sure you're not breaking anything. The benefit here is that you just load the jQuery you need, while with jQuery Multi you'll load both.


URL redirect module working fine with nodes not with alias url's I am new to Drupal. I have installed URL Redirect module and tried the following.

Source URL: testwebsite.com/how

Redirect URL: testwebsite.com/how-to-do

Its get stored with node id instead actual URL.

Source URL: http://www.testwebsite.com/node/123545

Redirect URL: http://www.testwebsite.com/node/134566

When I tried to call with node URL its redirecting fine. But when I call testwebsite.com/how it doesn't redirect.

You can use Path Redirect module in your scenario. Module page says :

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.


How do I disable ajax on file fields? I'm having some problems where using drupal_get_form() breaks the upload/remove functionality of a file field when it's processed with ajax. It seems this may be a core issue (http://drupal.org/node/1526300) but I haven't found a solution that works for me yet.

I've noticed that the form degrades gracefully when ajax is disabled in the browser and the file field works correctly.

I would like to just disable ajax for this form but I don't see how. I don't see any #ajax elements in hook_form_alter() or hook_field_widget_form_alter().

You can force the buttons to submit normally by unbinding the javascript events using something like this in a form alter:

// Disable ajax upload for file field
drupal_add_js("jQuery(function() { jQuery('#edit-field-image :submit').unbind(); });", 'inline');

It would be nice if there was a way to not have the javascript bound in the first place by manipulating the $form (or something else).