Thread Subroutine über Formularbutton aufrufen (4 answers)
Opened by Ben at 2009-09-22 15:00

pktm
 2009-09-22 16:08
#126017 #126017
User since
2003-08-07
2921 Artikel
BenutzerIn
[Homepage]
user image
Also, das mit in einer Datei mache ich nicht, weil ich Templates nie in Module einbette. So sind es also zwei Dateien: run.pl und workspace.tmpl

Hier also, wie ich mir das so vorstelle. Da sind einige Techniken dabei, die dein Ansatz nicht enthält, z.B. die Verwendung von CPAN:CGI::Application, CPAN:HTML::Template für Templates, diese Platzhalter oder CPAN:Data::FormValidator zur Überprüfung von Benutzereingaben.

Ich hoffe, du kannst mit dem Code etwas anfangen, zumindest was den Zugriff von Daten aus Formularen angeht. Generell schließe ich mich pq an, bitte wirf deinen Code weg :)

./run.pl
Code: (dl )
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/Perl/bin/perl

package CatcherInTheRye;

use strict;
use warnings;
use base qw/CGI::Application/;

use CGI::Application::Plugin::Forward;
use CGI::Application::Plugin::Redirect;
use CGI::Application::Plugin::ConfigAuto qw/cfg/;
use CGI::Application::Plugin::ValidateRM;
use CGI::Application::Plugin::DBH (qw/dbh_config dbh/);

#use CGI::Application::Plugin::Session; # for MessageStack
#use CGI::Application::Plugin::MessageStack;

# for development
use CGI::Application::Plugin::DebugScreen;

use Data::Dumper qw/Dumper/;

=head1 NAME

CatcherInTheRye - Perl extension for blah blah blah

=head1 SYNOPSIS

use CatcherInTheRye;
blah blah blah

=head1 DESCRIPTION

Stub documentation for CatcherInTheRye, created by h2xs. It looks like the author of the extension was negligent enough to leave the stub unedited.

This one uses a database with the following tabel in schema 'test':

--
-- Definition of table `time_reports`
--

DROP TABLE IF EXISTS `time_reports`;
CREATE TABLE `time_reports` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`field` varchar(45) NOT NULL,
`number` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;



=head2 EXPORT

None by default.


=head1 METHODS

=cut

=head2 cgiapp_init()

Open database connection, setup config files, etc.

=cut

sub cgiapp_init {
my $self = shift;

# -- Database configuration.
#my $dbc = $self->cfg('db'); # todo: use a config file

my $dbc = {
'dsn' => 'DBI:mysql:test:localhost',
'username' => 'Test',
'password' => 'test',
'db_attributes' => {
'PrintError' => 0,
'RaiseError' => 0,
'AutoCommit' => 1,
},
};

my $data_source = $dbc->{dsn};
my $username = $dbc->{username};
my $auth = $dbc->{password};
my $attr_href = $dbc->{attributes};
$self->dbh_config($data_source, $username, $auth, $attr_href);


# -- Set some defaults for DFV unless they already exist.
$self->param('dfv_defaults') ||
$self->param('dfv_defaults', {
missing_optional_valid => 1,
filters => 'trim',
msgs => {
any_errors => 'some_errors',
prefix => 'err_',
invalid => 'Invalid',
missing => 'Missing',
format => '<span class="dfv-errors">%s</span>',
},
});

} # /cgiapp_init




=head2 setup()

Defined runmodes, etc.

=cut

sub setup {
my $self = shift;

$self->start_mode('start');
$self->run_modes([qw/
start
new_form
new_validate
/]);

} # /setup




=head2 cgiapp_prerun()

We know what the runmode will be. Do we want to do anything about it?

=over
=item Authentication?
=item Authorization?
=item Redirection?
=back

=cut

sub cgiapp_prerun {
my $self = shift;
} # /cgiapp_prerun




=head2 cgiapp_get_query()

Bote: uploads are disabled by default in CGI::Simple.

=cut

sub cgiapp_get_query {
require CGI::Simple;
my $q = new CGI::Simple;
return $q;
} # /cgiapp_get_query




=head2 start( $errs )

Display the workspace with link to anything the user can do or data 'n stuff.

=cut

sub start {
my $self = shift;
my $errs = shift; # may be undef

# -- get the data to display in the workspace, that is all records that
# have been saved until now.
my @all_records = ();

my $sql = qq~
SELECT * FROM time_reports
~;

my $dbh = $self->dbh();
my $sth = $dbh->prepare($sql) or return("Error preparing SQL. Unfortunately for you, I didn't implement any error handling.");
my $rv = $sth->execute() or return("Error executing SQL. Unfortunately for you, I didn't implement any error handling.");

while( my $row_href = $sth->fetchrow_hashref() ) {
push @all_records, $row_href; # some magic here
}

my $t = $self->load_tmpl('workspace.tmpl', associate => $self);
$t->param('c.query.url' => $self->query->url());
$t->param($errs) if $errs;
$t->param(records => \@all_records) if @all_records;
return $t->output();
} # /start




