How to export data from drupal to Excel? I've inherited a Drupal site. I need to extract the main page data out of the site to be able to import it into a different system, but I've never used Drupal and the site is live so I need to tread carefully in order to extract the data without affecting the site.

Currently the website has lots of content pages for manufacturers. Each manufacturer has a name, description, some images and other (mainly text) data. Say, for example, there are 2000 of these manufacturers. What I'd really like to be able to do is export an Excel file (or XML file, whatever) so each field has a different column in the spreadsheet, and each drupal page (i.e. each manufacturer) is a different row in the export spreadsheet. Ideally the images will be exported as full URLs in a column in the spreadsheet.

When I log into Drupal and click the 'content' button at the top, it gives me a list of every page on the site. I can filter this to only show 'Manufacturer' pages. When I edit a specific manufacturer page it gives me a form containing all of the editable fields for that manufacturer, prepopulated with the data to edit. I just need this information for each manufacturer dumped out into a spreadsheet.

So as a complete Drupal noob, where would I start in doing this? Would I just go straight to the database and try to piece it together (if so, is the data stored in a single table, or will there be some major queries involved in doing this - any pointers about which tables to look at would be greatly received) or is there a tool for getting a bulk export of this kind of thing? I guess I could even create a web page which displayed this information in an HTML table and just scrape it from there, but ideally an export would be nice.

You are in luck! There is a module for that. (I love saying that!)

Views Excel Export
Views

This is an extension for Views module, which pretty much can list any data from Drupal's DB; users, content, comments and any other entities. You will have to install the Views module and then install the Views Excel Export module which will export the list generated by Views to an Excel file. Without any code! Brilliant isn't it?

If you need instructions on how to install a module in Drupal, you can follow Installing modules (Drupal 7) on Drupal documentation.


Editable message after registeration is there a way to make this message controllable from back end which appear after user registration.

   $message = t("Thank you for registering at $site_name. Your application for an account is currently pending approval.<br/> Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.");

because it contains HTML it can't be done by string override.

Anything inside a t() function can be overridden, you need to paste the exact contents into String overrides in settings.php or use the String Overrides module


GET request of more than one resource I'm working with services 7.x-3.12, I need to create a web service in order to get a kind of "associative request" between : books(table stored in db) and categories(another table) those two tables are linked by entity_id

I can GET books (retreive, index) same for categories, but how to get Book A -> categorie A ? or the book list of category A

How can I make it work (the get service)?
P.S. book is a content type (node), categories are taxonomy(taxonomy_term)

The short answer is, you can't. I have an issue posted to hopefully make this, and other filters, a reality soon.

In the mean time, you can however create a custom service resource that uses POST, and from there build a custom callback function to return your desired results.

Alternatively, you can use the Views JSON module (a sub module of Views datasource) or Services Views to easily create a View (with contextual filters, normal filters, sorts, etc) that returns JSON data to you via GET.


Drupal module for download limit Is there any Drupal 7 module there, that can restrict any user, based on role/privilege, number of downloads per day. For example, 'x' type of user can download 10 files/day.

I don't think such module exist. But you can write your own module.  Download Count may help you while writing your custom module.


Upload large file to azure storage and link it in Drupal I have some large Files (>3GB) to upload to a Drupal (running on azure). Because of the size of the files, I think i need to upload it to the azure storage (with Azure Storage Explorer) and then use the file in Drupal. This all works fine so far.

But: When I create the content page, I can't find a way to browse the azure storage instead of the local File system?

