This is a followup to #406486: Allow pluggable select list values, in which we added the ability to provide select list options from PHP. Currently our lists are typical things: days of the week, countries, states, etc. Webform could be significantly empowered by making using views as a mechanism for creating select list values.

Comments

quicksketch’s picture

I don't have any solid plans yet for this feature even though it's a very obvious thing to add. My primary concern is bloating the list of possible predefined select list values with all of the views on the whole site.

My first idea was to use a Views tag (such as "webform") to identify views that should be used as Webform select lists, however this is a rather unusual approach and I'm backing away from it.

Instead, I think we should do exactly the same thing that is done for blocks. That is, make a display style for "Webform options" that works in a very similar way to the "Block" display style. We can configure Webform-specific options within the view like what name you'd like displayed for this list of values. It would also allow use to add our own validation to ensure that there are only two columns of data being displayed (one for key and one for value).

quicksketch’s picture

Oh, another topic of concern: passing arguments into the view. My inclination is to NOT include this functionality. Why? Because most users that create webforms have no idea how a Views argument works or even what it is used for. The other reason being that the most likely arguments: the webform NID or the current users UID, can be calculated by the View directly just by pulling the value from the URL (since Webforms are nodes and put all options underneath node/x) or from the global user object.

John Pitcairn’s picture

Subscribe. This would be great - I'm currently sticking at an earlier webform version to avoid the loss of anonymous select-population from session variables (I've no wish to add another module or switch to other equally hacky workarounds). As far as views args go, I suspect I'd find that very useful, but happy to make the attempt without to begin with.

sapox’s picture

Hi,
So eventually this feature will allow to dynamically populate a select-option list with content directly from the database everytime the form is seen by a user?

I'm new here and I just want get this clear. I have read a couple of other post (#406486: Allow pluggable select list values , #151603: Can I put options in a select field from a database query? ) but those are for static predefined lists. And I need something updated, directly from the database content. (Using Webform-3.x)

If this is not the right thread, any advice is welcome.

Thx.

quicksketch’s picture

Yes, you will be able to populate a select list with values from the database as long as you are able to make a view that contains what you want to be in the select list. So this could be a list of nodes, terms, users, files, or whatever. If it's a table that Views knows nothing about, you could in theory use Table Wizard to expose it to Views.

luthien’s picture

Hi sapox, I'm using webform-3 and I'm dynamically populating the select-option list with content coming from an external MySQL database (not Drupal), and it is not a static predefined list. I guess the answer to your question is yes, you can populate the list dynamically. I'm not using views to do it but my own sql query to generate the array that populates the select dynamically.

sapox’s picture

Hi luthien,
Could you explain in more details how to do this? I'm can do my own sql querys to get the data that I need from the database, but my proble is that I don't know what to do next to populate the select list. An example will be really helpful ;-)

luthien’s picture

includes/webform.options.inc file has examples for static lists. You will need to create a similar code for your dynamic select.

Static Example: List the Days of the week.

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

  $items['days'] = array(
    'title' => t('Days of the week'),
    'options callback' => 'webform_options_days',
    'file' => 'includes/webform.options.inc',
  );
...

/**
* Option list containing the days of the week.
*/
function webform_options_days() {
  $days = array(
    'sunday' => t('Sunday'),
    'monday' => t('Monday'),
    'tuesday' => t('Tuesday'),
    'wednesday' => t('Wednesday'),
    'thursday' => t('Thursday'),
    'friday' => t('Friday'),
    'saturday' => t('Saturday'),
  );

Dynamic Example: populate the list after querying an external database (be sure your external DB was set up in your settings.php configuration file - $db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';).

I created a survey, using webform 3, to be completed by participants to a particular activity (stored in the external database). The goal was to populate the select with the list of activities.

1) Define your variables:

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

$items['act_names'] = array(
    'title' => t('Survey - Activities List'),
    'options callback' => 'webform_options_activities',
    'file' => 'includes/webform.options.inc',
  );
  return $items;
}

2) Create your function to populate the select box dynamically.

function webform_options_activities() {
db_set_active('mydb');
$q = 'SELECT * FROM {your-table} WHERE ...';
$result = db_query($q);
$act_names =array();
$act_names[''] = "Please select one";
$q = 'SELECT count(*) FROM {your-table} WHERE  ...';
$itemnum = db_result(db_query($q));
db_set_active('default');
if($itemnum > 0) {
while (fetch your $result here)) {
for($x = 0; $x < $itemnum; $x++) {
$act_names[key] = "value";
}
}
}
  return $act_names;
}

Hope this help to understand how it works. The example was created using an external DB, not the Drupal DB. I fixed the text to avoid misunderstandings, as per the comment below.

quicksketch’s picture

1) inside _webform_options_info() add the definition of your function and variables:

