summaryrefslogtreecommitdiff
path: root/ishtar/furnitures/widgets.py
blob: 6276e27716b4ee3f0f43386bd254d1247882c63f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>
# Copyright (C) 2007  skam <massimo dot scamarcia at gmail.com>
#                          (http://djangosnippets.org/snippets/233/)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.
from django import forms
from django.utils.safestring import mark_safe
from django.forms.widgets import flatatt
from django.utils.encoding import smart_unicode
from django.utils.html import escape
from django.utils.simplejson import JSONEncoder
from django.core.urlresolvers import resolve
from django.utils.translation import ugettext_lazy as _

from ishtar import settings

class DeleteWidget(forms.CheckboxInput):
    def render(self, name, value, attrs=None):
        final_attrs = flatatt(self.build_attrs(attrs, name=name,
                                               value='1'))
        output = ['<tr class="delete"><td colspan="2">']
        output.append(u"<button%s>%s</button>" % (final_attrs, _("Delete")))
        output.append('</td></tr>')
        return mark_safe('\n'.join(output))

class JQueryDate(forms.TextInput):
    def render(self, name, value=None, attrs=None):
        rendered = super(JQueryDate, self).render(name, value, attrs)
        rendered += """
<script type="text/javascript"><!--//
    $(function() {$("#id_%s").datepicker($.datepicker.regional["%s"]);});
//--></script>
""" % (name, settings.COUNTRY)
        return rendered

class JQueryAutoComplete(forms.TextInput):
    def __init__(self, source, associated_model=None, options={}, attrs={}):
        """
        Source can be a list containing the autocomplete values or a
        string containing the url used for the request.
        """
        self.options = None
        self.attrs = {}
        self.source = source
        self.associated_model = associated_model
        if len(options) > 0:
            self.options = JSONEncoder().encode(options)
        self.attrs.update(attrs)

    def render_js(self, field_id):
        if isinstance(self.source, list):
            source = JSONEncoder().encode(self.source)
        elif isinstance(self.source, str) or isinstance(self.source, unicode):
            source = "'%s'" % escape(self.source)
        else:
            try:
                source = "'" + unicode(self.source) + "'"
            except:
                raise ValueError('source type is not valid')
        options = 'source : ' + source
        options += ''', select: function( event, ui ) {
            if(ui.item){
                $('#id_%s').val(ui.item.id);
            } else {
                $('#id_%s').val(null);
            }
        }, minLength: 2
        ''' % (field_id, field_id)
        if self.options:
            options += ',%s' % self.options

        js = u'$(\'#id_select_%s\').autocomplete({%s});\n' % (field_id, options)
        js += u'''$(\'#id_select_%s\').live('click', function(){
                $('#id_%s').val(null);
                $('#id_select_%s').val(null);
});''' % (field_id, field_id, field_id)
        return js

    def render(self, name, value=None, attrs=None):
        attrs_hidden = self.build_attrs(attrs, name=name)
        attrs_select = self.build_attrs(attrs)

        if value:
            val =  escape(smart_unicode(value))
            attrs_hidden['value'] = val
            attrs_select['value'] = val
            if self.associated_model:
                try:
                    attrs_select['value'] = unicode(self.associated_model.\
objects.get(pk=value))
                except:
                    attrs_select['value'] = ""
        if not self.attrs.has_key('id'):
            attrs_hidden['id'] = 'id_%s' % name
            attrs_select['id'] = 'id_select_%s' % name
        if 'class' not in attrs_select:
            attrs_select['class'] = 'autocomplete'
        return u'''<input%(attrs_select)s/>\
<input type="hidden"%(attrs_hidden)s/>\
        <script type="text/javascript"><!--//
        $(function() {%(js)s});//--></script>
        ''' % {
            'attrs_select' : flatatt(attrs_select),
            'attrs_hidden' : flatatt(attrs_hidden),
            'js' : self.render_js(name),
        }

class JQueryJqGrid(forms.RadioSelect):
    COL_TPL = "{name:'%(idx)s', index:'%(idx)s', sortable:true}"
    class Media:
        js = ['%s/js/i18n/grid.locale-%s.js' % (settings.MEDIA_URL,
                                                settings.COUNTRY),
              '%s/js/jquery.jqGrid.min.js' % settings.MEDIA_URL,
             ]
        css = {'all':['%s/media/ui.jqgrid.css' % settings.MEDIA_URL]}

    def __init__(self, source, form, cols, attrs={}):
        self.source = source
        self.form = form
        self.attrs = attrs
        self.cols = cols

    def render(self, name, value=None, attrs=None):
        rendered = unicode(self.form)
        """
        for k in self.form.fields:
            field = self.form.fields[k]
            print unicode(field)
            print field.label_tag
            rendered += u"<tr><td>%s</td><td>%s</td></tr>" % (field.label_tag,
                                                              unicode(field))
           """
        rendered += """
</table>
<button id='search_%s' class='submit'>%s</button>
<h4>%s</h4>
""" % (name, unicode(_("Search")), unicode(_("Search and select an item")))
        extra_cols = []
        col_names, col_idx = [], []
        for k in self.form.fields:
            field = self.form.fields[k]
            col_idx.append(u'"%s"' % k)
            if k in self.cols:
                col_names.append(u'"%s"' % field.label)
                extra_cols.append(self.COL_TPL % {'idx':k})
        col_names = col_names and ",".join([""]+col_names) or ""
        col_idx = col_idx and ",".join(col_idx) or ""
        extra_cols = extra_cols and ",".join([""]+extra_cols) or ""
        rendered += """<table id="grid_%s" class='jqgrid'></table>
<div id="pager_%s"></div>
<input type="hidden" id="hidden_%s" name="%s">""" % (name, name, name, name)
        rendered += """
<script type="text/javascript">
var query_vars = new Array(%(col_idx)s);
jQuery(document).ready(function(){
jQuery("#submit_form").click(function (){
    var mygrid = jQuery("#grid_%(name)s");
    jQuery("#hidden_%(name)s").val(mygrid.getGridParam('selrow'));
    return true;
});
jQuery("#search_%(name)s").click(function (){
    var data = "";
    for (idx in query_vars)
    {
        var key = query_vars[idx];
        var val = jQuery("#id_"+key).val();
        if (val){
            if (data) data += "&";
            data += key + "=" + val;
        }
    }
    var mygrid = jQuery("#grid_%(name)s");
    var url = "%(source)s?" + data;
    mygrid.setGridParam({url:url});
    mygrid.trigger("reloadGrid");
    return false;
});

jQuery("#grid_%(name)s").jqGrid({
    url:'%(source)s',
    datatype: "json",
    mtype: 'GET',
    colNames:['id', '%(name_label)s'%(col_names)s],
    colModel:[
{name:'id', index:'id', hidden:true},
{name:'value', index:'value'}%(extra_cols)s
    ],
    sortname: 'value',
    viewrecords: true,
    sortorder: "asc",
    emptyrecords: "%(no_result)s",
    loadtext: "%(loading)s",
    pager: '#pager_%(name)s',
    pgbuttons: false,
    pginput: false,
    width:740
});
});
</script>
""" % {'name':name, 'col_names':col_names, 'extra_cols':extra_cols,
       'name_label':unicode(_("Name")), 'source':unicode(self.source),
       'col_idx':col_idx, 'no_result':unicode(_("No results")),
       'loading':unicode(_("Loading..."))}
        return rendered