I use Windows Azure Integration. But this just gives me the possibility to upload a file to a azure storage blob. When I try this with a large File in the Drupal installation, it takes forever (ok, I didn't wait until the end). I am looking for the other way around: upload file to azure storage. Use this file in Drupal.

Does anyone have a solution? Or how would you solve the problem?

Using the proposed Remote File Source worked for me when I choose "File Attach". I have to upload the file to the web-server though and not to the azure storage. But doing this with filezilla does the job.

How about the Remote File Source module?

  Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.

I haven't tried it, but it looks stable with only a couple of bugs


Changing values in preprocess view function I want to preprocess view to alter a field based on another field. I am able to print the value but not change it.

I did this:

function MYTHEME_preprocess_views_view__VIEWNAME(&$vars){

     kpr($vars['view']->result['0']->field_field_name[0]['rendered']['#markup']);
}

Which prints the correct value.
But when I try to change/unset the value it does not work. Both of these do not work.

 unset($vars['view']->result['0']->field_field_name[0]['rendered']['#markup']);

 $vars['view']->result['0']->field_field_name[0]['rendered']['#markup'] = '';

I also tried another way  which prints the value but does not change it:

 unset($vars['view']->result['0']->_field_data['nid']['entity']->field_name['und'][0]['value']);

Note: I am rewriting the results of a field with view UI.

The MYTHEME_preprocess_views_view($vars) hook is executed at the end of the process to build a view. The purpose of the views_view.tpl.php is a general wrapper for all elements of the view. The result of fields have been builded and rendered and they have been stored in the variable $vars['rows'].

If you want to change, alter, unset a view, we can do in different phases. Between them, i've chosen the pre-render phase:

function HOOK_views_pre_render(&$view) {
  if(isset($view->name) && $view->name == 'YOUR_VIEW'){
    // kpr($view);
    foreach($view->result as $r){
      $r->field_field_NAME[0]['rendered']['#markup'] .= '. ADDING TEXT TO CHANGE THE RESULT';
    }
  }
}

These are the stages that are given by Views API (you will find it in the views folder). Maybe one of them is more useful:

hook_views_pre_view(&$view, &$display_id, &$args) {}

  Allows altering a view at the very beginning of views processing, before
    anything is done.

hook_views_pre_build(&$view)

  This hook is called right before the build process, but after displays
    are attached and the display performs its pre_execute phase.

hook_views_post_build(&$view) {}

  This hook is called right after the build process. The query is now fully
    built, but it has not yet been run through db_rewrite_sql.

hook_views_pre_execute(&$view) {}

  This hook is called right before the execute process. The query is now fully
    built, but it has not yet been run through db_rewrite_sql.

hook_views_post_execute(&$view) {}

  This hook is called right after the execute process. The query has
    been executed, but the pre_render() phase has not yet happened for
    handlers.

hook_views_pre_render(&$view) {}

  This hook is called right before the render process. The query has been
    executed, and the pre_render() phase has already happened for handlers, so
    all data should be available.

hook_views_post_render(&$view, &$output, &$cache) {}

  Post process any rendered data.


Add a filter to my view before executing I have a view and I want to get it's results.

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->execute();

If I have 'nid' filter added to my view, I can modify it and get my view filtered.

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->display['page']->handler->handlers['filter']['nid']->value['value']=180;
$nview->display['page']->handler->handlers['filter']['nid']->operator='=';
$nview->execute();

But what do I need write to add a filter if no filter present in view settings of my view?

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();

//some code here

$nview->execute();

UPD: Unfortunately, I can't use hook_views_query_alter because I need to use my code in my custom function which accepts view's name as an argument.
My target is to alter any view which name passed as an argument to my custom function.
So I need to alter filter/query only if I need get view's result and the view executes from my function. But if the view executes from it's page or block it needs to be executed without altering.

Another way is to add the filter as an exposed filter in the view and then set it programmatically like this:

// Set created date range filter.
$item = $view->get_item($display_id, 'filter', 'created');
$item['value']['min'] = $settings['min'];
$item['value']['max'] = $settings['max'];
// Disable exposed filter in UI, for programmatic filter.
$item['exposed'] = FALSE;
$view->set_item($display_id, 'filter', 'created', $item);

That should come before $view->pre_execute();

You can also add a completely new filter in a similar way, by building up a valid $item to use with $view->set_item.


AngularJS implementation I'm trying to use AngularJS in Drupal 8 template.  My objective is to get the power of drupal as a backend to do content query, and AngularJS as a front end to make a single one page application. I'm implementing AngularJS in drupal module with name drupal_ng. The complete code is in https://github.com/agungsuyono/drupal_ng.  However, I'm wondering whether my implementation is not correct.  Because I didn't see the result as expected; it seemed ng-controller didn't work in the HTML template. The javascript controller that I wrote did not bind to the HTML template.

Here are some of the code of drupal_ng module. I really appreciate for any help.

drupal_ng/drupal_ng.module

    <?php
    /**
     * Implements hook_theme().
     */
    function drupal_ng_theme() {
      return array(
        'drupal_ng_view' => array(
          'template' => 'view',
          'variables' => array('title' => NULL),
        ),
      );
    }

drupal_ng/drupal_ng.libraries.yml

    angularjs:
      version: VERSION
      js:
        'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js':  {type: external}

    drupal_ng:
      js:
        js/drupal_ng.js: {}
      dependencies:
        - drupal_ng/angularjs

drupal_ng/src/Controller/DrupalNgController.php

    <?php
    namespace Drupal\drupal_ng\Controller;

    use Drupal\Core\Controller\ControllerBase;

    class DrupalNgController extends ControllerBase {

      public function viewDrupalNg() {
        $title = t('Hello!');
        $build['myelement'] = array(
          '#theme' => 'drupal_ng_view',
          '#title' => $title,
        );
        $build['myelement']['#attached']['library'][] = 'drupal_ng/angularjs';
        $build['myelement']['#attached']['library'][] = 'drupal_ng/drupal_ng';
        return $build;
      }
    }

drupal_ng/js/drupal_ng.js

    var myApp = angular.module("myModule", []);

    myApp.controller("myController", function ($scope) {
      $scope.message = "This is AngularJS";
    });

The word "This is AngularJS" should appear in the HTML template below but it didn't.

drupal_ng/templates/view.html.twig

{{  title }}

        {{ message }}

This is the screen shoot of the result in Chrome browser using AngularJS debugger.  From the debugger, it seems that the message "This is AngularJS" is already there, but it didn't appear in the screen.

I would like to just comment on this, because my answer is not exactly a solution to your particular implementation, but I do not have enough reputation :/

I will just say that in my opinion your approach to the problem is wrong. Because you are loading Angular as a JS library from Drupal, you are adding lots of unnecessary overhead to your application, especially to the initial load of the page and you are defeating the purpose of using a Front-end framework.

In my experience, using a Front-end framework like Angular is a solution to completely decouple the Front-end from the Back-end. So my suggestions is just that:

Create a regular Angular application and inside that Angular app you create a sub-folder that will contain your Drupal application.

And from this point on you can use REST webservices for fetching the data from Drupal. The core Views module combined with the core REST module provides out of the box Drupal functionality for this, and in addition Symfony provides the JsonResponse class that you use for sending simple responses. ( I really recommend using the JsonResponse, because it just bypasses Drupal's entire rendering system)

This way, you have nice Back-end code that can be organized in different controllers, which will callbacks to routes exposed as REST endpoints and a completely decoupled Front-end layer that will only call a number of select REST methods on different routes.

PS: for more information on this topic, please search for the term Headless Drupal, and you will find lots of helpful info


How to add extra save buttons In Drupal 7, my user profile page is getting really long. If someone sets or forgets a password, they don't see the Save button, and hence their password is not changed.
Using the Corolla theme, how can I add an extra save button right below the password fields?

You need to implement hook_form_alter() and duplicate the Save button.

Something like this should work:

function yourmodule_form_user_profile_form_alter(&$form, &$form_state) {
  // Copy the existing submit button into the account fieldset.
  $form['account']['submit'] = $form['actions']['submit'];
  // Give it a high weight to have it show below the other fields.
  $form['account']['submit']['#weight'] = 50;
}

However, I suggest you also look for ways to shorten your form, maybe through theming or by using http://drupal.org/project/field_group.


File upload drag and drop Possible Duplicate:
  Drag & drop files into drupal site?

I need to implement drag and drop file upload functionality.  Does Drupal make this easy somehow?  Should I use a JS toolkit, like Dojo or Mootools?

Although -dev for D7, You could try http://drupal.org/project/dragndrop_uploads

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.


Reoccurring weekly billing that only a user can see, based on a schedule in another node I need to setup a timed event, weekly, that will create a node or "billable event" based on a given pricing schedule (values on another node) and based on a date in another field on a different content type.  And now if that wasn't confusing enough, I need for only the specific user to be able to see it.  I'm open to any ideas as I really have no idea where to begin.

I will suggest using these modules:
https://drupal.org/project/nodeaccess (to restrict node access per role or per user)
https://drupal.org/project/elysia_cron (flexible cron jobs)

Create separate cron job with flexible schedule where you can put all you custom logic with related nodes.


Drupal 6 term based view not translating vocabulary terms I have a dilly of a pickle here. Please do help if you can.

I have a site that uses internationalization translation to translate content.
Some of the content is not translating.
Specifically a "view" that is of type "term".  All my other views are translating correctly.

Here is the configuration page of my vocabulary

Here is an example of the term translations.

Here is the view for the taxonomy term countries.
The view here seems to not have the correct  filters available. For node based views, you can add a filter called "node translation-language" and set it to filter on the current language.  But with views based on taxonomies there is no equivalent "term translation-language".  How are we supposed to filter out the extra taxonomy terms from the view.

This is an example of a view based on nodes that has the filter "term translation-language"
My term based view is missing this filter

Here is the Countries view in action...notice that Haiti shows up for every language in it's non translated form (note that those are 3 different Haiti's)

Can someone please explain what I need to do to get a term based view translating and not showing extra terms?

Thanks,

David

I think what you are trying to do is something along these lines:

Which here gives me:

And when I change the language, eg:

it then gives me:

I've set my vocabulary here up like so:

with translations (quickly done just for this so pardon the potential sloppiness)

and nodes translated like this (pardon the silly titles):

so if you are getting different results, check to make sure all of the various places you can set a language are similar.


Parent term doesn't show child term entities My website has  two taxonomies school and city, are connected.
Here's city term list

Newyork(parent)
-Yonkers(sub-term)
-Albany(sub-term)
-New Rochelle(sub-term)
-Utica(sub-term)

And school term has a city_field connected (with term referenced) to city taxonomy.
 I can list schools according to city terms(eg:newyork schools)

Problem:
All city terms show  schools. That's ok. But parent term(newyork) doesn't show subterm(Yonker, Albany, New Rochelle,Utica) schools.

Newyork (parent term) shows schools if only newyork selected. It should show other city schools under newyork.

What I did:

I've tried to add parent relationship, no result. I've tried to add parent relationship to contextual field, taxonomy term:name field and criteria and many combinations. No result...

Here's view structure:
I've done with prkos help term to term relationship view . You may check here if you want to see how it'shandled.

Any help or article guide with this would be awesome . Thanks

I was able to solve it, although there may be a more elegant solution. I had to use two additional modules: Views arg parent term and Views Contextual Filters OR. There are a lot of LEFT JOINs so it's not very performance friendly.

The problem actually lies in listing the children terms (Yonkers, Albany, etc) of the term page you're currently viewing (Newyork), along with the term of the page itself (Newyork). Once you solve that it's simple to pull information about the terms from School term vocabulary that reference your City terms (through a Relationship).

List the term and its children on the term page

Start with Taxonomy Term View type (Block Display), filter to list only City vocabulary. Add Fields for Term ID or Term name to display Cities just to test that all are there (you should see all Cities listed).

You can add the relevant School terms (that reference the term listed) although it's not yet necessary, we can take care of it when we get the correct contextual filtering.
Add a Contextual filter Term ID from Taxonomy term Category, and configure it with these options:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
City
Filter value type: Term ID

You can now test this filter by entering a City term ID into the Preview field, it should limit the results list to show only that City views row. (You can see all of the results by entering all into Preview.)
To list child City terms add a Relationship Parent term from Taxonomy term Category, don't require it or it will limit the results beyond what is useful to this case
Add another Contextual filter Term ID from Taxonomy term Category, make it use the Parent Relationship from the previous step and configure it similarly to the last one, only change one option: filter Type:
Taxonomy parent term ID from URL
Under Views Query settings tick Contextual filters OR, best to apply it only to this Block so it doesn't interfere with your other Displays if you have them.

This will make all Contextual filters work with an OR operator instead of AND. In your case it will allow Views to filter by term ID of the page you're viewing OR it's child, so both options will be valid.

You can now enter a city term ID twice into Preview and you'll see both that term and its children. For example, let's say your Newyork term ID is 18, if you enter 18/18 into Preview you'll see all the terms from your City vocabulary.

Show which terms reference the ones listed
To show the School terms that reference City terms add a Relationship Taxonomy term using City. You can require it, this will exclude all City terms from the list that aren't referenced by any School terms. Since it's a School terms list we want in the end it doesn't make sense to allow any "empty" rows.
Add a Field Taxonomy term: Name and make it use the Relationship from the previous step (field_city).

You can now see the relevant School terms in your results! You can now remove the City TID and Name fields, if you don't need them for the testing, so you only end up with School terms.
Place the Block on your City term pages and it will list School terms that reference that term or its children. You'll probably only want to place it on first level term pages (Newyork) because it doesn't work in reverse, it won't display parent terms when you're viewing child term pages, it will only list their own related ones.

Add the third Taxonomy level
Just in case someone needs it, if the Vocabulary has the third level, to show grandchildren on parent pages you have to add another Relationship Parent term, make it use the earlier Parent Relationship, don't require it.
Add another Term ID Contextual filter and configure it like the second one, with Taxonomy **parent** term ID from URL, only make it use the second Parent Relationship.

You'll now have to enter the parent TID thrice to make the Preview work 18/18/18. (This doesn't affect the Block, arguments are handled automatically.)


Date API: Proper method of parsing dates I'm working on a simple event sign up module. The functionality is split in two modules, one which provides an Event content type with title, description and date (from - to) fields, and the second with sign up functionality and sign up window dates for Event content type. The problem is that I don't seem to find a way to properly parse and do comparisons and calculations on the event/signup dates.

Date API documention is quite light on specifics on this area, so it has not been much of a help.

How can I use the Date API to obtain DateObject from the event date stored on the node?
How can I determine whether the stored event is an all day event?

How can I use the Date API to obtain DateObject from the event date
  stored on the node?

Offhand, I'm not 100% sure the right way to do this. It sounds like you want to use the DateObject to perform some calculations -- not just to run through a theme field_formatter. This date issue thread has some code kinda trying to use date fields and their values, but doesnt help much.

Simply because I can understand it (and have used this module myself) I recommend trying out the sub-module of Date, date_api, and an additional 3rd party module: field_extract.

With field extract you can easily (and correctly) access a fields value for instance as a timestamp:

  // Extract from a date, this extracts the first value and provides a
  // formatted date output, uses the specified format, by name.
  $event_timestamp = field_extract_value('node', $node, 'field_event_time', 0, array('format' => 'timestamp'));

You can then use the DateAPI to create a DateObject:

$date = new DateObject($event_timestamp);

  How can I determine whether the stored event is an
  all day event?

Use the date_is_all_day() function found in the date_api module, it compares 2 date fields to check if they encompass a full day.

 function date_is_all_day($string1, $string2, $granularity = 'second', $increment = 1) { ... }