NO, no, no! Make your own module and implement your own hook_webform_options_info()!! Read the webform_hooks.php for documentation. Do not hack Webform.

sapox’s picture

Version:7.x-3.x-dev» 6.x-3.x-dev

Hi,
Using the example provided by luthien I created my own version. I'll put it here, so maybe it can help someone else, but I have to say that I'm not an expert PHP coder so maybe is not the most optimized code but it simply works. As quicksketch pointed out, I created my own module to not hack Webform.

The important thing is to create 2 functions in your myownmodule.module, which should look like this: (assuming that I have a table called "materials" and a field called "names")

<?php
function myownmodule_webform_select_options_info() {
 
$items['materials'] = array(
     
'title' => t('Materials list from db'),
     
'options callback' => 'myownmodule_webform_materials_options',
  );
  return
$items;
}

function
myownmodule_webform_materials_options() {
   
//$query = "SELECT `materials`.`name` FROM materials ORDER BY `materials`.`name` ASC";
   
$query = "SELECT name FROM {materials} m ORDER BY m.name ASC"// updated query syntax to  improve compatibility
   
$result=db_query($query);
    while(
$a_list = db_fetch_object($result)){
        foreach (
$a_list as $key => $val){
           
$materials[$val] = $val;
        }
    }
    return
$materials;
}
?>

That should do the trick. I'm sure that a better programmer can generate a more optimized code, so advices are welcome.

The only thing that I couldn't make was to overwrite the first element in the select list that say "select..."

quicksketch’s picture

Thanks sapox, using a separate module is definitely a better way to go, so you don't have to keep track of new changes as they come out, especially since Webform 3 is still open to changes. The one suggestion I have is to use the Drupal-ish syntax for queries:

$query = "SELECT FROM {materials} m ORDER BY m.name ASC";

This syntax makes it compatible with multiple database systems and table prefixing.

sapox’s picture

Updated.
But, any idea how to overwrite the first "select..." element in the list?

quicksketch’s picture

But, any idea how to overwrite the first "select..." element in the list?

It's inserted automatically for you, but if you set a default value and make the field required, it is not necessary and won't be added.

frozensage’s picture

Thanks Sapox for that which essentially means I could generate the SQL query in Views, which in my case is outputting the terms from a specific vocabulary, and then get that to show up in a select list. Abit tedious but I think it will work for the time being.

kostajh’s picture

Since a lot of people are asking, here is a post that explains how to populate your pre-built options list with a View: http://www.designhammer.com/news/providing-dynamic-select-options-to-web...

However this approach is not very flexible and doesn't fit the needs of Drupal site builders (i.e. non-developers). I think the approach advocated by quicksketch in comment #1 is the right way to do this:

...we should do exactly the same thing that is done for blocks. That is, make a display style for "Webform options" that works in a very similar way to the "Block" display style. We can configure Webform-specific options within the view like what name you'd like displayed for this list of values. It would also allow use to add our own validation to ensure that there are only two columns of data being displayed (one for key and one for value).

So I think we should keep this thread to discussing/testing that kind of implementation (unless of course folks think another way is better).

devkinetic’s picture

I have a big need for passing args to my view && OR custom function in my webform.

My registration webform displays options based on the node it's being submitted from's taxonomy. I need the ability to pass the NID to my function or view either via POST to hidden field or some other way.

I would suggest leaving this option open to developers in code.

devkinetic’s picture

I was able to achieve my functionality manually. I ran into an issue when submitting my forms due to the fact that the code was executed again after it had redirected away from the node being viewed (using panels node template with webform displayed at bottom). This caused my code to break (since the function could no longer load the node from the url), and I resorted to temporarily storing the $items array in $_SESSION.

This is a proof of concept of how webform can be extended with dynamic parameters. I definitely think that once the code is executed (on page, not in admin) the determined $items should be stored in the object and not re-processed. Also, access to the hidden fields in the webform could be a key feature as well.

I hope this helps, or serves as a launching point for others trying to accomplish this:

<?php
function tnc_site_webform_select_options_info() {
 
$items = array();
  if (
function_exists('_registration_get_view_options')) {
   
$items['taxonomy'] = array(
     
'title' => t('Class Days'),
     
'options callback' => '_registration_determine_view_options',
    );
  }
  return
$items;
}

function
_registration_determine_view_options() {
 
$items = array();
 
  if (!isset(
$_SESSION['registration'])) {
     
$_SESSION['registration'] = array();
     
$items = _registration_get_view_options();
     
$_SESSION['registration']['items'] = $items;
  }
  else {
   
$node = node_load(arg(1));
    if (
$_SESSION['registration']['nid'] == $node->nid) {
      foreach (
$_SESSION['registration']['items'] as $key => $value) {
       
$items[$key] = $value;
      }
    }
    else {
      unset(
$_SESSION['registration']);
     
$_SESSION['registration'] = array();
     
$items = _registration_get_view_options();
     
$_SESSION['registration']['items'] = $items;
    }
  }
 
// dsm($items);
 
return $items;
}

