source: trunk/LATMOS-Accounts-Web/lib/LATMOS/Accounts/Web/Model/AttrFormsA.pm @ 1722

Last change on this file since 1722 was 1722, checked in by nanardon, 8 years ago

Fix input for DATE/DATETIME attribute

File size: 11.2 KB
Line 
1package LATMOS::Accounts::Web::Model::AttrFormsA;
2
3use strict;
4use warnings;
5use base 'LATMOS::Accounts::Bases::Attributes';
6use base 'Catalyst::Model';
7use LATMOS::Accounts::Log;
8use Date::Parse;
9use DateTime;
10use DateTime::TimeZone;
11
12=head1 NAME
13
14LATMOS::Accounts::Web::Model::AttrForms - Catalyst Model
15
16=head1 DESCRIPTION
17
18Catalyst Model.
19
20=cut
21
22sub escape {
23    my ($self, $text) = @_;
24    $text ||= '';
25    for ($text) {
26        s/&/&/g;
27        s/</&lt;/g;
28        s/>/&gt;/g;
29        s/"/&quot;/g;
30    }
31    $text;
32}
33
34sub new {
35    my ($class) = @_;
36    bless({}, $class);
37}
38
39# call either OBJ or type + base
40
41sub ACCEPT_CONTEXT {
42    my ($self, $c, $attributes, $base_or_object, $maybe_otype) = @_;
43
44    my $new = LATMOS::Accounts::Bases::Attributes->new($attributes, $base_or_object, $maybe_otype);
45    $new->{c} = $c;
46    $new->{htmlname} = $attributes;
47    $new->{htmlname} =~ s/[\.-]/_/g;
48    $new->{htmlid} = $attributes;
49    $new->{htmlid} =~ s/[\.-]/_/g;
50    $new->{valcount} = 0;
51    $new->{hconfig} = LATMOS::Accounts::Web->config->{attrs}{$attributes} || {};
52    bless($new, __PACKAGE__);
53}
54
55sub htmlname {
56    $_[0]->{htmlname};
57}
58
59sub htmlid {
60    my ($self) = @_;
61
62    if ($self->{valcount}) {
63        return sprintf('%s_%03d', $self->{htmlid}, $self->{valcount});
64    } else {
65        return $_[0]->{htmlid};
66    }
67}
68
69sub htmlnewid {
70    my ($self) = @_;
71
72    $self->{valcount}++;
73
74    return $self->htmlid;
75}
76
77sub hconfig {
78    my ($self, $val) = @_;
79    $self->{hconfig}{$val}
80}
81
82sub attr_label {
83    my ($self, $label, $hint) = @_;
84    $label ||= '';
85   
86    $hint = $self->hconfig('hint');
87
88    return sprintf('<label %sfor="%s">%s</label>',
89        ($hint ? sprintf('title="%s"', $self->escape($hint)) : ''),
90        $self->escape($self->htmlname),
91        $self->escape($self->label || $self->htmlname),
92    );
93}
94
95sub attr_raw_value {
96    my ($self) = @_;
97
98    my @val = grep { $_ } (exists($self->{c}->req->params->{$self->htmlname}))
99        ? ($self->{c}->req->param($self->htmlname))
100        : $self->getValues;
101
102    if (@val) {
103        return @val;
104    } elsif(!$self->object) {
105        return (grep { $_ } ($self->default_value))
106    }
107}
108
109sub attr_field_name {
110    my ($self) = @_;
111
112    $self->htmlname;
113}
114
115sub attr_field {
116    my ($self, $type) = @_;
117
118    # Force Array context:
119    my @attr_raw_value = $self->attr_raw_value;
120    if (!$self->multiple) {
121        push(@attr_raw_value, undef) unless(@attr_raw_value);
122    }
123    my @htmls = ();
124
125    foreach my $attr_raw_value (@attr_raw_value) {
126        $self->htmlnewid;
127        push(@htmls, $self->attr_item($attr_raw_value));
128    }
129
130    if (my $js = $self->attr_js) {
131        push(@htmls,
132            qq[ <script>
133            \$( function() {
134            $js
135            });
136            </script>]
137        );
138    }
139
140    my $addempty = '';
141    if ($self->{multiple} && !$self->readonly) {
142
143        my $old = $self->{valcount} + 1;
144        $self->{valcount} = 999;
145        my $code = $self->attr_item('');
146        $code =~ s/'/\\'/g;
147
148        $addempty = sprintf('<div id="%s_div"></div>', $self->htmlid);
149        $addempty .= "\n";
150        $addempty .= sprintf(q|
151            <button id="%s_add" type="button" style="display:block">+</button>
152            <script type="text/javascript">
153            var cn_%s = %d;
154            $( '#%s_add' ).click(function(even, ui) {
155                $('#%s_div').append('%s'.replace(/%d/g, cn_%s)).append('<br>');
156
157                cn_%s++;
158                %s
159            });
160            </script>
161            |,
162            $self->htmlid,
163            $self->htmlid,
164            $old,
165            $self->htmlid,
166            $self->htmlid,
167            $code,
168            $self->{valcount},
169            $self->htmlid,
170            $self->htmlid,
171            $self->attr_js,
172        );
173
174        $addempty .= "\n";
175
176    }
177
178    return join("<br>\n", @htmls) . $addempty;
179}
180
181sub attr_item {
182    my ($self, $value) = @_;
183
184    my $html = '';
185
186    my $type = 'attr_' . uc($self->form_type);
187
188    if ($self->can($type)) {
189        $html .= $self->$type($value);
190    } else {
191        $html .= $self->attr_TEXT($value);
192    }
193
194    $html .= q|<span class="inputvalidate" id="|. $self->htmlid . q|_check"></span>|;
195
196    if (my $ref = $self->reference) {
197        my $uri_part = $self->_uri_part($ref);
198        if ($self->base->attribute($ref, 'displayName')) {
199            my $text = '';
200            if ($value &&
201                (my $obj = $self->base->get_object($ref, $value))) {
202                $text = $obj->get_attributes('displayName');
203            }
204            #$html .= sprintf(
205                #qq|<span id="${htmlid}_ref" style="margin-left: 1em">$text</span>|,
206                #   $self->escape($text),
207                #);
208        } elsif($value && $uri_part) {
209            $html .= sprintf(
210                '<a href="%s"><img class="attr" src="%s" title="%s"></a>',
211                $self->{c}->uri_for('/', $uri_part, $value),
212                $self->{c}->uri_for('/static', 'images', 'arrow-right.png'),
213                $value,
214            );
215        }
216    }
217
218    $html
219}
220
221sub attr_js {
222    my ($self, $value) = @_;
223
224    my $type = 'attr_' . uc($self->form_type) . '_js';
225
226    if ($self->can($type)) {
227        return $self->$type($value);
228    } else {
229        return '';
230    }
231}
232
233
234sub attr_TEXT {
235    my ($self, $value, $name, $id) = @_;
236
237    return sprintf(
238        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
239        $self->escape($id   || $self->htmlid),
240        $self->escape($name || $self->htmlname),
241        $self->escape($value),
242        $self->form_option('length') || 30,
243    );
244
245}
246
247sub attr_TEXT_js {
248    my ($self) = @_;
249
250    my $html = '';
251
252    if ($self->uniq) {
253        $html .= sprintf(q|
254                $( '[name="%s"]' ).on('input', function() {
255                    var id = $(this).attr('id');
256                    $.ajax({
257                        method: "POST",
258                        url: '%s',
259                        data: { val: $(this).val() },
260                    }). done(function( msg ) {
261                        $( '#' + id + '_check' ).html (msg);
262                    });
263                    return false;
264                });
265        |,
266        $self->htmlname,
267        $self->{c}->uri_for('/ajax', 'objattrexist', $self->otype, $self->name),
268        );
269    }
270
271    $html;
272}
273
274sub attr_LABEL {
275    my ($self, $value) = @_;
276
277    if ($self->real_form_type =~ m/(DATE|DATETIME)/) {
278        if (my $time = str2time($value)) {
279            my $dt = DateTime->from_epoch(epoch => $time);
280            $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
281            $value = $dt->dmy('/') . ($self->real_form_type eq 'DATE'
282                ? ''
283                : ' ' . $dt->hms(':'));
284        }
285    }
286
287    return $self->escape($value);
288}
289
290sub attr_TEXTAREA {
291    my ($self, $value) = @_;
292    return sprintf(
293        '<textarea id="%s" name="%s" cols="40">%s</textarea>',
294        $self->escape($self->htmlid),
295        $self->escape($self->htmlname),
296        $self->escape($value || ''),
297    );
298}
299
300
301sub attr_DATE {
302    my ($self, $value, $name, $id) = @_;
303   
304    warn "-- $name $value";
305
306    if (my $time = str2time($value)) {
307        my $dt = DateTime->from_epoch(epoch => $time);
308        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
309        $value = $dt->dmy('/')
310    }
311    warn $value;
312
313    return sprintf(
314        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
315        $self->escape($id   || $self->htmlid),
316        $self->escape($name || $self->htmlname),
317        $self->escape($value),
318        $self->form_option('length') || 20,
319    );
320}
321
322sub attr_DATE_js {
323    my ($self, $value) = @_;
324    return sprintf(q|
325        $('[name="%s"]').datepicker( {
326            changeMonth: true,
327            changeYear: true,
328            dateFormat: 'dd/mm/yy'
329        } );
330    |, $self->escape($self->htmlname));
331}
332
333sub attr_DATETIME {
334    my ($self, $value, $name, $id) = @_;
335
336    if (my $time = str2time($value)) {
337        my $dt = DateTime->from_epoch(epoch => $time);
338        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
339        $value = $dt->dmy('/') . ' ' . $dt->hms(':')
340    }
341
342    warn $value;
343
344    return sprintf(
345        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
346        $self->escape($id   || $self->htmlid),
347        $self->escape($name || $self->htmlname),
348        $self->escape($value),
349        $self->form_option('length') || 20,
350    );
351}
352
353sub attr_DATETIME_js {
354    my ($self, $value) = @_;
355    return sprintf(q|
356        $('[name="%s"]').datepicker( {
357            changeMonth: true,
358            changeYear: true,
359            dateFormat: 'dd/mm/yy'
360        } );
361    |, $self->escape($self->htmlname));
362}
363
364sub attr_CHECKBOX {
365    my ($self, $value) = @_;
366    $value ||= '';
367
368    return sprintf('<input type="checkbox" id="%s" name="%s"%s>%s',
369        $self->escape($self->htmlid),
370        $self->escape($self->htmlname),
371        ($value ? '  checked="yes"' : ''),
372        ($self->form_option('rawvalue') ? " $value" : ''),
373    );
374}
375
376sub attr_LIST {
377    my ($self, $value) = @_;
378
379    my @values = $self->can_values;
380    $value ||= '';
381
382    if (@values < 10) {
383        return sprintf(q|<select id="%s" name="%s">%s%s</select>|,
384            $self->htmlid,
385            $self->htmlname,
386            ($self->mandatory ? '' : '<option value="">--</option>'),
387            join(",\n", map { $_ = sprintf('<option value="%s"%s>%s</option>', $_, ($_ eq $value ? ' selected="selected"' : ''), $self->display($_)) } sort $self->can_values),
388        );
389    } else {
390        my $html = $self->attr_TEXT($self->display($value));
391    }
392}
393
394sub attr_LIST_js {
395    my ($self) = @_;
396    return sprintf(q|
397            $('[name="%s"]').autocomplete({
398                delay: 200,
399                minLength: 0,
400                source: '%s',
401            })
402            .autocomplete( "instance" )._renderItem = function( ul, item ) {
403                return $( "<li>" )
404                .append( "<a>" + item.label + " (" + item.value +  ")</a>" )
405                .appendTo( ul );
406            };
407        |,
408        $self->htmlname,
409        $self->{c}->uri_for('/json/refval', $self->otype, $self->name),
410    );
411}
412
413sub _uri_part {
414    my ($self, $ref) = @_;
415    my $uri_part = {
416        user => 'users',
417        group => 'groups',
418        nethost => 'nethosts',
419        netzone => 'netzones',
420        site => 'sites',
421        aliasess => 'aliases',
422    }->{$ref};
423}
424
425sub _attr_js_item {
426    my ($self, $value, $htmlid) = @_;
427
428    $htmlid = $self->htmlid;
429    my (@js);
430
431    if (my $ref = $self->reference) {
432        my $uri_part = $self->_uri_part($ref);
433        if ($self->base->attribute($ref, 'displayName')) {
434            push(@js, 
435                $self->{c}->prototype->observe_field( $htmlid,
436                    {
437                        update => "${htmlid}_ref",
438                        url => $self->{c}->uri_for('/ajax', 'rawattr', $ref),
439                        frequency => 1,
440                        with   => "'attr=displayName&id=' + element.options[element.selectedIndex].text",
441                    }
442                )
443            ) if ($self->form_type =~ /list/i);
444        }
445    }
446
447    return(join("\n", @js));
448}
449
450
451=head1 AUTHOR
452
453Thauvin Olivier
454
455=head1 LICENSE
456
457This library is free software, you can redistribute it and/or modify
458it under the same terms as Perl itself.
459
460=cut
461
4621;
Note: See TracBrowser for help on using the repository browser.