Two commands won't work with drush I try to run typical commands like drush cc all or drush pm-uninstall while in the folder of my local site (in my pc, win 7 sp3), and yet I get error say:

  "'mode' is not recognized as..."
  "There were no modules that could be uninstalled".

I've never seen the first error in windows 7, and I do have modules to uninstall, so why won't I see a list? thanks,

Based on this comment https://github.com/drush-ops/drush/issues/58#issuecomment-23716869 it has something to do with your PATH variable. Fix it and the error should go away.

  Added C:\Windows\System32;C:\Windows\SysWOW64 to PATH in Environment
  Variables.  Both errors gone the 'mode' one and the other one about
  console window width.


How to create a node programmatically in Drupal 7? I know you can create nodes programmatically by creating a node object and then firing node_save() but I don't actually want to store the node in the database.

Is there a way to create nodes of a specific content type in code that show up in the Find Content screens and work with views etc, but are not physically stored in the database.

The reason I ask is that I have a view that lists a series of nodes of a specific content type, but I want to create a custom node in that list that uses PHP to set the content dynamically but if I fire node_save() will it node get stored in the database every time the module is executed.

I'm also using node reference to link to these nodes so my programatic node will need to work with node reference too.

You're trying to do a lot there.

You can do most of what you want without having a node in the database. I think node reference is a sticking point.

Views can be used with a number of back ends, you can get it to point to a different database or index your data with solr and use solr views to search and access your content, there is an issue with using completely external content but you can get round that. Sparql views can allow you to get data from a triple store.

You can populate a node object with fields and use theme node to display it without using node save.

A common pattern is to create stub nodes, which contain only a reference to an external resource and use nodeapi hooks to load the data when the node is viewed. This is often less work and would allow you to use the standard search and node reference functionality.

Without knowing quite why you don't want to save the nodes, it is difficult to make a concrete suggestion.


Not able to set the time for auction products, using the Ubercart Auction module I guess this question is for those of us using the ubercart auction module

This module allow you to make auction of products (of the Product Content Type generated by Ubercart). When you create a new product you have to fill the Auction Settings and in there you have to set the expiration date and time of the auction.

My problem is that I see the field to set the date but no input is shown to fill the time (i.e.: 18:00:00).

The README file of the module says:

  Use the "Expiration date and time" field to set the expiration time for the auction.

then I understand that this is either a bug (I already posted the issue) or I have a mis-configuration on my site.

I think you just need to upgrade to the latest dev version, this is what the same fieldset looks like for me with that version:

This is on a blank Drupal 7.14 installation with only the required modules for uc_auction enabled:

Ubercart Auction - 7.x-1.x-dev (2011-Dec-11)
Ubercart - 7.x-3.1
Date - 7.x-2.5

It would be a good idea to make sure you have the latest stable versions of those contrib modules installed as well; if I remember rightly the date_popup module used to have an issue with setting the #default_value of a date_popup type field, so the problem might just be that.


How do I disable digest subscription notices for all users? I expect to do this in the database rather than through the UI. I thought I'd done it already, but it seems they are still going out. Any help would be much appreciated.

I'm not sure you'll really be able to force everyone out of getting Digests, but if you look in

/admin/config/system/subscriptions/userdefaults

In the Settings Fieldset, above Type of links to send field, there's a checkbox for Digest mode. If that's checked, it may be causing you problems.
I'm looking at this in D7.

My main thought is that user preferences for a digest may override the defaults you've set up, so I'm not sure you'll really be able to completely shut down this feature. I'm also not sure why you'd want to. Getting pinged about a new comment every time it happens can overwhelm someone's inbox if even a moderate conversation is going on. My team likes giving a digest every 3 hours as the default because it will give users about 2 updates a day, but won't overwhelm them unless they change the settings themselves.


Add a views exposed filter block into my theme using template.php I would like to render a views exposed filter block in my node theme. This is what I am doing:

function MYTHEME_preprocess_node(&$vars) {
   $search_form = drupal_get_form('views_exposed_form');
   $search_box = drupal_render($search_form);
   $vars['search_box'] = $search_box;
}

This way I could simply add variable $search_box into my theme and the filter block would be displayed.

I have confirmed and 'views_exposed_form' is the correct form_id. The problem is that this is throwing a nasty error that doesn't log the error message. My template gets broken (still appears, but broken) and no error message is logged.

It does work if I try to display, let's say, a regular search box. The code is the same, all I have to do is change to the search block form id (search_form) like this:

$search_form = drupal_get_form('search_form');

Right now, I am almost pulling my hair, have searched up and down the web. Any help is appreciated. Thank you!

You're actually having an error if you check the php logs:

PHP Fatal error:  Call to a member function get_exposed_input() on a non-object in
.../sites/all/modules/views/views.module on line 1950

You can't just call drupal_get_form('views_exposed_form') because drupal wouldn't know which exposed form you want to render. Remember that a view or view display have its own exposed form.

If you check where the error is, you'll see that it's caused by not having a view object in the form_state variable.

What I suggest you do is use the Admin Block UI (/admin/structure/block) and just restrict which node types where you want to display the exposed filter.


How do I change a product variaton through an image field? Using Drupal Commerce you can set fields in the product entity which can function as attribute selection fields. The visitor can use them to switch the variations of a product.

I created a field called SIZE which allows the visitor to switch the variations of a product. This works fine. Now I need to allow to change the variation by clicking in a image of the variation. See my capture to get the idea.

I create an image field and set it to 1 value, but the "Attribute field settings" area didn't show up. In this area you can check "Enable this field to function as an attribute field on Add to Cart forms."

I thought this module could help, but as far as I see it is not useful for this: https://www.drupal.org/project/commerce_fancy_attributes

Try using Commerce Fancy Attributes along with Field Extractor Module

This module provides:

A formatter for reference fields
A views field for reference fields (called "Field extracted from entity referenced through $field")

This module uses field_view_field hook

  Returns a renderable array for the value of a single field in an
  entity.

  The resulting output is a fully themed field with label and multiple
  values.


Flagging content via email notification using Rules, Flags and Drupal 7 I'm using the Flag module to allow authors to approve (or flag) certain types of content that anonymous users upload.

Everything is working well, but I would like to extend the approval feature so it can be done using a notification email as well.  I can trigger an email without issue using the Rules module, but I would like to embed the non-ajax version of the flag link to simplify the approval process.

Is it possible to retrieve and send a 'flag' link via email using only the Flag and Rules module?  Otherwise, what would be the best way to go about allowing users to flag content via automated notification emails?

As far as I know, the Flags module in Drupal 7 has full Rules support since several months, but only in the -dev version, so have you tried something never than the beta?

This ought to be enough to accomplish what you ask for, but I may misunderstand where you are having problems with the integration.


Form State in the field instance settings form How do I access the global form state of the field instance settings form. hook_field_instance_settings_form only takes two arguments - instance and field.

Use case - Ajax refresh of an options list

You can't access it directly, what you can do it use #after_build which will be called with the $form_state, but this will happen at a later step.


How do I change the HTML structure of the primary links in Drupal 7? I read what reported in How do I change html structure of menu (primary links for example) to my own? but the accepted answer for that question is for Drupal 6.

How do I create a function that adds a CSS class or ID to a single "li" and "sub li"?

It's useful to refer to the API documentation when you have an idea of what to do in version 'X' of Drupal and you want to translate the method to work in version 'Y'.

In this instance, the following API page will prove useful:

http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7


displaying content using entityfieldquery I want to display content based on term ids using below method.If I include the below code in for loop it works but thats not appropriate way to call loop for each index value.Here $all_children[] contains term ids. Can anyone please tell me what is wrong with below code , or any suggestions?

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'escorts_product');
$query->propertyCondition('status', 1);
for($i=0;$i<=20;$i++)
  {
   $query->fieldCondition('field_product_sub_cat', 'tid', $all_children[$i],'=');
  }
$result = $query->execute();
if (isset($result['node']))
  {
    print "nomeer";
    $nids =  array_keys($result['node']);
    nodes = node_load(array_keys($result['node']));
    if ((node_load($nids, NULL, TRUE)))
      {
       foreach($nids as $nid)
         {
          //content
         }
      }
   }

I think this is the right way because it works for me. Error was in below line.

$query->fieldCondition('field_product_sub_cat', 'tid', $all_children[$i],'=');

Correct way to compare with array is:

 $query->fieldCondition('field_product_sub_cat', 'tid', array("$your_array_variable"));


Permit only one role to download files I'm trying to set up a new D8 site. It needs to include some "subscriber only" type functionality. There is one content type which is little more than a title, a file, and one extra field for sorting purposes. There is also a View to make this visible to the end user. What I'm trying to do is let the unauthenticated site visitors see the list, but not download anything while the authenticated users in a specific Role are allowed to download those files. The site's owner will be taking care of adding people to it manually. It isn't too frequent of an event, apparently.
I see how to make the View itself only available to people in that Role. I see how to make content as a whole unavailable to the unauthenticated (Anonymous Users) in /admin/people/permissions. Am I going to have to disable Anonymous Users' access to all content and then enable it one content type at a time?  Or is there a better way to achieve the goal?
I'm open to scraping the approach I've taken (Content Type, File field, and a View) and doing something else entirely if it would be better.
Note: We're currently using private files as the default storage location.

It's good you're using Private file system. That is one level of control you need to prevent the files from being freely downloaded.
Other levels of control are the Page (Views list), Node, and File fields.
You could create two different Views, one without the file field, and one with it, and use Role permissions on those pages. In this case you'd have to make nodes not accessible to all, which isn't fortunate if you want to control other types differently. There are modules, though, that you can use to set up different node type permissions.
But in your case I think it makes the most sense to have different File permissions. This way you don't have to duplicate Views or control node access.
You can do this with the Field Permissions module.
All can see the nodes and Views pages, but only special Roles will see the File field that has those special permissions.


