문제

I am using bootstrap with zend 2. The content of the modal is retrieved through ajax call. But the validation doesn't work at all, it submits without checking any field:

Here is where the modal loads:

<div class="modal fade" id="themesModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

        </div>
    </div>
</div>

Here is the modal content:

<div class="modal-body">
    <div id="themesbox">
        <div class="panel panel-info">

            <div class="panel-heading">
                <div class="panel-title">title</div>
            </div>

            <div style="padding-top: 30px" class="panel-body">
                           <?php
                                $form = $this->form;
                                $form->setAttribute('action', $this->url('user/default', array('controller' => 'users', 'action' => 'create')));
                                $form->prepare();
                                echo $this->form()->openTag($form);
                                ?>

                                <div id="mydiv"
                    style="display: none" class="alert alert-danger">
                    <p>Error:</p>
                    <span></span>
                </div>


                <div class="form-group">
                    <label for="name" class="col-md-3 control-label">user</label>
                    <div class="col-md-9">
                                        <?php echo $this->formElement($form->get('name'));?>
                                    </div>
                </div>

                <div class="form-group">
                    <label for="description" class="col-md-3 control-label">password</label>
                    <div class="col-md-9">

                                        <?php echo $this->formElement($form->get('password'));?>
                                    </div>
                </div>


                <div style="margin-top: 10px" class="form-group">
                    <!-- Button -->
                    <div class="col-sm-12 controls">
                    <?php echo $this->formSubmit($form->get('submit'));?>
                    <button id="cancel" class="btn btn-success" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
                    <?php echo $this->form()->closeTag();?>  
            </div>
            <!-- /.panel-body -->
        </div>
        <!-- /. panel panel-info -->
    </div>
</div>

Here is the jquery validation code:

 $('.form-validation').each(function () {
     $(this).validate({


    errorElement: "span",
    errorClass: "help-block",   

    highlight: function(element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
        $(element).attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
    },
    unhighlight: function(element) {
        $(element).addClass('valid').closest('.control-group').removeClass('error').addClass('success');
        $(element).attr('style', "border-radius: 4px; border:1px solid #ccc;");
    },
    errorPlacement: function (error, element) {
        $(error).attr('style', "color: #FF0000;");
        if ( element.prop('type') === 'checkbox') {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }

  });
 });

And here is the form code:

 $this->add(array(
            'name' => 'name',

            'attributes' => array(
                'type'  => 'text',
                'id' => 'username',
                'class'  => 'form-control',
                'required'  => 'true',
                'minlength'  => '8',
                'maxlength'  => '20',
            ),
            'options' => array(
                'label' => 'name',
            ),
        ));

        $this->add(array(
            'name' => 'description',

            'attributes' => array(
                'type'  => 'password',
                'id' => 'password',
                'class'  => 'form-control',
                'required'  => 'true',
                'minlength'  => '8',
                'maxlength'  => '20',
            ),
            'options' => array(
                'label' => 'Password',
            ),
        ));
도움이 되었습니까?

해결책 2

In a matter of fact all the server side validation mechanisms were in place and were working perfectly.

I needed client side validations through jquery.

Because the content of Bootstrap modal dialog is loading from ajax, it didn't consider the surrounding context as usual, I needed to insert jquery code in the ajax content.

ZF2 doesn't permit inserting js code in its view files.

So I did in the following way inserting the following line in the ajax content:

 <?php echo $this->inlineScript()->appendFile($this->basePath() . '/js/custom.js')?>

다른 팁

I have this working using a different method.

Rather than try to do your own validation on the client side (adding the error HTML etc) you should submit the form via AJAX and let ZF2 return a JsonModel with the form's markup.

If you are using the correct view helpers (FormRow specifically) it will correctly render the form errors.

For example

class FooController extends AbstractActionController
{

   public function createAction()
   {
     $request = $this->getRequest();
     $service = $this->getServiceLocator()->get('FooService'); 
     $form    = $service->getFooCreateForm(); // Zend\Form

     if ($request->isPost()) {
        $form->setData($request->getPost());

        if ($form->isValid()) {

            $foo = $service->create($form->getData());

            if ($foo instanceof Foo)
                // redirect to success page
            } else {
                $this->flashMessenger()->addErrorMessage('Error!');
            }
            return $this->redirect()->toRoute('foo', array('action' => 'index'));

        } else if ($request->isXmlHttpRequest()) {

            $renderer = $this->getServiceLocator()->get('viewrenderer');
            $formView = new ViewModel(compact('form')); // add the form to the view
            $formView->setTemplate('foo-module/foo/form');

            return new JsonModel(array(
                'success' => false, // Flag to keep modal open
                'content' => $renderer->render($formView), // The "content" being the form HTML
                'message' => 'Please check all form fields have been completed successfully',
            ));
        }
     }
     return new ViewModel(compact('form'));
   }

}

form.phtml

<?php
  echo $this->form($this->form);

create.phtml

//...modal html
<div class="modal-body">
    <?php echo $this->partial('form.phtml', compact('form')); ?>
</div>
//... modal html

And you would also want to:

  • Remove any buttons from the ZF2 forms (as the modal already has two)
  • Add an JS event listener to the modal submit button and AJAX post the form content to the createAction
  • If the result of the call is success == true then close the modal
  • If the result is success == false you will have the content variable which can then replace the existing modal content using $('.modal-content').html(result.content) This will include the validated form HTML (including all the errors generated view the form view helpers).
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top