=head2 new_validate()

Validate user input.

Unless valid, redirect to form, display errors.

If valid, write things to DB or wherever you want to store it.

=cut

sub new_validate {
my $self = shift;

my $form_profile = {
required => [qw/field number/],
optional => [qw/rm submit/],
constraints => {
field => qr/^.{1,45}$/,
number => qr/^\d+$/,
}
};

my $results = $self->check_rm('start', $form_profile) || return $self->check_rm_error_page();


# -- Results are valid, create new record in DB.
# INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
# [INTO] tbl_name [(col_name,...)]
# VALUES ({expr | DEFAULT},...),(...),...
# [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
my $sql = qq~
INSERT INTO time_reports (field, number) VALUES (?,?)
~;

my $dbh = $self->dbh();
my $sth = $dbh->prepare($sql) or return("Error preparing SQL. Unfortunately for you, I didn't implement any error handling.");
my $rv = $sth->execute($results->valid('field'), $results->valid('number')) or return("Error executing SQL. Unfortunately for you, I didn't implement any error handling.");


# -- todo: set up a confirmation message
#$self->push_message(
# -scope => 'mainpage',
# -message => 'Your stuff has been written',
# -classification => 'INFO',
#);


# -- Redirect to workspace
my $url = $self->query->url(-absolute => 1,) . '?rm=start';
return $self->redirect($url);
} # /new_validate




=head2 cgiapp_postrun( $output )

Output manipulation:

=over
=item add common header/footer?
=item Cleanup your HTML?
=item Rewrite URLs?
=back

=cut

sub cgiapp_postrun {
my $self = shift;
my $output = shift;



} # /cgiapp_postrun




=head2 teardown()

Close database connections (if not persistant), flush out session storage, etc.

=cut

sub teardown {
my $self = shift;

} # /teardown


=head1 SEE ALSO

Mention other useful documentation such as the documentation of related modules or operating system documentation (such as man pages in UNIX), or any relevant external documentation such as RFCs or standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

A. U. Thor, E<lt>a.u.thor@a.galaxy.far.far.awayE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by A. U. Thor

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.

=cut

1;


use strict;
use warnings;
use FindBin qw/$Bin/;

my $app = CatcherInTheRye->new(
TMPL_PATH => $Bin . '/templates',
);
$app->run();


./templates/workspace.tmpl
Code: (dl )
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Boring</title>

<style type="text/css" media="screen">
input.error {
border: 1pt outset #FF8000;
color: black;
background-color: #FFFFCC;
}
</style>

</head>
<body>

<h1>workspace</h1>

<p>Links to anything you can do or data 'n stuff.</p>

<h2>form</h2>

<!-- TMPL_IF CAP_Messages -->
<div style="border: 2px solid blue;">
<h2>Messages</h2>
<!-- TMPL_LOOP NAME="CAP_Messages" -->
<div class="<!-- TMPL_VAR NAME="classification" -->">
<!-- TMPL_VAR NAME="message" -->
</div>
<!-- /TMPL_LOOP -->
</div>
<!-- /TMPL_IF -->

<!-- TMPL_IF some_errors -->
<p style="color: red; font-weight: bold;">Your input is not valid. How hard could it be? *sigh*</p>
<!-- /TMPL_IF -->

<form action="<TMPL_VAR c.query.url>">
<input type="hidden" name="rm" value="new_validate" />

<fieldset>
<legend>New record</legend>

<div>
<label for"field">Random anything (e.g. "cookie", min 1, max 45 chars, required)</label>
<input type="text" name="field" id="field" <TMPL_IF err_field>class="error"</TMPL_IF> />
</div>

<div>
<label for"field">Random int (e.g. 4, required)</label>
<input type="text" name="number" id="number" <TMPL_IF err_number>class="error"</TMPL_IF> />
</div>

<div>
<input type="submit" name="submit" value="make some" />
</div>
</fieldset>

</form>

<hr />

<h2>data 'n stuff</h2>


<!-- TMPL_IF records -->

<table>
<tr>
<th>#</th>
<th>field</th>
<th>number</th>
</tr>

<!-- TMPL_LOOP records -->

<tr>
<td><!-- TMPL_VAR id --></td>
<td><!-- TMPL_VAR field --></td>
<td><!-- TMPL_VAR number --></td>
</tr>

<!-- /TMPL_LOOP -->

</table>

<!-- TMPL_ELSE -->

<p>There are no records, go make some. Now!</p>

<!-- /TMPL_IF -->

</body>
</html>


Fragen? Fragen!

Edit: Käferchen
Last edited: 2009-09-22 17:33:07 +0200 (CEST)
http://www.intergastro-service.de (mein erstes CMS :) )

View full thread Subroutine über Formularbutton aufrufen