Drupal Rooms Show Booking Unit Name in Confirmation Email I have had a drupal rooms site running for a few months now, and the client has come back to me asking for the selected room to be shown in the confirmation email sent to the customer.

I have had a look through the available tokens that come with rooms, but there isn't one to display Bookable Unit Name, probably because it can be a multiple value field if more than one room is booked.

Or even a way to display the Rooms Unit name in the line items, then that would print in the notification email under the line items token?

I have gone to products > room products > manage display > line items, but there is nothing there to display the name.

You could create a custom token to pull that info in.
Hook_token_info is the hook that makes a token available.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_token_info/7

While hook_token is the hook that actually replaces it.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_tokens/7

Since it's a multivalue field, you may need to include a numeric operator on the end (e.g. node_room_field_room_number:0) for the delta on the field.


Smiley icons in the comments I installed the Smiley module for drupal 7.
Filtered enabled smileys for plan text format.

I want to enable the smile in the comments field where the body of the comments is a plain text.

You need to rearrange text filters - make smiley filter last. If you put it before "strip HTML tags", it will add tags but they'll be stripped.


update user data without a form from a module in my drupal system i use the basic_wemail module along with a custom module i created that creates a postfix mail alias for a new user, so we can provide users with free email addresses as part of the service.

The basic_webmail module has a user form where a user can input their email address and logins for the module to save the email credentials as serialised user data. Since we dont want users to update this information and only to use the email credentials created by our custom postfix integration, but user_update(), user_insert() and user_presave() all work on a form submit, is there another way to pragmatically update a users serialised data?

$edit = array(
    'basic_webmail_username' => $full_username,
    'basic_webmail_password' => $password,
  );

user_save($user, $edit);

echo('lol that was easier than i thought');

user_save();


Custom display for text field I am new at Drupal, so I apologize if I am missing something obvious.

I have a content type that has some fields. This field is text and I want to have a custom "Field Display" for it.

I can do the JavaScript JQuery stuff to have a div expandable with a click, etc, but I don't know how to make that happen.

How do I change the field display for a field so that I can customize its look (with css or some elements or javascript). I don't want to put this stuff in the content of the field, as I don't want the content author to have to put that in every time.

Thanks.

You can find the CSS class or id by installing firebug in your Firefox installation. It let's you point and click on every area of the page.
If this is not enoug install the Theme Developer module (http://drupal.org/project/devel_themer). It helps you to find the appropriate theme merhods and template files to tweak the output to your needs.

If this is all strange stuff, make yourself familiar with basics about drupal theming. This is a good starting point: http://drupal.org/documentation/theme


How can I track statistics on my site's user population? I have a site with a fairly large number of users and I am trying to track statistics on them over time.

For example, users can have:

Any combination of four roles
One of two values for gender
One of two values for an additional field

I want to track each combination of role, gender, and additional attribute separately.

This has lead me to use Views to create a huge number of content panes, each with filters set to catch a particular combination.  I then added all of these to a panel, where I view them once a week and write the numbers down.

However, I now want to add an additional field with 6 additional values.  Creating all those combinations in Views is going to be a mess.  Is there a more efficient way to do this rather than clicking through the Views UI, creating a content pane for each possible combination, and then adding that in Panels?

Other than the option you present, I think you have two choices.

One is to wire up a hook_menu(), and create a path that accepts role, gender, and the other field value.  You would then pass this into a db_select() or EntityFieldQuery(), and return the results in HTML table form.

The other option, and the one I would recommend, would be to make up a View over your users, add in your roles and fields, and then use Views Data Export to export as XLS or CSV.  You can then analyze your data in a third-party tool like Excel.

Why do I recommend the later?  Leverage your tools for their strengths.  Drupal is good an managing and serving up content (raw data counts).  Tools like Excel are great at analyzing data.  These three fields are what you need to look at now, but this could change in the future.  Having a full export of the raw data will make this much easier down the road.


Adding custom module pages to the Solr index We're using Drupal 6.
I have written several custom modules that generate a number of pages. All the paths are "given" to drupal using hook_menu() so the system is fully aware of how to access them.

However, if I search for something that I know is on a page I have created with one of these custom modules, it does not appear in search results. We're building a lot of content using custom modules which are pulling data out of pre-existing databases. We need these to be searchable.

How can I add these new paths and the content on these pages into the Solr index?

Apache Solr Search Integration is a replacement for the core content search.
This means that the output of your custom modules will appear in the Solr index, if the modules create nodes.

If the content returned by the custom modules is dynamic, then they need to create dummy nodes that they will be updated with hook_nodeapi(). When ApacheSolr rebuilds its index, it loads the node with node_load(), which then invokes any implementation of hook_nodeapi(), passing "load" as operation parameter.


Stop caching for a specific node type Drupal 7 I'm working with a node type that has several custom fields. The values of these fields need to refresh on each page load, but because of Drupal's caching feature, they don't. What is the best way (simplest way) to stop this content type from caching?

See if http://drupal.org/project/cacheexclude can do it for you. If not you need to create a module that will implement hook_init. Inside of that hook you need to load the node from arg() from there see if the node is of a certian type; if it is disable the page cache.

<?php
  // Get the current active node object if present.
  $node = menu_get_object();
  if (!empty($node) && !empty($node->type) && $node->type == 'page') {
    drupal_page_is_cacheable(FALSE);
  }
?>


Render a form from an existing module We are just trying to gain a deeper understanding of Drupal forms and how to manipulate and render them as needed.

We have a module installed which allows uses to edit and create content through a form.  The module renders the form on its own edit/create page.  We would like to render the edit/create forms on a different page with other content.

Below are a few functions which we believe render the forms. (if not which function should we be looking for??)

/**
 * Page callback for creating a customer profile of a given type.
 */
function commerce_addressbook_profile_create($account, $profile_type) {
  // Add the breadcrumb for the form's location.
  commerce_addressbook_set_breadcrumb($account, $profile_type);

  $profile = commerce_customer_profile_new($profile_type, $account->uid);
  // The submit handler needs an indication that the profile was just added.
  // The regular is_new property gets unset after save is complete.
  $profile->_is_new = TRUE;
  module_load_include('inc', 'commerce_customer', 'includes/commerce_customer_profile.forms');
  return drupal_get_form('commerce_addressbook_customer_profile_form', $profile);
}

/**
 * Page callback for editing a customer profile.
 */
function commerce_addressbook_profile_options_edit($account, $customer_profile) {
  // Add the breadcrumb for the form's location.
  commerce_addressbook_set_breadcrumb($account, $customer_profile->type);

  // If the profile is referenced by an order, make sure it gets duplicated.
  $profile = clone($customer_profile);
  if (!commerce_customer_profile_can_delete($customer_profile)) {
    $profile->previous_id = $profile->profile_id;
    unset($profile->profile_id);
    unset($profile->revision_id);
    $profile->is_new = TRUE;
  }
  module_load_include('inc', 'commerce_customer', 'includes/commerce_customer_profile.forms');
  return drupal_get_form('commerce_addressbook_customer_profile_form', $profile);
}

What is the process for calling these functions (if they are the ones we are looking for) into a TPL page?

EASY TO READ COMMENTS:
I have added the follow to template.php within my theme directory

function THEME_preprocess_page(&$variables){
    module_load_include('inc', 'commerce_addressbook', 'includes/commerce_addressbook.user');
    $variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);
}

I have also included the following with a page tpl file.

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

This results in the page returning a 500 error. (commenting out the variables line allows the page to load.)

You don't want to be putting that much PHP code into a tpl template file. Your menu item should have two parameters (user account, and profile type) and the page callback is specified as the desired function.

If you are doing this another way, you still need the user object and customer profile. In a preprocess function or in a custom page callback, you can create the form as a variable:

template.php:

// you can load a user account in various ways, ill assume this is behind a user path
$account = menu_get_object('user');
// you will need to verify this is the right function to use.
$customer_profile = commerce_customer_profile_load(profile_id_here);

$variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);

in your tpl file:

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

I am not familiar with the commerce_addressbook module, but there is a chance you'll need to include the file that defines those functions too, especially if they do not live in a .module file but live in a .inc file.

In which case, you'd need:

module_load_include('inc', 'commerce_addressbook', 'filepath/filename');
$variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);


Need Ability to Override Default text field When the textfield is left blank, a default value populates. But when a value is placed into the text field, that value should show on the front end. It currently does not.

I have  admin rights to edit,view any pages. I have enabled everything for adminstartor roles under User Management->roles. Even then am unable to update a new value to that field. It is populating the default value.

You can change the field default text in the field settings page of the content type, for example:

admin/structure/types/manage/[your-content-type]/fields/[your-field]

You need to change [your-content-type] and [your-field] by the real values on your drupal website.


Drupal showing blank page after migrating to a local server (this question has been asked on Stackoverflow so I apologise for the repitition)

Firstly some background,..

IVe started a new job as PHP developer with a company that hosts 2 Drupal (6.x) sites.

While I have years of experience in PHP, Drupal ( and indeed off the shelf content management systems in general ) is a new one on me. Still, there is loads of documentation and its not rocket science, so no problems there.

The server environment is IIS (live server 7.0, locally 7.5) IIS is a totally new beast to me too, so it adds to teh learning curve.

I have successfully gotten a clean install of Drupal (7.x) to run locally, so I know the server is up and running correctly

