Login

Tag "java"

Snippet List

Javascript Chain Select Widget

This widget will render a chained select menu powered by JavaScript to make it easier to identify foreign keys. This widget includes danjak's form decorator (http://www.djangosnippets.org/snippets/59/), and Xin Yang's chained select javascript functions (http://www.yxscripts.com/). I developed this to be used with an IT inventory system. See screenshot here: http://bayimg.com/cAjAGAabN The models are laid out that location -> area -> room. But the __str__ of area and room did not include unique fields, so the built-in single select box that django uses for ForeignKey's did not work for me. A few notes: 1: I will not be maintaining this, I am only putting it out here in case it helps others. 2: The chained select menus will only be available to the first form on the page. Reason being: the template names the form, not the django backend. So, I had to reference the form in javascript as document.forms[0]. 3: Due to the javascript processing, the chain select menu will not show current values other than the default specified in the javascript. Thus, form_for_instance and a dict of values passed to form_for_model will not pre-set the chained select. 4: The rendered selects are put into a vertical table. No other layout is supported. 5: The select field names for upper-leveled options are "chain_to_[destination_field_name]__[current_selects_model_name]. 6: The select name for the destination option is the name that django sends internally, which is usually the field name. The value of each option in the select is the primary key associated with that object. 7: I tried to get this built in to the native form_for_model helper function for use with the default admin site, but failed miserably. How to get it working (quick version): 1: Define your models 2: From your view, import the form_decorator and ChainSelectWidget (I put them in CustomWidgets.py and made sure it was in the path). 3: Build arguments for the form_decorator eg: widget_overwrite=dict(field=ChainSelectWidget(order=[(top, 'order_field'), (next, 'order_field'), (field, 'order_field)] 4: Send arguments to form_decorator eg: callback = form_decorator(widgets=widget_overwrite) 5: Build modified form eg: mod_formclass = form_for_model(field, formfield_callback=callback) 6: Instance the modified form eg: instanced_form = mod_formclass() 7: Send instanced form to the templating engine 8: From the template, import the chainedselects function file (replace [] with <>) eg: [head][script language="javascript" src="path/to/chainedselects.js"][/script] 9: Display the form object as you normally would.

  • javascript
  • dynamic
  • widgets
  • select
  • widget
  • js
  • java
  • chain
Read More
Author: ogo
  • 1
  • 7

1 snippet posted so far.