Hi,

Is it possible to write php code in the options field to automatically and dynamically populate
the list of options from a table in the database?

If it`s not possible, could you point me to another way of doing it?
What I want is that the different options will be the recent story posts on my site.

Thanks

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

RoloDMonkey’s picture

I need exactly the same thing. I have succeeded in adding the fields dynamically using hook_form_alter(). Unfortunately, I haven't been able to get Webform to accurately reproduce the dynamically generated content in the email or the submission view.

I'm very close. If anyone has other pieces to this puzzle I think we can make this work. Maybe even create a new component?

RoloDMonkey’s picture

Assigned: Unassigned » RoloDMonkey

Okay, I have found several other requests for this. I have pointed them all at this thread and closed them as duplicates. I will finish a preliminary hack for this soon.

RoloDMonkey’s picture

Title: Can I put options in a select field from database quary? » Can I put options in a select field from database query?
RoloDMonkey’s picture

Title: Can I put options in a select field from database query? » Can I put options in a select field from a database query?

I have finished a very preliminary hack. I have started documenting what I did, and I am providing the source code that I have developed so far. You can find all of this at:

http://www.irolo.net/drupal_webform_and_dynamic_checkboxes

I hope to polish this over the next few days.

wonder95’s picture

What about the Active Select module?

RoloDMonkey’s picture

I'm not sure that Active Select does what we need. Not only do you have to generate the selection dynamically, but you also have to save a submitted value to the database and retrieve it later.

RoloDMonkey’s picture

Status: Active » Closed (fixed)

I have finished the final version of my dynamicselect component. Documentation and the file are available at:

http://www.irolo.net/drupal_webform_and_dynamic_checkboxes

In addition, a demonstration will be available for a while at my staging site:

http://immaculata.bydesign-area51.com/registration

At this point I think that I have provided enough of a framework for a developer to solve similar problems. I would like to encourage others to expand on what I have done, but I am closing this particular issue for now.

blairski’s picture

Hi RoloDMonkey ,

Thanks for your tutorial and code. I have used it and ammended it to prepopulate the webform with data from the user profile table. That all works fine. However, I am having trouble getting the default value to set. Its probably really simple. I know this issue is closed, but I am not sure where else to post. Can I post my alterations here for someone to have a quick look?

Summit’s picture

Component: User interface » Code
Category: support » task
Status: Closed (fixed) » Active

Hi,

I set this item to active if you don't mind, I was wondering what the status of this component is after release 1.8?
Will your dynamicselect component be part of webform components in this great module?
This way it will be possible to follow up webform development more quicker, right?
Thanks for your consideration already!

greetings,
Martijn

RoloDMonkey’s picture

Martijn,

The dynamicselect component that I created was only to meet my needs. I documented what I did so that other developers could create similar solutions.

I do not currently have any plans to turn the dynamicselect into a "real" webform component. I would love to see someone else build on what I did, but I simply do not have the time.

If you need a particular solution but you are not able to write it yourself, you can try the companies that provide Drupal Services or you can get bids from the Paid Drupal services forum.

RoloDMonkey’s picture

blairski,

Please post your code as an attached file and I will see if it is something easy to figure out.

quicksketch’s picture

I'd certainly be up for including this as part of webform, though I'd like to wrap it into the existing select element as either a separate field or just a checkbox for "Use PHP to generate options" to reuse the existing textarea.

dolittle’s picture

When are you planning to implement this functionality?

I've tried webform 2.x but couldn't find it.

Thanks

quicksketch’s picture

Yes, I've got a lot on my plate but I hope to get to this soon.

blairski’s picture

FileSize
2.77 KB

RoloDMonkey,
Sorry it has take me a while to attach the file. I changed you function _dynamicselect_load_options() to bring in one of the user profile fields (counties). That works fine. I am just getting stuck on setting the default, which should be the users current county that they set in their profile.

dolittle’s picture

There is a beta1 release of webform 2.0.

Will the 2.0 version support this feature?

Please...

quicksketch’s picture

No, the first release of 2.0 will not support this feature. I'm very busy with a lot of things.

Again, patches to add the feature would gladly be accepted as long as they are well-written and included in the current select.inc rather than as a another select list. This feature will only be included in the 2.x version as I'm trying to depreciate the 1.x version.

quicksketch’s picture

Marked http://drupal.org/node/242644 as duplicate.

gordonbooker’s picture

I have downloaded the dynamicselect.zip file and looked at the code. Unfortunately, as a newbie it's beyond me as to how to make this work, or to make it into a patch.
It would be extremely useful if anyone could give some advice as to how to use this code.

Oghnia’s picture

I can't get this patch to work... any help guys

Oghnia’s picture

ok a little update,,

this works,, but for some reason the I can't get the selected fields to display into the submitted email..

I get all other fields but this one,,

is something missing?

quicksketch’s picture

ehowland’s picture

Version: 5.x-2.0 » 5.x-1.3
FileSize
8.81 KB

Here is a patch for select.inc that was made against 5.x-2.0. It adds a php fieldset which contains a boxes for adding php code that creates defaults and for options. In order to see the (collapsed) fieldset the user must have "use PHP for additional processing" permissions.

This patch also makes the Options box optional (since the php generated data overwrites anything in that field) but adds some error checking to make sure that there are either options or php.

Several weeks ago I looked at the differences between 5 and 6 and it looked to me like it might well apply cleanly against 6 but I have not tested it.

ehowland’s picture

Version: 5.x-1.3 » 5.x-2.0
Assigned: RoloDMonkey » ehowland
Category: task » feature
Status: Active » Needs review
FileSize
8.82 KB

UMM. It seems that the nesting caused an error message to show up when it should not have (claiming no data). A slightly better patch.

quicksketch’s picture

Version: 5.x-1.3 » 5.x-2.0
Status: Needs review » Needs work

Thanks for the patch whiteowl!

The approach in this patch seems a bit strange. Rather than evaluating the PHP when showing the form, you're evaluating when creating it. This makes it so that the select list can't contain truly dynamic values, you basically just saving a little bit of work when setting up the form initially.

This patch should be made to work on display, rather than inserting values and then letting Webform use those options as it did before.

ehowland’s picture

I agree that this is strange but I believe that it is not strange how you think it is strange.

Try adding this as the php Options:
return array('c'=>date('c'), 'r'=>date('r'), 'U'=>date('U'));

Off topic here, but I get an error message (which I do not see the source of) about illegal choices if I do not make these associative arrays. Although the error message is different ("An illegal choice has been detected. Please contact the site administrator.") I thought it might be some sort of problem with the special characters, but I do not understand why date('U'), which is just a number, does not work. The patch only evaluates the PHP one time, but I wonder if the function is called several times and the discrepancy of the choices between these calls triggers an error which in turn generates the error message.

When you refresh the form each of these dates updates every time (at least for me).

Every time you generate the form you will see the values from the last invocation of the form in the Options box. This is because (and this is the slightly odd thing) every time the form is generated, the newly generated values are stuffed back in the database so that when the form is processed the data shows up as valid data. Without this step the data does not get entered into permanent storage. This is what you helped me with before in the issue http://drupal.org/node/254169. So the form administrator sees the historical data but the users do not!

So the summary is - yes some strangeness - no it works how you want (I think).

ehowland’s picture

Status: Needs work » Needs review

One other thing I did not notice before is that this makes the reporting modules a bit wierd.

I am mostly interested in the table output and that works fine both for both my interest and for the dates (at least as associative arrays which renders the results to be unchanging - not the most useful case).

The odd behavior comes if you go to the results tab and click the view screen for a transaction. A new form is generated from the data, and that new form will have the current date (from the PHP) rather than the original date. This is OK if you are having your users pick a date format, but not if you wanted them to pick a specific time (One week from now, Two weeks from now, Never). This will not be specific to this date example, but to any changing data (sort of the point for using PHP in the first place). This is a wider issue and its solution will require more restructuring beyond the select.inc file.

coupet’s picture

subscribe

Duncan Pierce’s picture

Status: Needs review » Needs work

subscribe

jazzitup’s picture

subscribe

Ok, I've seen a patch of a patch by whiteowl in #24.
Is it the full patch for the original select.inc, since there is no attached patch in #23?

ehowland’s picture

The full patch is in 24 as an update to the patch that as previously in 23.

jazzitup’s picture

Version: 5.x-2.1 » 5.x-2.0
Status: Needs review » Needs work

There is no patch in #23 and those "-" and "+" signs at the beginning of the lines just don't make sense if I apply #24 on the original select.inc file (I'm using webform 5.x-2.1.1). I've just reversed the logic: all "-" became "+" and now it works, but the result is not so stable.

Summit’s picture

Hi Madjoe, Could you file your patch please?
Thanks a lot in advance,
greetings,
Martijn

jazzitup’s picture

Version: 5.x-2.0 » 5.x-2.1
Status: Needs work » Needs review
FileSize
5.48 KB

Since I don't know which version of webform do you use, here's the entire select.inc in the archive for 5.x-2.1.
It still have some weird bugs and it's not that stable so this code really does need work, and I'm playing with it right now.

@whiteowl: Is it possible that this does not work as select options with this PHP addition to a select component:

$m = db_query("SELECT nid, title FROM table");
$f = array();
while ($nids = db_fetch_object($m)) {
    $obj = check_plain($nids->nid) . "";
    $obj_name = check_plain($nids->title);
    $f[$obj] = $obj_name;
}
return $f;

I've checked the same PHP code on page.tpl.php and I can see the array elements by doing print_r ($f); but I have problems with creating options for my select box by using this method.

Could you please check my select.inc... did I miss something with your patch?

If I try to Submit this custom PHP code while creating a new select component, and go to see the form, I could only see "select..." option with no other options inside of my "php select box", and if I refresh the same page, I can't see that select box anymore - it just vanishes somehow. Maybe we should escape double quotes before storing custom PHP code like this to the database?

jazzitup’s picture

Version: 5.x-2.0 » 5.x-2.1
Status: Needs work » Needs review

I've created a function func() in my template.php that returns array("A", "B", "C").

If I create a select component, this is what is stored in the database within extra field:

a:2:{s:3:"php";a:2:{s:10:"phpoptions";s:14:"return func();";s:10:"phpdefault";s:0:"";}s:6:"aslist";s:1:"Y";}

After I visit the form for the first time, I could only see "select..." as an option in a select component.

After my visit to the form this is the content of the same extra field, but the select component is not visible in my future page visits:

pre_a:3:{s:3:"php";a:2:{s:10:"phpoptions";s:14:"return func();";s:10:"phpdefault";s:0:"";}s:6:"aslist";s:1:"Y";s:5:"items";s:5:"A
B
C";}

Take a look at the prefix "pre_" that is the default prefix for my database tables?! The regular "Default value" becomes "pre_".

lelizondo’s picture

subscribe

EdCazini’s picture

subscribing

marcvangend’s picture

-subscribe-

quicksketch’s picture

Status: Needs review » Needs work

To re-iterate, the approach in this patch is incorrect and need to be rewritten before it is included in the final project. Instead of pulling in the options when configuring the element, the options should be pulled in when displaying the element (or viewing results). This patch needs to be fixed before it's included in Webform.

gterez’s picture

subscribing

Rick Hood’s picture

I am probably way off here, but:

You can put a token in the options field. I have experimented where I put %get[model] in the options field, which will show "blah-blah" as the (one) select option if URL to the form is /mywebform?model=blah-blah.

I know nothing about "token creation" but would there be a way to create a token whose value contains the result of a query to the database that brings back the stuff you want to show here? Then you could just put that token in the options field?

BTW this is all for Webform 6.x-2.3

I tried RoloDMonkey's method above but am lost because things have change so much from 5.x to 6.x-2

ngmaloney’s picture

I put together a 5.x module for dynamic selects. None of the other patches fit the bill for what I needed. It renders the options at display time. I'll gladly port it to 6.x if there is any interest. I currently have the module hosted at http://github.com/ngmaloney/dynamic_select/tree/master

Rick Hood’s picture

Wow that's great. I would greatly appreciate a port to 6 when you get a chance. I am working on a D6 project now that needs this.

Christopher Herberte’s picture

+1 D6, subscribing

hbevan’s picture

+1 for D6!

millenniumtree’s picture

D6 pls
Need it for emails of all employees in company and don't want to show email addresses on the site (neither displayed nor HTML code)

Rick Hood’s picture

I'm kind of desparate to get a dynamically created list of checkbox choices on a webform for a project I am working on (D6 and Webform 6.x-2.3). Wondering if there is some other option. Could I add the check boxes via hook_form_alter with a dbquery in there someplace or would that not work?

In a post above I was also wondering if somehow a token could be created (not sure how to create tokens) that could be put as default for this field.

If all else fails I guess I could forget abotu using webform for this particular form, create a content type for it instead and use messaging to email it.

Any direction anyone can give me would be appreciated. ;-)

John Pitcairn’s picture

Here's an alternate rather crude solution that should work:

Create a markup field as your first field. In there, run whatever you need to generate your array of values (recipient names perhaps) for the form select. For each of those values, create and populate a custom session variable. You might want to use an array that uses some other related value (recipient's email address) as a key, so you can do a lookup later to extract that. Store that array in another session variable (or perhaps a global if you can get that to work). ie:

for($i = 0; $i < count($myvalues); $i++) {
$_SESSION['my_webform_var_'.$i] = $myvalues[$i];
}
$_SESSION['my_webform_vars_lookup'] = array_flip($myvalues);

In the webform select field, hand-populate the select entries with your session variables. You'll need to decide on some maximum number:
%session[my_webform_var_0]
%session[my_webform_var_1]
etc

Note you can't have separate value/display here using this syntax, so just make it the display version.

In the webform advanced settings "additional processing" field, grab the user-selected value, translate that into whatever you need the real value to be (like an email address - here's where that reverse-lookup array comes in handy), and place that wherever it needs to go. Finally, unset all your custom session variables.

Comments?

jphelan’s picture

+1 for D6

bignab’s picture

FileSize
4.54 KB

Here is a 6.x port of the module you put together. I borrowed some of the code from the regular select box in order to email and display the multiple values.

csc4’s picture

Subscribing

ngmaloney’s picture

bignab: Great work!

jwhat’s picture

dynamic_select worked for me in D6 to query a Taxonomy vocab and display it in it's proper hierarchical view.

Here's the code I used in the "options" setting for this form component:

$vid = 5;
$tree = taxonomy_get_tree($vid);
$options = array('' => 'select...');
if ($tree) {
  foreach ($tree as $term) {
    $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
  }
}
return $options;
Summit’s picture

Hi, Where do you put this code from #53 in webform please?
thanks for your reply in advance,
greetings, Martijn

EdCazini’s picture

If you have not already created one, add a new form component of type select, or edit an existing one. Either ways, while creating or editing that select component, there is an Options textarea there, copy and paste the code from #53 above.

Syph’s picture

If you have not already created one, add a new form component of type select, or edit an existing one. Either ways, while creating or editing that select component, there is an Options textarea there, copy and paste the code from #53 above.

I get an error stating

Options within the select list must be unique. The following keys have been used multiple times:

* }

Bartezz’s picture

same problem here, subscribing!

Bartezz’s picture

Bignab and others who got this working,

How should one install this D6 version of dynamic_select?
I've added it to sites/all/modules and enabled the module but it doesn't work.

Do I have to patch my 6.x-2.7 version of webform module like needed when using the 5.x version of dynamic_select?
When I look at the code I see it uses a hook which isn't even available in 6.x-2.7 version of webform.

Please tell me how to get this working!!!

Bartezz

@ quicksketch; will this get into 6.x-3.x? It's a neat feature!

Bartezz’s picture

Version: 5.x-2.1 » 6.x-2.7
Status: Needs work » Needs review
FileSize
2.49 KB

Ok, I've got it working with the code supplied by bignab in #50 and the patch for D5 inserted by hand in the 6.x-2.7 version of webform.module.

To install Dynamic_select for D6;
- download http://drupal.org/files/issues/dynamic_select_6.zip
- unzip to sites/all/modules
- enable the module in admin/build/modules/list

- donwload the attached patch for webform.module 6.x-2.7
- apply the patch

- then in node/[nid]/edit/components you will find you can add a component of the type dynamic_select
- add one and within the settings for this component you can add php under 'options'

Sample code from strikeink, to list the terms of a taxonomy as selectable options;

// change vid to the taxonomy you want to use
$vid = 1;
$tree = taxonomy_get_tree($vid);
$options = array('' => 'select...');
if ($tree) {
  foreach ($tree as $term) {
    $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
  }
}
return $options;

Ofcourse you can implement anything you want as long as it returns an associative array!!!!
See the desciption under the option field;

$options = array(); 
$options["yes"] = "YES"; 
$options["no"] = "NO";
return $options;

Hope this helps others and also hope quicksketch is willing to apply this to webform so the people can create their own components in the future :)

Cheers
Bartezz

PS. If you've downloaded, applied and tested PLEASE post your feedback here even if it works!!! I see many questions on this forum but not too many replies saying "thank you, the solution you gave me worked!". That doesn't help others nor help improving code!

Bartezz’s picture

Another code snipplet...

This one is what I'm using to show titles of nodes of a certain type with a certain term as select options;

$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM {node} node INNER JOIN sgz_term_node term_node ON node.vid = term_node.vid WHERE (node.type in ("hulpverlener")) AND (term_node.tid = 12)');
$arr = array();
while ($record = db_fetch_array($result)) {
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']);
}
return $arr;

Tip: Because I'm not great at SQL I use VIEWS to create a MySQL query which is nice and easy :) Be careful with single and double quotes tho. Don't mix those within the query! And be sure to check_plain the output!

Cheers

occupant’s picture

Thank you! This is just what I've been looking for. I'm able to use views to make the query and it all works as advertised.

I'm using the snippet above (#60), but I want to display the taxonomy term's value rather than it's numeric id - any tips on doing that? My php skills are pretty rudimentary.

Also, what about displaying several query values for each select component (eg. a taxonomy term and node title)? I've been playing with it for a while but ... you know... the sucking at php thing keeps getting in my way :)

James

Bartezz’s picture

Hey James,

Not sure how you are using the snipplet in #60 to show taxonomy terms but anyway... play around with VIEWS!!! In the Views UI when you create a view which isn't anything more than a db query it will give you the query used to create that particular view. That way you can change the snipplet to output anything you want.

If you want to run multiple queries and output the options within the samen select you can do something like this (probably better ways but since you don't know much about php this is probably the easiest);

//define arr as an array
$arr = array();

// do a query
$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM {node} node INNER JOIN sgz_term_node term_node ON node.vid = term_node.vid WHERE (node.type in ("hulpverlener")) AND (term_node.tid = 12)');
while ($record = db_fetch_array($result)) {
  //add each result to the arr array
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']);
}

// do another query
$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM {node} node INNER JOIN sgz_term_node term_node ON node.vid = term_node.vid WHERE (node.type in ("dokter")) AND (term_node.tid = 16)');
while ($record = db_fetch_array($result)) {
  //add each result to the arr array
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']);
}

//when we're done with adding queries to the arr array then return the array
return $arr;

Cheers

ramandeep.kaur’s picture

I need to have a dropdown in webform where I have to populate data from a view (of all the OG's say). Is this possible....??

josi123’s picture

Version: 6.x-2.8 » 6.x-2.7

#60

Thank you! I've been looking for this functionality in Webform for years...
Maybe this will help someone:

If you want the select list to show more than one column from the query just concatenate the columns alias:

For instance, if we want a select showing node title plus node id with some kind of separator ("-"), all on the same line:

$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM {node} node INNER JOIN sgz_term_node term_node ON node.vid = term_node.vid WHERE (node.type in ("hulpverlener")) AND (term_node.tid = 12)');
$arr = array();
while ($record = db_fetch_array($result)) {
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']) . " - " . check_plain($record['nid']);
}
return $arr;

Just use Views to construct the query with the fields you want to show, and put the resulting SQL as the db_query parameter as shown above (to show the SQL query while editing the View you have to preview it). As Bartezz said, don't forget to replace double quotes in the SQL statement with single quotes, ex:
...WHERE (node.type in ("hulpverlener")) ... change to WHERE (node.type in ('hulpverlener')) )

EDIT
Replace single quotes in the SQL statement with double quotes, ex:
...WHERE (node.type in ('hulpverlener')) ... change to WHERE (node.type in ("hulpverlener")) )

Bartezz’s picture

Status: Needs review » Reviewed & tested by the community

Think we can change the status now. Looks like it's working for everyone.
Hopefully it'll get comitted soon!!!

Cheers

pshahmumbai’s picture

Created a small module called 'webfromredirect' to do that :)

<?php
function webformredirect_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'load':
      //Replace this number with your form node id
      if ($node->nid == 6) {

      //SQL query to get the data in the form of nid, title
      $result = db_query("SELECT nid, title FROM {node} WHERE type = 'holy_destination' AND status = 1 ORDER BY title ASC");

      $select_data = '';
      while ($singlenode = db_fetch_object($result)) {
       //Getting the data ready for the webform
        $select_data .= $singlenode->nid . "|" . check_plain($singlenode->title) . "\n";
      }

      //Adding the data to the webfrom
      //'4' is the select element id which I got from devel module Dev load option
      $node->webform['components']['4']['extra']['items'] =  $select_data;
    }
    break;  //case break
  }  // switch end
}  // function end
josi123’s picture

I guess patch #59 doesn't work for 6.x-2.8 version?

Bartezz’s picture

Could be I'll look into it asap (remind me when I forget, am very busy with some projects right now).

Hope that when I provide a 6.x-2.8 patch that everyone will test and post back AND that quicksketch will commit...
It's of not much use and rather contra productive to keep having to create new patches and patch new releases if the code has been reviewed and tested by the community.

Cheers

Bartezz’s picture

Version: 6.x-2.7 » 6.x-2.8
Status: Reviewed & tested by the community » Needs review
FileSize
2.26 KB

Here ya go:

To install Dynamic_select for D6;
- download http://drupal.org/files/issues/dynamic_select_6.zip
- unzip to sites/all/modules
- enable the module in admin/build/modules/list

- donwload the attached patch for webform.module 6.x-2.8
- apply the patch

PLEASE post back when you've tested!!! Also if it is working as expected....

Cheers,

Forget about this... posted a buggy patch.
Will work on this tomorrow....

Bartezz’s picture

Was missing a line in my patch, dunno how that was possible but here's a proper patch.

To install Dynamic_select for D6;
- download http://drupal.org/files/issues/dynamic_select_6.zip
- unzip to sites/all/modules
- enable the module in admin/build/modules/list

- donwload the attached patch for webform.module 6.x-2.8
- apply the patch

PLEASE post back when you've tested!!! Also if it is working as expected....

Cheers,

botris’s picture

I tried this patch just now for the first time, but it works half...
D6 - 6.14
Webform 6.x-2.8

When I try the taxonomy (#53) way, it works. But when I try to get all the titles from a specific node type with a query, I get nothing. The SQL query is directly copied from views.

$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM node node  WHERE node.type in ('training') ORDER BY node_title ASC');

$arr = array();

while ($record = db_fetch_array($result)) {
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']);
}

return $arr;

Please advice

EDIT
Ok I got it working by doing the opposite as discribed in #64. I changed the single quotes from the views query into dubble quotes and now it works.

$result = db_query('SELECT node.nid AS nid, node.title AS node_title FROM node node  WHERE node.type in ("training") ORDER BY node_title ASC');

$arr = array();

while ($record = db_fetch_array($result)) {
  $arr[check_plain($record['node_title'])] = check_plain($record['node_title']);
}

return $arr;

EDIT 2
Doesn't work with Better select.

josi123’s picture

The new patch works (webform 6.x-2.8, Drupal 6.12).
#71 is correct. In the View query, replace single quotes with double quotes.

Bartezz’s picture

Version: 6.x-2.7 » 6.x-2.8
Status: Needs review » Patch (to be ported)

Oops my mistake :)

But I think the patch is ready to be committed then right?
Cheers

Summit’s picture

Yes please, would be great if this would be committed!
Greetings,
Martijn

bwyatt’s picture

All the examples I see above seem to only use the Drupal API database functions, which is great if I want to pull from Drupal. But what about external databases? Would it be possible to use this patch to populate options from another database?

quicksketch’s picture

Version: 6.x-2.8 » 6.x-2.9
Status: Patch (to be ported) » Reviewed & tested by the community

It's been a while since I've looked at this issue, my apologies. As time has gone on, I've become less and less inclined to introduce new "execute arbitrary PHP code" options into Webform. In the 3.x version I'm hoping to remove all execution of arbitrary code, considering it's extremely dangerous potential.

So not being very keen on adding more of what I've been trying to get rid of, I had been avoiding this issue. However, I'm very happy to see the direction Bartezz has taken this, which is to simply move the option to a new component. This is great in a lot of ways, not least of which means it's something that can be added to the 2.x version so we don't have to wait for the 3.x version to come around to get this functionality. I'd be very happy to apply Bartezz's patches to all versions of Webform, since it looks like it's actually a bug/limitation in the API.

Patches are usually marked RTBC when they're ready to go in (rather than "to be ported"). It sounds like this patch has been tested already, right?

Bartezz’s picture

Hi Quicksketch,

It's not really my code. I provided a patch basically just out of what I've scavanged from this issue. Most of the credits go to bignab.
I've been using it for a while now on a semi-production site and have encounterd no problems whatsoever. (well not counting badly formed SQL statements, which will not trhow you a warning nor will it crash, it just doesn't work then).

Thanx for embracing this piece of code which I think will improve webform a lot!

Cheers

Bartezz’s picture

Status: Reviewed & tested by the community » Needs work

I managed to find a bug after all.

When I run an analysis I get a warning;

warning: Missing argument 1 for _webform_dynamic_select_options(), called in sites/all/modules/dynamic_select/components/dynamic_select.inc on line 267 and defined in sites/all/modules/dynamic_select/components/dynamic_select.inc on line 422.

Won't have time in the upcoming 2 weeks to take a look at this. If anyone else has a chance to... please do.

Cheers

omerida’s picture

i tested the patch in #70 succesfully, would love to have this hook in webforms.

DoubleT’s picture

The patch in #70 is great, but what should I do to use profile token?
The default value is not selected.

bradezone’s picture

Do we know if this is working for 6.x-2.9?
I just tried the instructions from #70 and the new dynamic_select component is not showing up.

pixelwhip’s picture

I've also followed the steps in #70 using 6.x-2.9 and adding the 2.8 patch manually. I'm not seeing the dynamic select component on the webform config page or when adding components. Any thoughts on why this might be?

Thanks for all the work, this will save me from the tedious work of creating and maintaining huge select lists!

Bartezz’s picture

Status: Needs work » Reviewed & tested by the community
FileSize
2.51 KB
4.17 KB

Hi all,

Finally had time to take a look at the minor bug mentioned in #78.
I also created a patch for webform 6.x-2.9.

For those who have a problem with dynamic select or the patch => I have this working on latest versions of Drupal core & webform.
If you have problems, try clearing cache. If you have other problems... you probably haven't followed directions.

@DoubleT #80, I have no idea how to use profile token. I reckon you should create an issue in the Post Installation forum on how to load tokens...

Quicksketch will you commit this?

Cheers

josi123’s picture

This is an important funcionality for me. Stopped updated Webform to avoid breaking this patch. I will try the new patch. Thanks again Bartezz!

ikeigenwijs’s picture

Subscribing

bradezone’s picture

New patch/module works great with webform 6.x-2.9

I'm using code very similar to #71.

Thanks!

josi123’s picture

The patch from #83 also works for me with Webform 6.x-2.9

Lanae’s picture

Works for me too! I'm using Webform 6.x-2.9 also and D6.15. Thanks Bartezz for this patch!

One minor issue, the descriptions I enter for the dynamic_select fields are ignored, and instead they all only use 'Hold CTRL and click for multiple selections'. Any tips for fixing this would be great...I would like to customize the help hint for each field, like the rest of the webform elements.

quicksketch’s picture

Note that I've reworked the entire component system over in #340241: Provide hook_webform_component_info() to allow 3rd-party components, but only for the 3.x version. The approach differs significantly from this patch, considering the 2.x version of the component system has several deficiencies that make it difficult to extend properly.

Bartezz’s picture

Hey quick,

Thanx for letting us know, haven't been paying attention! :)
Do I have to rewrite the dynamic_select for it to work with 3.x?
I currently do not have much time to do so, kinda hoping someone else will pick this up!

Cheers

quicksketch’s picture

Do I have to rewrite the dynamic_select for it to work with 3.x?

Yes it will need to be updated, but I wouldn't be in a hurry to do so. The APIs are still changing in the 3.x version are likely to change. There's about to be another large overhaul to address #181077: Printable page for webform submissions, which requires that components provide HTML output of their data.

joelstein’s picture

How about a totally different direction for this ticket... why not simply integrate Views? Views already does all the "dynamic selecting" you could hope for, and then it keeps custom PHP out of the UI. Something like CCK has for the node reference field type. You could specify your own select options in a textarea, or choose a Views view, which will dynamically populate the select for you.

Bartezz’s picture

Sounds like a good idea at first thought... yet I don't have time to implement such a thing...

Cheers

manogolf’s picture

Trying to follow what is going on here I'm really unsure of the end goal?

What I would like is a way to display on the site the number of users that have completed my webform. A counter display of submissions.

Will using this patch help?

marcvangend’s picture

@#94: No, that's not what this patch is for. This patch is meant to populate a select box with the results of a database query. For instance, you have a content type "brochure" and visitors can order brochures by filling out a webform. In that case, you need a select box which contains the titles of all brochure nodes.

manogolf’s picture

Wow. Sounds like a real handy feature. Thanks for the clear explanation.

lorenlang’s picture

subscribing

But personally, I'd really like to be able to use straight PHP as well. I've got some selects that change on a regular basis and I could easily program them to stay up to date that way. Things like a dropdown list of the past 20 years or the next 5 semesters based on the current date end up getting out of date until someone happens to look and remind us.

John Pitcairn’s picture

Ahhhh, crap!

Finally updated webform and it seems we can no longer access the session variable array for anonymous users. I was relying on that (#48).

Looks like I'll need to try this module/patch. Rats, more work.

John Pitcairn’s picture

Works nicely, and not much work at all, many thanks. Would be good if this patch could get committed.

John Pitcairn’s picture

Urk ... not so fast. The dynamic select element's default (selected) option cannot be set by %get[].

I'm thinking this might be a bug, other form element default values are successfully selected by %get[].

Can anyone else reproduce this?

John Pitcairn’s picture

#76: If the desire is to avoid parsing arbitrary php, how about allowing select elements to be populated by a named drupal variable? Then the module just needs to check that the variable contains an associative array.

Similarly, it would be really useful to allow default value fields to accept variable input (now that $_SESSION is not allowed for anonymous users) - I have a situation where I need to set a different default depending on certain conditions, but I don't want that in the URL.

bocky’s picture

I am using code:

 $result = db_query('SELECT node.nid AS nid,
   node_data_field_mdatum.field_mdatum_value AS node_data_field_mdatum_field_mdatum_value,
   node_data_field_mdatum.delta AS node_data_field_mdatum_delta,
   node.type AS node_type,
   node.vid AS node_vid
 FROM node node 
 LEFT JOIN content_field_mdatum node_data_field_mdatum ON node.vid = node_data_field_mdatum.vid
 WHERE node.nid = 13');
$arr = array();
while ($record = db_fetch_array($result)) {
  $arr[check_plain($record['node_data_field_mdatum_field_mdatum_value'])] = check_plain($record['node_data_field_mdatum_field_mdatum_value']);
}
return $arr;

to get data from field_mdatum (multi-value date field). Everything is working fine, it shows data in format: 2010-02-02T00:00:00.

What i would like to do is to show date in short format (or custom).

I tried with check_plain(format_date($record['node_data_field_mdatum_field_mdatum_value', 'medium'])); But this returns 1.January 1970 for all entries.

Thanks for help:)

kostajh’s picture

Patch and module in #83 work fine for me. Would be good if it was committed to the 2.x branch.

quicksketch’s picture

We have an alternative mechanism in the 3.x branch, making this unnecessary there. Since it's an API change and support for 2.x is ending quickly, I'm not inclined to commit this. We'll probably only have one more 2.x release ever before support comes to an end, I'd prefer we don't build a dependency on *exactly* the 2.10 version of Webform, since there will be no more releases after it in the 2.x branch.

kostajh’s picture

Hi quicksketch, what is the alternative mechanism in the 3.x branch and how does one utilize it? Is there any documentation?

quicksketch’s picture

kostajh: the functionality was added in #340241: Provide hook_webform_component_info() to allow 3rd-party components. All of Webform's new hooks are documented in the webform_hooks.php file included with the 3.x version of the module.

kostajh’s picture

I'm a bit confused by how to work with this API.

In the 2.x branch, a patch and light-weight module were offered #151603: Can I put options in a select field from a database query? to allow dynamic population of a select menu via PHP. So for example, I could call a function that loaded a view, gathered the objects, and populated the select menu with those items. This was easy to implement in a few dozen lines of code. However the patch was not committed in favor of Webform API in the 3.x branch, which would allow other modules to declare their own components. That's fine, and I understand the reasons for doing this.

However, now I am looking at the Webform 3.x API (http://drupalcode.org/viewvc/drupal/contributions/modules/webform/webfor...) and trying to understand how to implement the same functionality that was possible with 2.9 and the dynamic select patch, with little success. I imagine there are must be others in the same boat. All I need is a select menu that is dynamically populated via PHP (in my case, with a call to a function in a custom module that returns an array). Unless I am missing something obvious, it seems like trying to do this with the Webform 3.0 API would require several hundred lines of code.

Could any of the developers who are familiar with the Webform 3.x API provide some guidance? Thanks.

quicksketch’s picture

Status: Reviewed & tested by the community » Patch (to be ported)

In the 2.x branch, a patch and light-weight module were offered

Hmm, are you talking about the module in #83? That module is only 10 lines, but the component is about 400 lines. The 3.x approach works the exact same way only instead of "hook_load_webform_components", there is "hook_webform_component_info", which provides information such as a translated name and description, as well as some capabilities of the component.

Note that I'm still open to #406486: Allow pluggable select list values (which has been left open separately intentionally), which simply suggests a hook be added to select.inc to provide a list of key/value pairs. This issue has long focused on making a new component, versus #406486 is about adding a hook to the existing select.inc.

I'm moving this to "to be ported", even though the module provided in this issue will never be part of the Webform project itself.

kostajh’s picture

Thanks quicksketch. I'll see about porting dynamic_select to 3.x, although I think you are right that the approach in #406486 makes more sense.

luthien’s picture

hello, while waiting for the dynamic select to the part of the 3.x API, does anyone has a working version for the #83 patch or an alternative way of achieving the desired results for 3.x? I need to populate my webform fields from an external database but I could not find a way of doing it with 3.x.

I also have an extra question for quicksketch, it is not related with dynamic select: How to display the value from a particular field as part of the email subject? example: I have two fields, last name and first name; if I want to send the email with those two field concatenated in the subject, how do I do it?

thanks.

quicksketch’s picture

luthien, please do not post unrelated questions in the same issue. I don't think there is an existing issue for your question, so please post a new one.

kostajh’s picture

Hi Luthien, I'm working on finishing up the port of Dynamic Select module to the 3.x API, and aim to be finished up by the end of the week. It's functional, just need to clean up some of the code before sharing.

jackylam’s picture

Subscribing

felipe’s picture

Subscribing

kostajh’s picture

I applied for a CVS account today with the completed Dynamic Select code. I'll let you all know if/when that gets approved and when I create the namespace on drupal.org for the project.

quicksketch’s picture

If considering make a new project, I'd recommend making a module for ALL custom Webform PHP code. Since I'm dying to kill off the "Additional Processing" and "Additional Validation" fields (and I will remove them in one way or another in 3.x). If #406486: Allow pluggable select list values were put in place, then you could simply extend the existing select.inc instead of making a new component, which would be much better from a maintenance point of view. Then we could put all the custom PHP functionality of Webform in one place, and I wouldn't have to deal with the support requests from people breaking their sites. ;-)

luthien’s picture

Hi kostajh, I will be the first one to use it. All my webforms requires custom PHP code. Thanks!

kostajh’s picture

Hi quicksketch, that's a good idea. However, for the moment I'd like to get the Webform Dynamic Select project out since many people can set it up and use it right away. I will take a closer look at #406486: Allow pluggable select list values and think about your idea for a Webform PHP module when I have some time later in the month.

luthien’s picture

Hello kostajh, where can I get a copy of your updated code to test it? thanks

jackylam’s picture

Hi, I will be interested to test as well.

kostajh’s picture

It seems like the CVS approval process might take a while, so until the project is approved those who would like to test the Dynamic Select module for Webform 3.x may do so by downloading the tarball here: #746366: kostajh [kostajh]

luthien’s picture

The Dynamic Select module is working great, I'm using it in a production site to display content extracted from an external database.

quicksketch’s picture

The subscribers in this issue would likely be interested in these two issues:

#406486: Allow pluggable select list values
#754580: Remove Custom PHP Execution (Additional Processing/Validation) Fields

This makes the dynamic select module largely unnecessary, because there is now a hook in the normal select for populating lists. kostajh, rather than starting a new module, it would be really great if you could extend the split-off module http://drupal.org/project/webform_php instead, making it a one-stop-shop for people that want to type PHP code into textareas.

ybthefurste’s picture

Core 6.16, Webform 2.9

- works just fine -

luthien’s picture

do you have a rough guide on how to create the hooks? i.e. what files needs to be modified, etc.

Working like a charm with version 6.x-3.0-beta5!

I added my hook here: sites/all/modules/webform/includes/webform.options.inc

The only problem I see is with future module updates overwriting the file above and loosing custom code.

quicksketch’s picture

luthien, the documentation for hook_webform_select_options_info() is in webform_hooks.php (included with Webform), you just need to put your hook into a new module and then you can create your own webform select options there.

luthien’s picture

thanks quicksketch for the prompt reply. I still need to use the dynamic select module as I have to dynamically populate a second select by passing the value of the first one as a reference for my query.

Is there any other way of populating your select component dynamically? creating a custom hook is not going to work if I don't know how to pass the value from initial selection to the second select. Kind of the country > city example, select country then populate city based on selected country but, in my particular case, I don't know what results will be displayed for first select (dynamically generated, not static values) thus not being able to create options based on first value.

adeb’s picture

Subscribing

benmmc’s picture

Here is a simple post on implementing hook_webform_select_options_info(), which is the hook provided in Webform 3.0-beta 5.

http://fleetthought.com/programmatically-adding-pre-built-option-lists-drupal-webforms

luthien’s picture

Hi engineindustries, implementing the hook was easy to do following the instructions from quicksketch above. The functionality I need, and it is not easy to implement, is an option to populate a list dynamically based on the first dynamic list selection. Even more extreme, my lists are populated with options from an external database, so I need a way of passing the initial selection key to populate the second select after using the key to query my external db. I was able to the desired functionality using the dynamic select module, but that module was not saving the results for the submission thus it was not perfect.

mnapthine’s picture

MattBrigade’s picture

Dude, thanks!

quicksketch’s picture

Status: Patch (to be ported) » Closed (fixed)

Not sure why this post is open still.

Ludo.R’s picture

Just to be sure :

Are dynamic select options (e.g. list of nodes) now possible through hook_webform_select_options_info()?
With Webform 6.x-3.x of course!

Thank you!

luthien’s picture

yes, dynamic select options are now possible. The only problems I'm experiencing with dynamic selects in webform module are the reports. I have a dynamic select (populated with a query to an external DB) that was implemented using hook_webform_select_options_info(). The web form works fine, values are submitted correctly. The problem is when one of the values of the dynamic select is not an option anymore because it has expired, then the report fails. To generate reports from those web forms with dynamic fields, I'm using the webform_report module that works very good. The module is actively maintained and the developer adds new functionality to the module almost every day, we just need to wish for it.

Ludo.R’s picture

Good to know that.

Thank you for your feedback, i will check that next time i'd need it.

jorisx’s picture

just a node ref option from cck to webform would be very nice,
thanx guys... gone try the module option for now :)

loominade’s picture

hook_webform_select_options_info()


function [modulename]_webform_select_options_info() {
  $items = array();

  $items['node'] = array(
    'title' => t('Nodes'),
    'options callback' => ' get_nodes_array',
  );
  return $items;
}

function get_nodes_array() {
   $array = array();
   $sql = db_query("SELECT node.title, node.nid
                    FROM node
                    ORDER BY node.title ASC");
    while($row = db_fetch_object($sql)) {
      $array[$row->nid] = $row->title;
    }
    return $array;
}

I love you guys

theoracleprodigy’s picture

While the above does work with some modification... I have another question. How do you break up the data from the display. What if what you want to post is numeric but the title is what you want to display:

example:

select amount, display from x

I thought you would just return the list as:

$array[$row['amount']] = $row['amount'].'|'.$row['display'];

However this did not work.

vasanthkay’s picture

The dynamic select module created by kostajh (http://drupal.org/node/746366) is very useful... I used it in one of the form I created.
As luthien had pointed out in that thread, there is an issue wrt report generated from the webform. The dynamic select field is empty in it.
Also, I noticed one more issue wherein, doing validations for the dynamic select field with "webform validation" module is not possible. It does not detect the dynamic select option as one of the fields in the form.

Has anyone experienced the same problems ? Any ideas or alternate solutions to overcome these two problems would be highly helpful to me and the community as well.

kostajh’s picture

@vasanthkay: check out hook_webform_select_options() in the webform_hooks.php file in Webform 3.x.

luthien’s picture

@vasanthkay, I used the new hook from webforms to populate the dynamic select boxes and the webform_report module to generate the reports.

Squiggles’s picture

Issue summary: View changes

Is there a version of this for Webform 4? Would be nice if this was available. :)