The problem happens when I try to pull down the live site. I have replicated the database locally, and I know that it is connecting, however when I try to run the local site I get a blank page with the following source c ode:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
  <head>
    <?include '_inc_head_common.tpl.php';?>
  </head>

  <body id="body">

      <?include '_inc_header.tpl.php';?>
      <?include '_inc_content_3col.tpl.php';?>
      <?include '_inc_footer.tpl.php';?>
  </body>
</html>

So it seems that it is getting to a point and no further..

has anyone encountered this before or could someone point me in the direction that I should be looking at?

Thanks

Kevin

Seems like you are using PHP shorthand. Can you change it to a proper  and see if that helps? Please see if the path is correct since drupal is using relative path (base_url, base_path). Also please update the $base_url in the settings.php if you have.


Unable to save variable(s) from a custom form I want to create a custom form with a few textfields and then use variable_set to save those textfields as variables.

I am not able to save the variable with the code below.

Question: I do not see the drupal message on hitting submit and when I go to the 'variables' table, I do not see the variable 'id_event'. I have tried clearing all caches several times.

Code below is from *.module file of my custom module "mymodule"

    function mymodule_menu() {

     $items['example_form'] = array(
         'title'        =>  'Progress Numbers',
         'description'  =>  'Form to enter variables that will be shown on Progress Update Block on Front Page',
         'page callback'    => 'drupal_get_form',
         'page arguments'   => array('example_form_form1'),
         'access arguments' => array('access administration menu'),

     );

     return $items;
 }

The callback function:

 function example_form_form1($form, &$form_state) {
  $form['id_event'] = array(
    '#type' => 'textfield',
    '#title' => t('Id Event'),
    '#required' => TRUE,
    '#default_value' => variable_get('id_event', 7),
  );

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

Submit Function

function example_form_form1_submit(&$form, &$form_state) {
  variable_set('id_event', $form_state['values']['id_event']);
  drupal_set_message($id_event);
}

Modify your example_form_form1_submit function as follows

function example_form_form1_submit(&$form, &$form_state) {
  variable_set('id_event', $form_state['values']['id_event']);
  $id_event = variable_get('id_event', '');
  drupal_set_message($id_event);
}


How do I implement hook_views_query_alter()? I try to implement hook_views_query_alter() in Drupal 8.
I found a hint, that it has to be in my_module.views_execution.inc.
I tried it, but the hook never gets called.

function mymodulename_views_query_alter(&$view, &$query)
{
    var_dump('foo');die;
}

Do I have to register the *.inc file anywhere? Do you have a documentation source on this topic?

In Drupal 8, best practice is to use hook_views_query_alter() in MYMODULE.views_execution.inc file. If instead it is placed in MYMODULE.views.inc, it will be executed only when rebuilding the views cache, causing your view to function properly once and then not subsequently.

MYMODULE.views_execution.inc file should have this structure...

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  // Only for my_view view.
  if ($view->id() == 'my_view') {
    // some action
  }

}

Ref: views_test_data.views_execution.inc


Jquery ticker in a drupal block isn't working I'm trying to add this ticker type to my site: http://cektkp.com/twittermarquee/.

I've created a new module to do so, and this is my module dir structure:

 module stocksTicker:
       1. stocksTicker.info
       2. js/
       3. images/
       4. stocksTicker.module

    js/:
       1. marqueeTicker.js

    images/:
       1.fade-trends2.png
       2.trendtip-pointer.gif

I enabled this module and added css to the block configuration from here: http://cektkp.com/twittermarquee/front.css.
I copied the .js file from here: http://cektkp.com/twittermarquee/twitmarquee.js to path/to/module/js/ directory.
Images are in path/to/module/images dir too.

This is my stocksTicker.module file:

/**
 * Declare what blocks are provided
 * by this module.
 */
function stocksTicker_block_info() {
  $blocks['bseTicker'] = array(
    'info' => t('BSE'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Return a rendered view of the block.
 */
function stocksTicker_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'bseTicker':
      $block = getBSETicker();
      break;
  }
  return $block;
}

/**
 * This function does the real work of getting
 * the stocks info and marking it up & produces
 * it in a renderable format.
 */
function getBSETicker() {
  $path = drupal_get_path('module', 'stocksTicker').'/js/marqueeTicker.js';
  $content = "

Trending topics
";
  $stockEntry = array("Stock1","Stock2","Stock3", "Stock4", "Stock5", "Stock6", "Stock7", "Stock8", "Stock9", "Stock10");
  foreach ($stockEntry as &$stock) {
       $content = $content . "
" . $stock. "This
is description.
";
  }

$content = $content . "

&nbsp;&nbsp;

Trending right now:

Why?Source: What the Trend?

&nbsp;

";
  $block['content'] = array('#markup' => $content,
                            '#attached' => array('js'  => array($path),),);'
  return $block;
}

When I try to view the changes, I do get the list and I do see the css working just fine but none of the jquery feature works (scrolling/ tooltip anything..) which is the main aim of this exercise. Please tell me how can I fix this.

I'm new to drupal so please excuse any silly mistake that I might have done.

In your js file, you are depending on the $(document).ready(function () {} ); to initialize your jquery stuff, but your content is being added via ajax ( if I understand correctly ), so this code will never fire, as the document is already loaded at that point.

This is the reason behaviors have been implemented in drupal.

If you change this to initialize your code in a drupal attached behavior, like so:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.stockTicker = {
        attach: function( context, settings ) {
            page.trendDescriptions = {};
            loadTrendDescriptions();
        }
    }
})(jQuery, Drupal, this, this.document);

or something of the sort, that may fix your problem. You'll need to look into the once() function, to prevent the code from running every time any content is added to the page, but for now, try a behavior and see if you get js behavior


How to check if 2 email fields have the same value entered during content creation? I'm trying to create a custom signup content type and I'm wondering if there is a way to check if two email fields have the same value entered. Similar to typing in an email twice to make sure you have the correct email down.

If the two email fields are not the same an error needs to appear upon saving.

I'm not using a webform for this, it's a custom content type.

Assuming this question is about D7, you could use the Rules module and create a (rather basic) rule like so:

Rules Event: Before saving content
Rules Conditions:

Content is of type "custom signup".
Entity has field (related to your 1st eMail field).
entity has field (related to your 2nd eMail field).
Data comparison: the value of the 1st eMail field is NOT equal to the value of the 2nd eMail field.

Rules Action: Show a message on the site (of type "error").


Add fieldset with add more button using ajax I have one fieldset like,

Education Qualification:
1. School, 2. College, 3. Course, 4. Year (these are the fields which will be in this fieldset)

Now I want to do "Add more" button under this fieldset then it will add same another fieldset as per user's requirement. If anyone have an idea so let me know on this. I can use Webform or Content Type also. Which will be suited for this type of form.?

This is easy to achieve with a content type and the Field collection module.  With that you can set up a qualification field of type field collection, then go to admin->structure->field collections and add the individual fields (School / College / Course).  If the qualifications field has a "Number of values" setting of "unlinmited" then you'll automatically get the "Add more" functionality as you described.

You may need to also use Field Group or Field Collection Fieldset in order to make the fields appear in a fieldset.


How do form #states interact with dialog action buttons, if at all? A dialog can be fired by a link formatted as such:

    Some path displayed in modal dialog.

If the contents of /some/path are a form, then drupal takes its action buttons and drops them into a "footer"

 in the dialog. This seems to take into account the initial state of the buttons -- so if submit has the disabled attribute by default then the corresponding UI button gets the .is-disabled class applied. The "real" form action buttons are rendered but set to display: none.

However, I've got #states set up on my submit button with

$form['actions']['submit']['#states'] = [
  'disabled' => [
    ':input[name="field_fivestar_rating[0][rating]"]' => [
      [
        ['value' => '-'],
        ['OR'],
        ['value' => '0'],
      ],
    ],
  ],
];

The "real" form submit button is updated correctly according to its #states attribute, but the same cannot be said for the corresponding dialog button. It seems to be static based on the initial state of the submit button.

Is this expected behavior? If so, is this something that deserves an issue in the queue? Seems like an oversight and usability concern.

This doesn't answer the question itself, but since I struggled for a while to get this all syncd up I figured I should drop the work into something that people might hit from google. To get the attributes all syncd up you can use the following js file:

