2009年2月10日星期二

Re: [fw-mvc] Dojo Form Problem

-- Ed Lazor <edlazor@internetarchitects.biz> wrote
(on Tuesday, 10 February 2009, 07:47 AM -0800):
> Could you tell me what I'm doing wrong on this form? The form
> displays, but it won't submit and display errors when you leave the
> form blank.

You need to bind the form's onSubmit action to first validate prior to
submission. You can do that fairly easily:

dojo.connect(dijit.byId("<FORMIDHERE>"), "onSubmit", function(e){
e.preventDefault();
var form = dijit.byId("<FORMIDHERE>");
if (form.isValid()) {
form.submit();
return true;
}
return false;
});

You can add that to the form via a decorator, or add this as a
dojo.addOnLoad event for the page.


> Here's code for the form, code for the controller loading the form,
> and code for the view displaying the form.
>
>
> ---------------------------------------------------------
> Form code:
> ---------------------------------------------------------
> class Test2Form extends Zend_Dojo_Form {
>
> public $drivers = array("-- Select --", "Rob Allen", "Charlie Brown",
> "Lucy van Pelt");
>
> public function __construct($options = null) {
> parent::__construct($options);
> $this->setName('mileagelog');
>
> $user_id = new Zend_Form_Element_Select('user_id');
> $user_id
> ->setLabel('Driver:')
> ->setMultiOptions($this->drivers)
> ->setRequired(true)
> ->addErrorMessage("Please choose a driver.")
> ->addValidator(new Zend_Validate_GreaterThan(0));
> $this->addElement($user_id);
>
> $logDate = new Zend_Dojo_Form_Element_DateTextBox('logDate');
> $logDate
> ->setLabel('Log Date')
> ->setRequired(true)
> ->addValidator('NotEmpty')
> ->addErrorMessage("Please provide a date.");
> $this->addElement($logDate);
>
> $submit = new Zend_Form_Element_Submit('submit');
> $this->addElement($submit);
>
> }
> }
>
> ---------------------------------------------------------
> Controller code:
> ---------------------------------------------------------
> public function test2Action() {
> $form = new Test2Form();
> $this->view->title = "Test Form Validation";
> $request = $this->getRequest();
> $form->setAction('/post/test2')->setMethod('post');
> $this->view->form = $form;
>
> if ($request->isPost()) {
> $formData = $request->getPost();
> if ($form->isValid($formData)) {
> echo "Success!";
> } else {
> $this->view->messages = $form->getMessages();
> $form->populate($formData);
> }
> }
> }
>
>
> ---------------------------------------------------------
> View code:
> ---------------------------------------------------------
> echo "<h1>{$this->title}</h1>\n";
> if (!empty($this->messages)) {
> echo "<ul>\n";
> foreach ($this->messages as $field => $messageList) {
> foreach ($messageList as $message) {
> echo "<li>$message</li>\n";
> }
> }
> echo "</ul>\n";
> }
> echo $this->form;
> echo $this->content;
>

--
Matthew Weier O'Phinney
Software Architect | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: