Sunday, August 5, 2012

Re: Dynamic form field type.

Hi,

On 6-8-2012 0:09, Nicolas Emiliani wrote:

> I have three Models,
>
> Home, HomeAttributeType and HomeAttributeValue. HomeAttributeValue has
> an FK to HomeAttributeType and one to Home.
>
> The idea is that the user can add as many HomeAttributeTypes as he wants and
> set the data type of the former. ie :
>
> ha1 = HomeAttributeType
> ha1.name = 'FooAttr2'
> ha1.type = 'boolean'
>
> ha2 = HomeAttributeType
> ha2.name = 'FooAttr2'
> ha2.type = 'numeric'
>
> So, now the user when creating a Home through a ModelAdmin, has the Admin
> for the HomeAttributeValue inlined, and so he can set, for example, for
> that home
> a FooAttr1 selecting in from the Drop Down menu.

Ok, so for example:
ha1.name = 'Garden'
ha1.type = 'boolean'

ha2.name = 'Rooms'
ha2.type = 'numeric'

Does this sound correct?

> And here comes the black magic, If he selects FooAttr1 the value field for
> the HomeAttributeValue
> should render itself as radio button (yes/no) and if it where FooAttr2 it
> should render itself as
> an InputText. I can easily do this with JS, but what I can't do is to
> somehow add a bunch
> of hidden inputs that can relate each HomeAttributeType to what they should
> render to.

And you don't need to. You would solve this with dynamically generated
JavaScript. Create a mapping from HomeAttributeType to the right widget
and connect an onchange event on the select widget.
Something like:
<select onchange="render_widget(self.selected.value)">
...
</select>
The javascript function render_widget gets the homeattributetype id
passed to it.
And the template for the javascript would be like:
function render_widget(id)
{
{% for attr in attribute_types %}
if( id == {{ attr.id }} ) {
render_{{ attr.type }}()
}
{% endfor %}
}

The above is raw and you need to refine it, taking into account which
row in the form the widget should be rendered etc.
In the ModelAdmin you then add extra media or you simply override the
template and add the url for this dynamic javascript to the template.
Take a look at contrib/gis/templates/gis/admin/openlayers.js for
django-generated javascript inspiration.

--
Melvyn Sopacua

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate