Add ability to toggle fields in forms
authorMagnus Hagander <magnus@hagander.net>
Wed, 30 Jan 2013 13:01:25 +0000 (14:01 +0100)
committerMagnus Hagander <magnus@hagander.net>
Wed, 30 Jan 2013 13:01:25 +0000 (14:01 +0100)
This uses jQuery to make it possible to enable and disable fields in the
default forms, by specifying an attribute on the form class. The form
class still has to implement proper validators, so it does not rely on
client side validations.

pgweb/util/helpers.py
templates/base/form.html

index 831cb05816f3f3f1fb9e5560aafbb7fc8aa16767..817f416e80f1bdeb1b887383d2c084f848ac7b92 100644 (file)
@@ -57,6 +57,7 @@ def simple_form(instancetype, itemid, request, formclass, formtemplate='base/for
                'formitemtype': instance._meta.verbose_name,
                'markdownfields': markdownfields,
                'form_intro': hasattr(form, 'form_intro') and form.form_intro or None,
+               'toggle_fields': hasattr(form, 'toggle_fields') and form.toggle_fields or None,
                'savebutton': (itemid == "new") and "New" or "Save",
                'operation': (itemid == "new") and "New" or "Edit",
        }, NavContext(request, navsection))
index ec90bbf6d239c7ee5898aff90f143bb04db1876c..3cc4e4722eb4b59bfd2a412333aeb5e1b66c461f 100644 (file)
       {%endfor%}
    }
 </script>
+{%if toggle_fields%}
+<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
+<script language="javascript">
+{%for f in toggle_fields%}
+function toggle_{{f.name}}() {
+   v = $('#id_{{f.name}}').prop('checked');
+{%for c in f.fields%}
+{%if f.invert%}
+   if (v) {
+{%else%}
+   if (!v) {
+{%endif%}
+      $('#id_{{c}}').attr('disabled', true);
+   } else {
+      $('#id_{{c}}').removeAttr('disabled');
+   }
+{%endfor%}
+}
+$(document).ready(function() {
+   $('#id_{{f.name}}').change(function() {
+      toggle_{{f.name}}();
+   });
+   toggle_{{f.name}}();
+});
+{%endfor%}
+</script>
+{%endif%}
 {%endif%}
 {%endblock%}