function
_registration_get_view_options() {
 
$node = node_load(arg(1));
 
$_SESSION['registration']['nid'] = $node->nid;
  if (
$node) {
    foreach (
$node->taxonomy as $item) {
      if (
$item->vid == 2) {
       
$items[$item->tid] = $item->name;
      }
    }
  } else {
   
$items['test1'] = 'test1';
   
$items['test2'] = 'test2';
   
$items['test3'] = 'test3';
  }
    return
$items;
}
?>
tomsm’s picture

subscribing

Summit’s picture

Definitely subscribing, would be absolutely great if views could be used as pre-built list for webform!
greetings, Martijn

froboy’s picture

Subscribing... this looks like some great functionality.

gionnibgud’s picture

StatusFileSize
new8.92 KB

Hi all I've noticed that in this issue http://drupal.org/node/406486 user jakali has made a module that uses taxonomies to populate pre-built list. The module is there to download if needed.
I did not know about his work and I've been doing more ore less the same job with a slightly different approach.
I'm posting my version of the module here since the other issue is now closed and links here.
With this module I've also added a checkbox in the vocabulary interface that lets you select the vocabulary to be used in webform's pre-built lists.

Please note that this module to work needs webform 3.x (al least I didn't test it on version 2.x) and a patch that can be found here: http://drupal.org/node/907762. This patch has already been committed so hopefully it won't be necessary once a new version of webform 3.x will be released.

While using taxonomy to maintain list may not be the optimal solution (not as good as using views or nodequeues) it's a very simple and effective one if you don't/can't use php to populate the list.

Any feedback it's obviously very much appreciated.

foraker’s picture

Subscribing

_vid’s picture

Subscribing...

jastraat’s picture

StatusFileSize
new1.42 KB

I created a small module to allow views to be loaded as pre-built option lists using hook_webform_select_options_info() . I'm attaching a copy. It's pretty bare-bones, but perhaps you could use it as a starting place for including the functionality in the webform module as a default pre-built list option...? I think a lot of folks would find it useful.

Summit’s picture

This sounds great, would love to have this integrated!
greetings, Martijn

aaronbauman’s picture

scottrigby’s picture

@quicksketch: I'm following up here from #406486-12: Allow pluggable select list values, I mainly wanted to second kostajh's request to allow passing an argument in hook_webform_select_options_info(). But now looking at this issue & #24 #767290-24: Allow Views to be used as pluggable select list values - is it the case that 'options arguments' could pass a views argument to a selected view? If so, I'm thinking we'd need another field (could accept basic tokens, or just a static value). I'd help contribute some effort to this (adding a field to pass the arg value), but I'm unclear about where the functionality stands. Also - in general - do you think passing arguments this way could be generally useful for dynamic lists based on a selected view?

scottrigby’s picture

re #27: never mind - somehow I didn't see 'options arguments' was already committed in #907762: Support callback arguments for hook_webform_select_options_info. Awesome.

@quicksketch: I also see you already answered my specific question about a field to pass views args - in #2 (I should try to post issues when I'm awake).

@jastraat: it might be good to allow selecting displays in webformlist_settings() (since each display could have different display_options. Something like:

    foreach ($all_views as $view) {
+      foreach (array_keys($view->display) as $display_id) {
bandelier’s picture

Subscribing

DoubleT’s picture

Subscribing

jeremyll’s picture

Subscribing

handsofaten’s picture

Subscribe

lazly’s picture

Hi!

Maybe its better, I created a view, after use this, its more comfortable. Read back pls, its only a variant for #8

<?php
function webform_options_viewlist() {
 
$view = views_get_view('webform_list');
 
$view->execute();
 
//kpr($view);
 
$rows = array();
  foreach (
$view->result as $row) {
   
$rows[$row->nid] = $row->node_title;
  }
 
//kpr($rows);
 
return $rows;
}
?>

Please create the view with 'webform_list' name, create filters, sorts and columns, or everything, its your choice. For special array generate the commented rows (kpr) is very usefull for you, please use for devel. (You will need devel module for kpr).
Read comment #9, its true! (but i'm lazy :))

mass43’s picture

Subscribe

mstrelan’s picture

subscribe

nathanhaigh’s picture

I'd like to use a view to pull out a list of events from CiviCRM and have these populate a select list for use in a webform designed for an eveluation questionnaire. I hope this feature is addedd quickly! :)

devkinetic’s picture

Example of doing it the right way, I pulled this from a working site.

1) Create a custom module and place the following code within it.
2) Re-namespace the functions obviously

In this example I am creating 3 lists, using the same view, and passing a taxonomy term for my argument each time

<?php
function expo_alerts_webform_select_options_info() {
 
$items = array();

 
$items['education_seminars'] = array(
   
'title' => t('SESSIONS: Education Seminars'),
   
'options callback' => '_expo_alerts_webform_options',
   
'options arguments' => 'education seminars',
  );
 
 
$items['forums'] = array(
   
'title' => t('SESSIONS: Forums'),
   
'options callback' => '_expo_alerts_webform_options',
   
'options arguments' => 'forums',
  );
 
 
$items['networking'] = array(
   
'title' => t('SESSIONS: Networking'),
   
'options callback' => '_expo_alerts_webform_options',
   
'options arguments' => 'networking',
  );

  return
$items;
}

function
_expo_alerts_webform_options($component, $flat, $filter, $arguments) {
 
$view_name = 'session_titles'; // name of view
 
$display_id = 'default'; // display
 
  //don't touch this
 
$view = views_get_view($view_name);
 
$view->set_display($display_id);
  if (
$arguments) {
   
$view->set_arguments(array($arguments));
  }
 
$view->pre_execute();
 
$view->execute();
 
$rows = array();
 
 
// my view uses NID and Node Title
 
foreach ($view->result as $row) {
   
$rows[$row->nid] = $row->node_title;
  }
 
  return
$rows;
}
?>
fietserwin’s picture

A bit aside: for those just looking to add their taxonomy lists to webform: see module Webform Term Options.

IMO, creating a view to get your taxonomy list looks a bit like overkill. So I think that the webform module should think about integrating the code of this module (34 lines) separately from this issue (which. don't get me wrong, certainly has lots of uses).

Wolfgang Reszel’s picture

Version:6.x-3.x-dev» 6.x-3.14

Any hints why I can't see custom predefined list options in the select box of the webform component? I added code to my custom module and also tried the webformlist module from jastraat.

sapox’s picture

@Tekl, if you are reading something directly from your database, try #10.

If not, code is even simpler:

<?php
function mymodule_webform_select_options_info() {
 
$items['yes_no'] = array(
     
'title' => t('Yes or No translation select'),
     
'options callback' => 'mymodule_webform_yes_no_options',
  );
return
$items;
}
function
mymodule_webform_yes_no_options() {
   
$yes_no = array(
       
'1' => t('Yes'),
       
'0' => t('No'),
    );
    return
$yes_no;
}
?>
sunshinee’s picture

I'm assuming this project is on the radar: http://drupal.org/project/webform_viewreference. Having used the original Webform View Reference Component and tested a patched version from Views field values are not displayed (Request for View Reference key|value pairs), I would LOVE to be able to select a view as the source of a select option list.

Perhaps the code used in the module/patch would help the effort to get this functionality in Webform.

steveoliver’s picture

Has nobody considered this use case: dynamic webform options for the user, not just the administrator?

What if the options for the webform user stayed in sync with the changing results of a view (or any other dynamic back, for that matter) without the need of manually updating the options through Webform reconfiguration.

I see the options list is stored in the database with other settings for each component. Instead of storing items as pairs of static options in webform_components.extra, we could store an items_callback and evaluate it each time, i.e:

<?php
function mymodule_webform_options_dynamic_callback() {
 
$options = '';
 
$source_of_options = $your_dynamic_backend;
  foreach (
$source_of_options as $k => $v) {
   
$options .= _webform_safe_key($k) . '|' . _webform_safe_value($v) . '\n';
  }
  return
$options;
?>

Not unlike a FAPI #options callback.

Is this what you were thinking, sapox?

Would an approach like this go against something fundamental to Webform, quicksketch?

quicksketch’s picture

What if the options for the webform user stayed in sync with the changing results of a view (or any other dynamic back, for that matter) without the need of manually updating the options through Webform reconfiguration.

That's the way the callback function already works within Webform. You wouldn't have to go and reconfigure the component every time the list changed, it would be updated immediately. Webform populates the select list options for you when you're editing a component with a pre-built list, but it doesn't actually save that exact list, it's just there for reference. Webform will use the callback function at the time the form is rendered.

steveoliver’s picture

Version:6.x-3.14» 7.x-3.x-dev
StatusFileSize
new2.09 KB

Oh, cool. I see now.

Maybe a little clarification in some of the language?

sapox’s picture

Version:6.x-3.x-dev» 7.x-3.x-dev

The code given above solves my problem, it populates the select list with data from the database every time the user renders the webform. If any change is made in the database, those changes are automatically updates in the webform.

mrconnerton’s picture

Okie dokie, I thought I would follow @quicksketch's advice/idea and take a stab at my first views 3 display plugin to produce.

Webform Views Select
http://drupal.org/sandbox/mrconnerton/1373760

This module will let you populate a webform select component with data from a view. To use this module:

  1. Create a new view
  2. Create a "Webform Options" display
  3. Add nid and title fields and filter as you please
  4. Add the select component to your webform and pick your view under "Load a Pre-Built Option List"

Currently this only supports a nid => title relationship, but of course I'm welcome to ideas on how to make it better.

mrconnerton’s picture

quicksketch - We can configure Webform-specific options within the view like what name you'd like displayed for this list of values. It would also allow use to add our own validation to ensure that there are only two columns of data being displayed (one for key and one for value).

Will undoubtedly be the next step. Although my wife will probably be upset that I stayed up till 5am writing this so that is for another day! :-P

steveoliver’s picture

It'd be slick to generate options for more than just select components, like a tableselect. We can produce views displays with at least the keys and values we need for all elements plus additional fields that can be mapped to properties of some Webform components.

Maybe a module like yours, mconnerton, more generically purposed, called webform_views_options or something, a new more generic webform hook, and of course support in webform_component_* for mapping, etc.?

-Steve

kanani’s picture

Pretty Slick, working well on my view with 300 results.

steveoliver’s picture

Re #48, I created a new issue #1376530: Allow Views to be used as pluggable selectable options, considering the possibility of providing options for Webform select and tableselect components from Views with flexible mapping of Views fields to Webform component properties.

pav’s picture

subscribing

steveoliver’s picture

I don't plan on building this tableselect component for Webform at the moment; I may in the future. However, I will likely help contribute to mrconnerton's Views displays module in the meantime.

Thanks again, Nate -- Webform rocks.

z_khn06’s picture

Is it possible to integrate this feature with drupal commerce

steveoliver’s picture

z: please clarify your question.

z_khn06’s picture

I would like to know if it possible to use such a feature to populate a select list in drupal commerce product options. I have a select list field which the users can select from the list of options but is it possible to populate this with data from a view so they can select a node.

OLD ACCOUNT USE ID 169175 INSTEAD’s picture

Thanks for putting this module together, it's a great start. Is there any way to include more from the view than just the title? I'd like to have images and other fields showing next to the select box. Here's an example of what I'd like to do: http://www.dickblick.com/requests/bigbook/

steveoliver’s picture

nottaken’s picture

@lrobeson we (with gorton studios) did some custom work on a webform that used a form alter that reworked the form options. I can give more details if needed. you can see it working at http://tolerance.org/material/orders after you enter your zip code. This was on D6. so this might be off topic a bit, but hopefully useful.

<?php
// Replace the product value with the html version.
       
$form['submitted']['productorder']['products']['#options'] = _splc_product_product_options();

/**
 * Product options for the form.
 */
function _splc_product_product_options() {
 
$products = array();

 
// Prepare field array - Reusing CCK nodreference function _nodereference_potential_references()
  // This clever bit of code was taken from webform_viewreference (which does almost what we need, but not quite).
 
$field['advanced_view'] = 'splc_product_orders_kits';
 
$field['advanced_view_args'] = '';
 
// Field name used for cid in _nodereference_potential_references
 
$field['field_name'] = md5($view.$args);

 
$data = _nodereference_potential_references($field);
 
$kitsview = views_get_view_result('splc_product_orders_kits');

   
//loop kits and create products array if sku value is not null. key should be sku id
   
foreach ($kitsview as $object) {
    if (!
is_null($object->node_data_field_fulfillment_sku_field_fulfillment_sku_value)) {
   
$products[$object->node_data_field_fulfillment_sku_field_fulfillment_sku_value] = $data[$object->nid]['rendered'];
    }
   
  }

  return
$products;
}
?>
OLD ACCOUNT USE ID 169175 INSTEAD’s picture

Thanks Steve! This is just what I needed. I got it mostly working, but (pardon my stupidity, still learning PHP) how do you add CSS classes to the fields? It seems impossible to style otherwise. When I try to add div tags around the fields, they get stripped out, but adding a link class works..?

steveoliver’s picture

You're welcome, Laura.

You know Drupal always gives you more than enough css selectors to target :)

The list of checkboxes should be contained in a parent element with an id such as webform-component-samples-requested and each option should be wrapped in something like <div class="form-item form-type-checkbox form-item-submitted-samples-requested-753"></div>.

I would target the input.form-checkbox and label.option children like...

#webform-component-samples-requested .form-type-checkbox {}

and

#webform-component-samples-requested .form-type-checkbox input.form-checkbox{}
#webform-component-samples-requested .form-type-checkbox label.option{}
OLD ACCOUNT USE ID 169175 INSTEAD’s picture

Lol, yeah I know Drupal isn't lacking in selectors, but for example, here's what I'm using:

$options[$item->nid] = $item->node_title . '<a href="' . render($item->field_field_catalog_issuu_link) . '" class="issuulink" target="_blank"> ' . render($item->field_field_catalog_image) . '</a>';

Which gives me a text field and a linked image, neither have any CSS selectors. That's fine for now, but what if I add another text field, how do I style one without affecting the other one? Hopefully that makes sense. Either way, your code was a huge help and I'm very grateful for it, so thank you again. :)

chaloum’s picture

I can see views being useful but we also need taxonomies, as can be done when creating a "content type" where the "field type" is a Term reference

chaloum’s picture

#1 quicksketch, I agree with your last paragraph

steveoliver’s picture

StatusFileSize
new3.26 KB

@lrobeson, I don't see any reason why that wouldn't work, however using l() would be a little cleaner and safer.

This code creates a custom class 'test-class' on my webform option labels for me:

$style = l($item->node_title, 'test-url', array('attributes' => array('class' => 'test-class')));
$options[$item->nid] =  $img . ' ' . $style;

OLD ACCOUNT USE ID 169175 INSTEAD’s picture

Thank you Steve, I went a different route and added a custom class via the Views field "style settings" and it shows up in the Views preview, but not on the Webform that's using the View. Is there something extra I need to add to my webform_select_options_info callback function to include those settings? That would ultimately be my preferred way of adding the extra CSS class(es). (If this question is too far outside the scope of this initial issue, I apologize.)

steveoliver’s picture

@lrobeson -- I've updated http://drupalsteve.com/node/57#hook_and_callback (lines 23, 34, and 26) to support row classes set in Views' Format > Settings.

It's pretty hacky, but it sets the class on an <a> wrapper, as this is an inline element that won't be stripped from the <label> element.

Lemme know if that makes sense?

flightrisk’s picture

I'm a little lost as to how this works. Does anyone have a step by step guide to creating a view and integrating it into webform for my select list?

I'm still curious as to why this is not an implementation of taxonomy instead. It seems way too complicated to use views just to get a list of taxonomy terms. I would prefer "term reference" to be one of the field types you can enter in the webform edit screen. I can use the existing "select list" type, but then have to cut and paste the same complicated key/value pair into each field if I have fields that all need to use the same term reference.

As an example, I have a webform that is a request for support. I need to track 10 to 20 "actions" to log what was done and on what date. So I have Action1 through Action20 as fields. I need the same select list for all 20 fields ("send email 1", "sent email 2", "phone call", "resolved"). What is the easiest way to accomplish this?

flightrisk’s picture

I completely agree! "Term Reference" should be one of the field options along with "date", "textarea", etc. It is the way just about every other module I've seen works. I'm still trying to see what benefit using views has over taxonomy.

steveoliver’s picture

A custom options callback for your situation could be crafted in about 10 lines.. See taxonomy.module -- http://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/7

flightrisk’s picture

Thanks Steve, but this seems to be one of the weaknesses of Drupal as it is supported. It seems geared towards professional PHP programmers and web designers. There are a lot of us who are technically proficient and just want a tool to make management of websites easier without having to hand code things. Drupal is sort of the "Frontpage" or "form builder" for the types like us. We don't know SQL (fluently anyway), we don't know PHP, we don't know the Drupal API, we barely know CSS, and we can't memorize all the individual APIs for all the supported modules like taxonomy and figure out how to insert a field from them in another module. So that 10 lines of code is an insurmountable mountain for us. I am a programmer in other languages (Delphi, Visual Basic, Visual C#), and I spent a month trying to learn all of the above only to throw in the towel and realize that unless I was doing this as my regular full-time job, the learning curve was too steep. I had an easier time learning different Windows APIs and programming device drivers!

If it is only 10 lines of code, wouldn't it make sense for this to be a feature in Webform? If it supports date fields and text fields and all those other fields, why doesn't it support a term reference field from the Taxonomy module? I found a module that I thought was perfect (webform term module), but it just reads the terms and puts the taxonomy selections in the pre built list. When you select it, it builds a key/field list and puts it in the correct box. But it is not dynamically linked. So in my case, when I need to add a taxonomy term I didn't think of after already creating my webform, I have to edit 20 fields and add the term to each one. With true taxonomy support, when you add a new term, it shows up immediately in any select list that references that taxonomy.

steveoliver’s picture

@flightrisk, This module, like Drupal, is designed to be extended. Hence the "hooks". Therefore, it doesn't make sense for your use case to be a feature of Webform. I recommend you open up a new feature request and/or reverse bounty if you want someone to build something for you. You're welcome to ping me after that.

flightrisk’s picture

Thanks Steve, though I have to respectfully disagree. And judging by the posts here, a lot of people are wanting the same thing just like they want views integration. I tried looking it up, what is a "reverse bounty"? I'll take your advice and open a feature request, though I imagine I will get flagged as "duplicate" since people keep asking for this same feature in multiple threads.

In the meantime, is there a guide to how to use views to do this? It really is an onerous solution, but better than nothing. I am fluent in views. I just don't get how it integrates with Webform.

mrconnerton’s picture

@flightrisk - I highly doubt there will ever be a node or term reference field for this module. At best there should eventually be an entity reference field. However that is going to take time to write. Like you said, the views solution for select component is better than nothing.

I have a very simple prototype in comment #46 which is currently hard coded to work with the node table only. I welcome your support to contribute code to that. I will give you commit access and you can help me test and commit the 6 or so patches people have already contributed.

If you wanted a hard coded solution, what you are looking for then is http://api.lullabot.com/hook_webform_select_options_info/7. You can look at my sandbox code to see how to get it working. That hook and a callback is your 10 lines of code to give you term references.

steveoliver’s picture

@flightrisk - http://drupal.org/project/webform_term_opts seems like what you want.

flightrisk’s picture

Steve, yes I tried this, but it is not dynamic. All this module does is take a taxonomy list and allow you to select that list from the pre-built lists and put them into the options field - once. If I then add a new item to the taxonomy list, it does not pick it up automatically. I have to go into each field in the webform and do it all over again.

*On further testing, the list IS updated if you actual try to make a webform submission. It just doesn't appear in the "option" list when you go to the webform and edit the fields with the taxonomy terms. Perhaps a bug? Or a "feature"? I don't really need the option list anyway if this does act dynamically. It is perfect for me.*

What am I missing that some of you seem to think that a views solution is fine or that entity is the way to handle this? Is there some benefit or feature I'm not understanding? I'd like to catch up with the conversation and see where development is headed.

flightrisk’s picture

mrconnerton, thank you for the offer, and I would be happy to help test, but as I mentioned, I have tried to learn PHP, the drupal API, and the webform API and realize it would take too long to get proficient. In my real job, I use SVN with TortioiseSVN and completely different IDEs, so I would have to install and learn yet another set of tools like GIT and Drush (which I don't have space for) and then learn how to use them to upload and download things to the drupal repository, etc, etc.

It is frustrating that a solution might only be "ten lines" of code, but it might as well be 10,000 because I don't know half the terms you are talking about. I have to basically sift through hundreds of lines of Drupal API functions in order just to learn which ones might be applicable, then do the same for the Webform API, etc. So if I was just needing to print something to the screen, I could probably learn enough PHP to do that with 1 or 2 lines of code, but to write a module that codes to 2 different APIs, I'm afraid is beyond me at this point.

Nicolas Bouteille’s picture

Great post indeed on #15 but the url has changed from news to blog : http://www.designhammer.com/blog/providing-dynamic-select-options-webfor...

lhfiso’s picture

Category:feature» support
StatusFileSize
new27.02 KB

I'm sure someone will make sense of this. I've got no idea but then again I wouldn't know half of what you guys on here know.

I want to create a select list from a view made up of redhen contacts fields; namely first_name and last_name. Using the module code provided by @jastraat (#24) I was able to get the view to appear as a select list in webform and show the values from the view using the following (slightly modified) code:

<?php
function _webformlist_get_view_options($component, $flat, $filter, $custom_args = array()) {
 
$options = array(); 
  if (isset(
$custom_args['view']) && !empty($custom_args['view'])) {
   
$name = $custom_args['view'];
   
$view = views_get_view($name, true);  
   
$view->execute(); 
   
$fields = $view->display['default']->display_options['fields'];

    foreach (
$view->result as $rowid => $result) { 
     
$display_fields = array();
      foreach (
$fields as $field => $data) {
        if (!
$data['exclude']) {
         
$rendered = $view->render_field($field, $rowid);
         
$display_fields[] = strip_tags($rendered);
        }
      }
      if (!empty(
$display_fields)) {
       
$options = $display_fields; /*Only modification that would get SOMETHING to show up*/
     
}
    
    } 
  }
  return
$options
}
?>

Only problem is that each field is a seperate row! See attached image.
I need it to display the two fields as one row e.g. 'first_name last_name' or 'Dwight Schrute'.

Using:

<?php
 
if (!empty($display_fields)) {
       
$options = implode(' ', $display_fields);
      }
?>

Gives: Fatal error: Unsupported operand types in /home/content/13/9755813/html/includes/form.inc on line 2619

If I try hiding fields and rewriting other fields using replacement tokens the hidden fields will just dissappear from the list and rewrite doesn't render.

I don't care how silly this might sound just HELP ME...please!!!

steinmb’s picture

Category:support» feature

Pls. don't highjack the issue.

pcdesign’s picture

Hi,

I read a few concerns about passing arguments to the view.
Lately I have been using a lot of extra functionalities on the rules module. On a certain point I got stuck because I needed a dynamic list of items (in the form of a loop...). The solution came from a module called views-rules (see at http://drupal.org/project/views_rules).

The reason I bring this up is because they have found a way to feed data into views' contextual filter and they found a way to output the data in a contruction of a view type like 'blocks' or 'panel panes' etc.
In this module it is up to the developper to configure the correct datatype, as well as for the filters as for the output fields (yes you can only use fields!!).

I hope this can give a fresh idea to the subject because I would be very very interested to see this come to life, this can come in handy.

pcdesign’s picture

Hello,

I'm already back with a small reference of a module: http://drupal.org/project/webform_viewreference

I think this is what we are looking for? (it just misses a port to D7... and maybe its a bit outdated...)

grtz
Peter

sunshinee’s picture

@Peter: That module has been around for a while. It does work to display a view as a select component, but it appears to be minimally or unmaintained and has several limitations that hinder its usefulness:

  • Only the default view can be used as a source
  • Only the node title can be displayed as the select value, regardless of Views output. For example, if I have a properly configured view that outputs rows like "myemail@domain.com|My Email" where I'm pulling the email address and title from CCK fields in MyNode, the webform component will simply display MyNode. It won't work as a conditional email value, and doesn't display the output as defined by the view.
  • If memory serves, arguments can only be entered as static values; they cannot be passed from another form component.

So, if you only need the node title from the default view, the module works. Otherwise, it lacks the true ability to use a view (as you define it) as a source. =)

rhlowe’s picture

Subscribing for future reference.

blackspiraldancer’s picture

I'm a bit let down that webform *still* misses this great feature. Being able to choose from an own defined dynamic list (eg. a webform for info request on a custom event list, etc.) is a core requisite, and for a non-coder/very-basic-coder is just sad to have to reinvent the wheel on every site.
When you get used to the comfortable Views interface, it's hard to step back and write your own code; I'll keep on using http://drupal.org/sandbox/mrconnerton/1373760

Nicolas Bouteille’s picture

I recently was forced to try out Entityform instead of Webform because of the lack of integration with Rules and I was very very pleased with Entityform. I think it's really great and better fitted for advanced scenarios like you face here.

It seems to me that you guys could use the fact that you can actually add the same kind of fields that you add to your nodes, including Term Reference fields, into an Entityform.
So if I am correct about what I read on the description of this issue it would be perfect for fields such as "days of the week, countries, states, etc."

Now if you really need this list to be dynamic and to be linked to a View then again the fact that Entityform is meant to integrate perfectly with Drupal 7 and all its modules will really help here when trying to alter the field, whereas Webform uses its own "Component" from what I remember.

Here I created an article explaining how to populate an Views exposed filter with dynamic values coming from a view. The workflow should almost be the same to alter a field I suppose.

http://bouteillenicolas.com/expertise-drupal/views-ajax-dynamic-dependen...

Hope this all helps.

DanChadwick’s picture

Issue summary:View changes
Status:Active» Closed (won't fix)

Closing due to implementation in related module.

robertwb’s picture

Status:Closed (won't fix)» Active

Looking at this thread that @DanChadwick recently closed, listed as "implementation in related module". I think it would be good to either have a relationship (in the issue summary) or at least a link to the module that the maintainers consider to be the most relevant implementation. There are two that I can see, one minimally maintained in a sandbox, and another that only shows release for D6 -- which makes it seem a bit of an over-statement to call either of those implementations. So, maybe I am missing another link, if so, pardon the intrusion.

DanChadwick’s picture

Status:Active» Fixed

@robertwb -- I am referring to the sandbox referenced above. I would suggest that someone push the sandbox forward into a real release, or fund the module's maintainer to do so.

mrconnerton’s picture

@robertwd I would like the sandbox project to pass coder / PAReview.sh before I promote to a full project. See #1669186: Request for full D7 project and leave some feedback if the project is working for you. With that said I am not actively working on the review of the module to push live and I think the other guy who was helping out has moved on as well. If you would like to help out let us know.

robertwb’s picture

@danchadwick - thanks for clarification. This note then signifies that the solution to this request is in the sandbox project of @mrconnerton - http://drupal.org/sandbox/mrconnerton/1373760 (can not add a "related" ref to sandbox projects)
@mrconnerton - thanks for the link, I can certainly put this in my queue for trying to help tidy as I play with it. I will then go to the review queue and post up corrections and support.

mrconnerton’s picture

Issue tags:+SprintWeekend2015

No worries. During the this past weekends SprintWeekend @mrjmd has stepped up to become the maintainer. He is working on getting the project to pass coder and parreview script and I will promote after that. He is already a full maintainer.

robertwb’s picture

@mrconnerton - sweet!

Status:Fixed» Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

jrwilson’s picture

Perhaps a simplified way for site builders is to use: values