(function ($, Drupal, drupalSettings) {
  var handler = Drupal.behaviors.commentsRatingFlexible = {
    attach: function (context, settings) {
      // If our form is loaded in a modal, then the context is
      // the form itself. Therefore we cannot look for the form
      // inside of context. As such, we need to check for forms
      // that exist in both situations an handle accordingly.
      var formInstances = [];

      // This would be the class for your particular form
      $('.comment-rating-flexible-form', context).each(function () {
        formInstances.push($(this));
      })

      if ($(context).hasClass('comment-rating-flexible-form')) {
        formInstances.push($(context));
      }

      // Lookup any rating-flexible-forms and disable the submit
      // button by default, since it shouldn't allow an empty val
      // for the fivestar field (if it's present)
      for (var k in formInstances) {
        var $form = formInstances[k];
        var $submit = $('.form-submit', $form);
        var $fivestarSelect = $('[name="field_fivestar_rating[0][rating]"]', $form);

        if (!$fivestarSelect.length) {
          return
        }

        handler.dialogSubmitButtonHandler($form); //must be called first
        handler.observeAttributes($submit);

        if ($fivestarSelect.val() == '-' || $fivestarSelect.val() == '0') {
          // #states don't apply on form load, only on change,
          // so we need to disable the form button here and
          // sync that onto the dialog's button
          $submit.attr('disabled', "");
        }
      }
    },
    /**
     * Syncs attributes from real form-submit onto dialog submit btn.
     *
     * @param $form
     *   The form contained in the dialog
     */
    dialogSubmitButtonHandler: function ($form) {
      var $drupalModal = $form.parent();

      // If the form is loaded outside the context of a modal, don't execute
      if ($drupalModal.attr('id') !== 'drupal-modal') {
        return;
      }

      // The actual modal and the rest of its contents won't exists
      // on the initial load. As such, we need to add a watcher to
      // the DOM to find out when our dialog action buttons exist
      // so that we can act on them then.
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          if (!mutation.addedNodes.length) {
            return
          }

          mutation.addedNodes.forEach(function (node) {
            var $node = $(node);
            if (!$node.hasClass('ui-dialog-buttonpane')) {
              return;
            }

            var $formSubmitButton = $('.form-submit', $form);
            var $dialogSubmitButton = $('.form-submit', $node);

            // Watch for our custom $.event from observeAttributes
            $formSubmitButton.on('attributeUpdated', function (e, attrData) {
              $dialogSubmitButton.attr(
                attrData.attributeName,
                attrData.attributeNewValue
              );
            })

            observer.disconnect();
          })
        })
      })

      observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
      })
    },
    /**
     * Fires an event when an element's attributes change.
     *
     * @param $el
     *   The jQuery element being observed
     */
    observeAttributes: function ($el) {
      var observer = new MutationObserver(function (mutationList, observer) {
        var eventData = [];

        mutationList.forEach(function (mutation) {
          if (mutation.attributeName === 'style') {
            return;
          }

          var attributeName = (mutation.attributeName === 'class') ? 'classList' : mutation.attributeName;

          $el.trigger('attributeUpdated', {
            'attributeName': mutation.attributeName,
            'attributeNewValue': mutation.target[attributeName],
            'attributeOldValue': mutation.oldValue
          })
        })
      });

      observer.observe($el[0], {
        attributes: true,
        attributeOldValue: true,
      });
    },
  }
})(jQuery, Drupal, drupalSettings);


Why go for Drupal 7? I'm planning a huge site which in a couple of years should be hosting a million documents.

I thought of going for D7 but I found that most of the modules are in Beta or even Alpha releases.

D6 is pretty stable.

My main requirement is Taxonomy, CCK and Views since I'll have lot of inter-related nodes organized under different hierarchies(taxonomy) and will be shown using Views.

If I go for D7 then I'll have to regularly keep updating site with new releases and bug fixes.

I want some suggestion.

I would start with D7 if I were you. Taxonomy and CCK are in core in D7 and Views is really stable in my experience, even though there's only a release candidate at the moment.

Do not underestimate upgrading a site from D6 to D7. Yes, it is possible, but you want to save yourself a couple of headaches and start with D7 right away.

Drupal 7 is much more scalable and since you're planning a huge site, you're going to need that.

You write that you will be hosting documents; does that mean that you're storing the document contents in the database, or are you hosting downloadable files like .pdf's and .doc's? D7 is much better for managing files, as is explained in this Acquia blog post.


What's the preferred method of creating different page templates Basically, I want to give my articles and blog entries a different class on the body so I can style them independently.

I am given to understand that the best way to do this is with creating custom tpl files

I'm working in a custom built theme that is pretty much running just on a page.tpl.php and a stylesheet.

How would I do this easily in Drupal 7? I tried this method for drupal 6 but it didn't seem to work.

This should by there by default.

For example, the body classes on my test site look like this for a simplenews node:

<body class="html not-front logged-in one-sidebar sidebar-first page-node page-node- page-node-90 node-type-simplenews toolbar toolbar-drawer i18n-en" >

As you can see, there is node-type-simplenews, among many other things.

Those classes are defined in template_preprocess_html() and are using in html.tpl.php (not page.tpl.php, unless you've overriden that. If so, you need to duplicate the logic in that function for your page.tpl.php.


Drupal 7 easy breadcrumb module hides breadcrumbs When I install the easy breadcrumbs module my breadcrumb disappears.
I am wondering if there is a particular settings that I need to change. If I am on the homepage the breadcrumb home is displayed. As soon as I install the easy breadcrumb the breadcrumb is hidden. I tried clearing the cache but that didn't fix the problem. I also changed the theme to see if it was a theme issue but that didn't fix it.

Have a look at the Easy Breadcrumb project page. The answer to your question is in the Configuration section of it. Here is a quote from module's project page:

To start using it, just go to the admin modules page (URL admin/modules/list), locate and activate it under the category "others", then go to the blocks list page (URL admin/structure/block) and locate the block named "Easy Breadcrumb", and configure it like any other block (region, URLs, etc.).
The configuration page of this module is under Admin > Configuration > User Interface > Easy Breadcrumb (URL admin/config/user-interface/easy-breadcrumb).
Configurable parameters:

Disable the default Drupal's breadcrumb.
Include / Exclude invalid path alias as plain-text segments.
Exclude some paths from the segments to be generated.
Include / Exclude the front page as a segment in the breadcrumb.
Customize the title of the front page segment in the breadcrumb.
Include / Exclude the current page's title as a segment in the breadcrumb.
Use the real page's title when it is available instead of always deducing it from the URL.
Print the page's title as a link or as plain-text segment.
Use a custom separator between the breadcrumb's segments.
Choose a transformation mode for the segments' title.
Make the 'capitalizator' ignore some words (words not to be capitalized).


Spam module for human spammers I'm currently using the Honeypot module for blocking spam and it does a great job at blocking bots but too many human spammers manage to get through. I tried Mollom but that blocks out too much ham which is definitely bad for me. What can I use in addition to honeypot to block human spam?

From my pesonal experience I can recommend you:

General protection

http:BL module to block most of bots from just viewing your site
CAPTCHA module with reCAPTCHA or Captcha Riddler submodule (other are useless) to protect registration and password reminder forms

Anonymous comments protection

listed above captchas (but that will disable caching on pages with comments)

or

AntiSpam module with Akismet

That will stop at least 99% of spam.


remove Anonymous user from "Entity Reference" users list in my case a project has a technical team, so project content type has a user reference field which is created by Entity reference module. but in node creation form, an "Anonymous" user is available to select.

how can I remove it?

One way would be to create a View with an "entity reference" display to show all users with an id greater than zero, then use the Views "Entity selection mode" for your entity reference field:

You can choose the View you just created and the anonymous user will no longer show.

There's also the Entity Reference View Widget module which provides an advanced version of this functionality, though it's still in alpha.


How do I retain user input in a form after submission? I am working on a simple form for searching a collection of marriage licenses. It consists of a select box where the user may choose to search last names, first names, or both, and a text field where they type the name they're searching for.

Everything is working fine so far, except that the user input is not retained after the form is submitted.  For example, if I choose "Last names" and enter "Olsen", after the form is submitted the search box will be empty and the select box will revert to its default of "Both first and last names".

Here is my buildForm() method:

public function buildForm(array $form, FormStateInterface $form_state){
    // The select box.
    $form['target'] = [
        '#title' => $this->t('Search'),
        '#type' => 'select',
        '#options' => [
            'both' => $this->t('Both first and last names'),
            'last' => $this->t('Last names'),
            'first' => $this->t('First names'),
        ],
        '#default_value' => $form_state->getValue('target'),
    ];

    // The search box.
    $form['q'] = [
        '#title' => $this->t('for'),
        '#type' => 'textfield',
        '#default_value' => $form_state->getValue('q'),
    ];

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

    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Go'),
    ];

    return $form;
}

As you can see, I've tried using #default_value to set a default value by calling the form state to get whatever the user picked/entered.  But alas, this does not seem to have done it.

How do I get it to display the user input in the form after submission?

Try adding $form_state->setRebuild(TRUE); to your submitForm().  Quoting from here:

  Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and \Drupal\Core\Form\FormSubmitterInterface::redirectForm() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect.

I think that as you have stubbed a submit handler, but not implemented anything (and so are presumably not calling parent::submitForm either), it is not considered "done", so it is not redirecting; but it is not rebuilding based on the new $form_state either, because you haven't told it to.  So you end up just seeing the original form.

As well as setting rebuild to true you may also need to $form_state->disableRedirect(TRUE) to get the desired behaviour of staying on the form, but with inputted values showing.


Manually flush ImageCache cache? Im using ImageCache but I've since modified some of the original image files in my Drupal site. The reason being I needed to modify images uploaded to nodes but don't want to manually add them all again. Can I now manually flush ImageCache's cache?

Thanks

Just display list of all presets, there are links for flushing presets.
Presets list is available at /admin/build/imagecache/list

Flushing urls of respective presets would be /admin/build/imagecache/[preset_id]/flush


Where do I place helper files? I would like to place some (PHP)functions in a helper files, which requires across modules and themes.

Do I have to create a new module or I can place a simple helper file with list of common functions, what is the best practice for these kind of functions in drupal 8 ?

Yes, create a utility module, so your consumer modules can declare a dependency to the utility module in their .info.yml file. Optionally to keep the admin UI clean you could use hidden: true in the utility module's .info.yml

(I assumed you are speaking of a very drupal-specific helper lib, not some general purpose library like e.g. Guzzle that would go into composer)


Time field not available I'm trying to set up a CSV import to create nodes. On the Mapping page for the feed import, several of the fields in my target node type are not listed in the dropdown box to select as a target field. I don't know why.

Some info:

All the fields that aren't showing up are of type Time, added by the cck_time module. I've not seen any specific issues with mapping this field type, but it does seem like the common denominator here.

I set up the feed, then added extra content fields. The fields that aren't showing up were all added at this later point, although others that were added at the same time are. I've flushed cache several times.

Several of the fields share the same label (ie: "Earliest booking"), although obviously not the same machine name. (For instance, there's one "Earliest booking" field for each weekday, and the field is nested inside a group for that weekday). Other fields that share identical labels are showing up in the Mapping dropdown.

The feed isn't Attached to the content type (under Basic Settings), it uses a standalone form. It uses a Node processor and the selected Bundle is the content type.

Any ideas? Why would a content field not show up in that Mapping dropdown? Have I missed some vital step?

Found a solution @ https://www.drupal.org/node/2085879

Where you can use the patch by agileadam @ https://www.drupal.org/files/issues/timefield_feeds_support-2085879-6_7.x-1.0-alpha2.patch

On top of which you can also apply a patch from pontus.froding found @ https://www.drupal.org/files/issues/0001-adds-weekly-repeat-to-times.patch which also as an added bonus adds the weekday repeating to the import

The patch is still to this date not imlemented into any release and the issue of time field not showing up in feeds was that Feeds doesn't know the field type and the Timefield module didn't have any feeds hooks in it, to make feeds module aware of it.

Implementing this patch manually (for now) seems to be the only solution.


Drush: Listing all modules installed on multiple servers I have many servers installed on the same network, and I want to check them all to see if they need updates.  This requires me to login to each server and run drush up and check the results.

Can someone suggest a better way to do this, maybe a script or something similar?

You can add Drush Aliases for each site, and then add an alias containing all your sites.

Then:

$ drush @allsites up


CKEditor toolbar missing when conditional field becomes visible I use the D8 Conditional Fields module to make a CKEditor field (author bio) invisible until there is something in another field (author). When I type something in the author field, the author bio field becomes visible, but it doesn't include a CKEditor toolbar. It appears that CKEditor initialization is not done on fields that aren't initially visible. Any way to overcome this?

Not finding a built-in way to avoid the problem of missing CKEditor toolbars on conditionally displayed fields, instead of using the Conditional Fields module, I use the Asset Injector module's JS Injector to inject this JavaScript into the node add/edit page (note that the authors field is an entity reference):

var el = document.getElementById("edit-field-authors-0-target-id");

if (el) {
  showHideBio();
  el.addEventListener("change", showHideBio);
}

function showHideBio()
{
  var el = document.getElementById("edit-field-bio-wrapper");

  if (this.value) {
    el.style.display = "block";
  }
  else {
    el.style.display = "none";
  }
}

Seems to work just fine, but open to suggestions for improvement. Thanks to @Taggart Jensen for the idea.


How do I solve this memory usage limited problem? I have more than 100,000 articles to move from Drupal 6 to Drupal 7.

How do I solve this memory usage limited problem?

module: migrate d2d

Currently migrate module does not support batch query for to get value of nodes. You need to apply one patch which work for you.


Can MySQL 5.6 be used with Drupal 6 and php 5.2.17 A server admin is looking to update the production mysql from the latest version 5.0 to latest 5.6. We are running a Drupal/Pressflow 6.22 and php 5.2.17. I believe this is going to bring on the apocalypse when it comes to things not working, but I need some concrete reasons on what may break and why.

Do anyone have any experience running a drupal 6 on mysql 5.6? Or PHP 5.2 with MySQL 5.6?

I know mysql 5.1 in acted strict mode in MySQL.

Anyone have any insight into if these will play nice with Drupal 6 and it's modules?

MySQL 5.6 works fine; using the mysqli driver. PHP 5.4 works after fixing a couple of notices, and php 5.2 works without any modifications.

In your settings.php file change $db_url = 'mysql://...' to $db_url = 'mysqli://...' to use the mysqli driver; it's that simple.


Render database values using 'markup tags' other than 'table tags' to keep things simple, I am trying to load a specific set of values from a database, which using the following code works:

foreach ( database::load() as $bdt) {
  $row[] = (array) $bdt;
}

$content['table'] = array(
  '#type' => 'table',
  '#rows' => $row,
  '#empty' => t('No entries available.'),
);

Which produces the following:

                  5.00 PM

                  1:00 PM

                  1:00 PM

                  3:00 PM

                  3:00 PM

                  5:00 PM

But I don't want to use table formats and I want to use other html markup tags, such as "
" or "
". I have tried to change the '#type' => 'table' to '#markup' but it will not render anything.

$content['table'] = array('#markup => '
time ' . $row '
',);

I have searched a few sites about it, but all point information back to using table format.

The working code was extracted from the "example modules" using the DBTNG example.

Please can anyone tell me how to go about it?

Many Thanks

As you do not like table.html.twig, I suggest to write your own table theme. As a reference, you can look how this is done for field_ui_table in core.

Or you use inline_template:

$content['table'] = [
   '#type' => 'inline_template',
   '#template' => '{%- for row_value in row -%}
 time {{ row_value }}
{%- endfor -%}',
   '#context' => ['row' => $row],
 ];


Default login page little change I want the following;
In the default login page, I want to delete this line:
Nieuw wachtwoord aanvragen (Also DELETE "request new passord) on this site: http://www.deklotvaarders.nl/user

Also I don't want that users can request new password.
Where to do that?? Which file?

Thanks so much,
Greetz,
Pieter-Jan

The best way to accomplish this is using hook_form_alter() with custom module. For example,

function your_module_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register') {
    drupal_set_title(t('Create new account'));
  }
  elseif ($form_id == 'user_pass') {
    drupal_set_title(t('Request new password'));
  }
  elseif ($form_id == 'user_login') {
  drupal_set_title(t('Log in'));
  }
}


Which table are field instance widget settings stored? Is it ok to update these everytime a node is saved? I wanted to utilise the Minimum/Maximum values of Integer field instance settings. I'd like to know where these are stored in the database, and whether it's feasible to use hook_node_save or presave to update these min/max fields. The site will use feeds to mass import nodes, and I was wondering if it'll be ok to update these values everytime the feed import is run?

Also is there an easy way to grab these min/max values on node view?

You can use field_info_instance() to get the details, and field_update_instance() to save them:

$entity_type = 'node';
$field_name = 'field_name';
$bundle = 'content_type';

// Load
$info = field_info_instance($entity_type, $field_name, $bundle);

// Get
$min = $info['settings']['min'];
$max = $info['settings']['max'];

// Set
$info['settings']['min'] = 1;
$info['settings']['max'] = 10;

// Save
field_update_instance($info);

I can't see any problem with updating those values during a mass import, but I can't see the benefit of doing it for every single node save. It would probably be better to run it once at the beginning/end of the import process.

You can use the same code in hook_node_view() to retrieve the values for display on the node page if you need them.


add ajax form-like functionality inside node I have an article on my Drupal site and need to add some calculations to it (to better illustrate a topic). It means, three textfield inputs and a button, after clicking the button a calculation should take place on server side (not in javascript, because I want this calculation to be in php on server side) and then comments should be displayed below the textfields.

The problem is, I would like to have all of it inside node, not below it - for better user experience.

Inserting input and submit button via wysiwyg works fine. Then, I need to use raw jquery ajax command and do everything manually - it should be possible.

So before doing this, I'd like to ask if there is a simpler way?

E.g. ajaxifying webform is documented. So, if the whole webform could be treated as one token, it could be inserted into wysiwyg using token filter inside node content. But webform as a token? - can't find such solution.

Build your webform, or Form api form, grab its ID and then follow my answer to insert this form into node's content through a custom module of yours

Cleaner way to do it.


how to set default_value for list_boolean field equal to 1, not 0? I'm using this code to add a list_boolean field to my user entities on D7.20.  The field is added, but the default value shows up as unchecked, whereas I've tried to be careful with

  'default_value' => array(0 => array('value' => 1)),

to make it show up checked.

Can someone explain what I'm doing wrong here?

Update: Actually this seems fine, see explanation in answer.

function MYMODULE_create_user_field_binary($myField_name, $label, $desc) {
  $field = array(
   'field_name' => $myField_name,
   'module' => 'list',
  'type' => 'list_boolean',
     'settings' => array(
     'allowed_values' => array(
       0 => '0',
       1 => '1',
      ),
     'allowed_values_function' => ''
     ),
     );
  field_create_field($field);

  $field_instance = array(
      'field_name' => $myField_name,
      'entity_type' => 'user',
      'bundle' => 'user',
      'label' => t($label),
      'description' => t($desc),
      'default_value' => array(0 => array('value' => 1)),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(
                'display_label' => 1,
                ),
        'type' => 'options_onoff',
       ),
      'settings' => array(
      'user_register_form' => 1,
    )
    );
  field_create_instance($field_instance);
}

Actually, the behavior here is a bit weird.  The box shows up unchecked when the field examining an existing user (e.g. when browsing /user/1/edit when logged in as admin), but it does show up as checked when browsing to /user/register when not logged in.  So that was a little confusing.

Upon further investigation, the new field isn't populated at all for existing users, i.e. the database entries simply don't exist.  So those will have to be created manually it seems -- at which point I can specify whatever value I want as the "default".  In my case:

INSERT INTO field_data_MYFIELD
(entity_type, bundle, deleted, entity_id, revision_id,language,delta,MYFIELD_value)
SELECT 'user', 'user', 0, users.uid, users.uid, 'und', 0, 1 from users;


What would cause contextual filter settings NOT to save? I have a view in Drupal using a contextual filter.  I save the changes about what to do when a value is passed.  After I hit save, everything revers back as if nothing ever happened.

Has anyone seen this before? Any suggestions?

In the end, the "simple" answer worked. I deleted the filter and added it back.  I'm not sure if I configured it wrong to begin with or if something "bigger" was at play.


Why doesn't print module_invoke('user', 'block', 'view', 0); use template files? If I invoke the user login block using module_invoke it doesn't use block-user-0.tpl.php. If I drop the block in the right sidebar and print $right it does use block-user-0.tpl.php.

Also, why will it only print the block once so that printing $right and module_invoke only results in one login form?

The code module_invoke('user', 'block', 'view', 0) eventually calls user_block('view', 0). The user_block function returns an array in this case; that's just how hook_block works. The documentation for hook_block says:

  If $op is 'view': return an array which must define a 'subject'
  element (the localized block title) and a 'content' element (the block
  body) defining the block indexed by $delta. If the "content" element
  is empty, no block will be displayed even if "subject" is present.

If you want to know how to render this block, check this comment on the theme_block documentation page.


How to identify and target a form element? A similar question has been asked before: How do you identify a form element?

I am using the Devel module and dpm($form) outputs the object nicely:

But I can't set/change the default value of a custom field. How do I target set the default value to 164 in this case?

$form['question_node_form']['field_points']['und']['0']['value']['#default_value'] = 164;

The above does not work and the points_field is blank.

EDIT (complete function):

function custom2_form_question_node_form_alter(&$form, &$form_state, &$form_id) {
    drupal_set_message("Form ID is : " . $form_id);
    dpm($form);
    $form['question_node_form']['field_points']['und']['0']['value']['#default_value'] = 164;
}

You're calling the explicit hook_form_FORM_ID_alter for a start so $form_id will never be anything except question_node_form.

However the problem is you are trying to target a child of the form array. The top level array is already question_node_form. Your code should look like this:

function custom2_form_question_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_points']['und']['0']['value']['#default_value'] = 164;
}

Debugging removed for clarity. Noticed we removed ['question_node_form'].

Also note you can't pass $form_id by reference (not that it matters) as it can't be changed.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


How to replace links and embedded image references after migrating of content I want to import content from a legacy system into Drupal using the migrate module. The URL structure is going to change.

Some of the content has links pointing to the old content and there are also embedded images with soon to be outdated links.

After migrate is done I'll have a mapping from old urls to new urls and should be able to run a custom script. This script would check for all nodes with old urls and replace it with the new urls and then just node_save() it.

Is this a good approach or is there a better solution?

Btw, I'm also planning on setting up a simple php site under the domain to 302 redirect old urls to the new url.

Writing a script that does a node_load(), search/replace, and then node_save() is definitely the best way to go about it, and I would argue that it is also the "proper" way to handle the situation.  If you go with this approach, you can refine and/or alter the script each pass to account for differences in the URLs.

In the past, I have

Use rewrites in .htaccess
Done search/replace on a database backup file
Put search/replace in a preprocess_page

to handle the situation, and all of these are not ideal, mainly because of slight variations in URL structure.


Votable node content type in D7 I'm trying to figure out the best way of creating a content type that allows for creating nodes that can be assigned to a group and can be voted for in competition with the other nodes in that group. I started writing a module for it by using the Fields API, Node API and Voting API but I want to check to see if I can use an existing module to do this before I get too far into the project.

For example, I want to create a content type called "contestant" and give the content type 3 different brackets it can be assigned to. Then when I create the contestent content and select one of those brackets, the content becomes votable and is ranked against other pieces of content within that bracket.

Any references to existing modules or suggestions would be awesome.

I'm not sure I totally follow what you're trying to achieve, but Fivestar is a very flexible module

https://drupal.org/project/fivestar

I use it to vote for a few different content "dimensions" (2-3 votable fields) and then with views you can output it as a table with click sorting by any one of the ratings fields.


using profile2 login information as billing information in commerce I have a site where people able to buy anything are already loged in. How do I collect from profile2 and apply this information in commerce billing automatically?

You're better to use Commerce Customer Profiles for that information.

Although "billing" is the default, you can add other groups of profile fields as types, e.g "Profile information" etc...

There's a module commerce_customer_profile_type_ui that helps creating new profile types, else you can do it in code via the API.


Creating several users in one request using Services/REST/Json I'm using Services 7.x-3.12 and able to create a single new user using REST/Json post, and that works well.

Is it possible to create multiple new users in one request? I couldn't find any documentation on this and wasn't able to make it work. I tried separating the users with a comma inside the Json body, like so:

{{"username":"testuser27”,"mail”:"testuser27@gmail.com","pass”:"test","roles":"2","status":"1"},{"username":"testuser27”,"mail”:"testuser27@gmail.com","pass”:"test","roles":"2","status":"1”}}

but no success - I get this error:

[ "Missing required argument account" ]

Any help/pointers would be appreciated.

Out of the box no.

But you could write a module that supplies you're own resource that takes multiple user objects.


How to show the brothers taxonomy term? I have a tree of taxonomies, these taxonomies are the menu of my site and they are working with taxonomy_menu module, I am displaying the menu through a view, but I'm only showing the children as low level, for example:

Parent 1

Child 1
Child 2
Child 3

Test 1
Test 2
Test 3
Test 4

Parent 2

Child 4
Child 5
Child 6

Parent 3

If access to view link parent1 show me only:

Child 1
Child 2
Child 3

If access to Child 3 links show me the children of child 3

Test 1
Test 2
Test 3
Test 4

But if access to test 1 show brothers need taxonomies:

Test 1
Test 2
Test 3
Test 4

If filter by parent term works for me but when the taxonomy have more children, but when you have no more children need to show the brothers.

Any idea?

You could create a custom module that looks for the children of that element, if returns 0, look for the parent of the element and print that parents children.

You could also try views, they have a function that helps to deal with results behavior when you don't find any elements related to you query.

Hope this helps.


AJAX callback function has to be defined in the same file? I have defined a textfield that includes an AJAX callback. In another separate file, I have the AJAX callback function defined.

Will this work or does the callback function need to appear in the same file the textfield was defined in?

This is the code I would use.

'associated_element' => array(
  '#type' => 'textfield',
  '#title' => t('Destination Data Element'),
  '#description' => t('Some text.'),
  '#ajax' => array(
      'event'=>'change',
      'wrapper' => 'linked_form_elements',
      'callback' => 'form_editor_linked_form_ajax',
    ),
  ),
);

use form_load_include() in your form definition function. I put this just above the return $form; line.

form_load_include($form_state, 'file_extension', 'your_module', 'your_file_name_without_extension');


How to update a field's value? Like the field_get_items function, is there a function to update a field's value? I want to update a field of type user reference.

In this example I load a node and change the value of a field called field_context and then saves the updated node:

$node = node_load($nid);
$node->field_context[$node->language][0]['value'] = 'foo';
node_save($node);

Use var_dump to show what fields your node contains.


Dynamic select lists (dependent dropdowns) I created 2 dependent dropdowns in Drupal 7. In the first dropdown you need to choose the device, in order to see its attributes in the second dropdown.

When an option from the first list is selected, the Ajax throbber appears but it doesn't seem to be working and I don't get the appropriate options in the second dropdown.

I have read all examples and resources I could find online, but I haven't found how to fix this. Any help would be very much appreciated.

Below I attach the relevant code. Apologies in advance, I am new in Drupal.

function my_module_getdevicesfromrooms() {
  $dropdown1 = array();

  $tabdelimited = file_get_contents("http://.../tabdelimited");

  // some code
  return $dropdown1;
}

/**
 * The device name is required in order to get the attributes using this function
 */
function my_module_getattributesfromdevices($test) {
  $dropdown2 = array();
  $tabdelimited = file_get_contents("http://....");
  // some code

  return $dropdown2;
}

function my_module_form_ajax($form, &$form_state) {
  $form['#prefix'] = "
";
  $form['#suffix'] = "
";
  $options_first = my_module_getdevicesfromrooms();
  $value_dropdown_first = isset($form_state['values']['my_module_deviceurn']) ? $form_state['values']['my_module_deviceurn'] : $options_first;

  $state2 = my_module_getattributedfromdevices($value_dropdown_first);

  $form['my_module_deviceurn'] = array(
    '#type' => 'select',
    '#title' => 'Device',
    '#options' => $options_first,
    '#default_value' => $value_dropdown_first,
  );

  $form['my_module_apply'] = array(
    '#type' => 'button',
    '#title' => t('Apply'),
    '#default_value' => t('apply'),
    '#ajax' => array(
      'callback' => 'my_module_ajax_callback',
      'wrapper' => 'nodes-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['my_module_attributes'] = array(
    '#type' => 'select',
    '#title' => t('Attributes'),
    '#options' => $state2,
    '#default_value' => variable_get('my_module_attributes', ''),
  );
  return $form;
}

function my_module_ajax_callback($form, $form_state) {
  return $form;
}

On your callback function, you need to setup a callback help. Basically getting your form data. Now my code is for D6 so some functions might be slightly different but check this out.
I left some of my tweaks in there. You'll just have to adjust accordingly.  but the big thing is the callback helper function.

function MOD_js_callback() {

// use of ajax callback helper to set form variables again
$form = MOD_callback_helper();

// grab form['datacenter_devices'] data and drop into changed_elements
// simply to not confuse rebuilt form with 'global' form
$changed_elements = $form['datacenter_devices'];

// Prevent duplicate wrappers.
unset($changed_elements['#prefix'], $changed_elements['#suffix']);

// concat status_messages and call drupal_render to render elements array for output.
$output = theme('status_messages') . drupal_render($changed_elements);
drupal_json(array(
    'status'   => TRUE,
    'data'     => $output,
));
}
function MOD_callback_helper() {

$form_state = array('storage' => NULL,'submitted' => FALSE);

$form_build_id = $_POST['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
// Enable the submit/validate handlers to determine whether AHAH-submittted.
$form_state['ahah_submission'] = TRUE;
$form['#programmed'] = $form['#redirect'] = FALSE;
drupal_process_form($form_id, $form, $form_state);

$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

return $form;
}