简体   繁体   English

如何在PHP中使用Phalcon创建分步表单

[英]How to create a step by step form with Phalcon in PHP

I'm currently working on a project using the Phalcon Framework that has pages with complex forms and a lot of inputs, to break it down nicely I'm dividing the forms into a step-by-step process. 我目前正在使用Phalcon框架进行一个项目,该项目的页面包含复杂的表单和大量的输入,为了更好地分解它,我将表单分为一个逐步的过程。

How would one validate the form on each step before going to the next step and then save the whole form on the final step? 在进行下一步之前,如何在每个步骤上验证表单,然后将整个表单保存到最后一步?

I can't seem to find anything documented about this sort of process as it likes to validate the form in it's entirety if I use the form builder. 我似乎找不到任何有关此类过程的文档,因为如果我使用表单生成器,它喜欢完全验证表单。

Simple, just create a custom methods in your form class to validate any step, and the posted data from some step save into message class and store it into session by "stepX", when posted data is not valid just set defaults from post. 很简单,只需在表单类中创建一个自定义方法来验证任何步骤,然后将某个步骤中发布的数据保存到消息类中,并通过“ stepX”将其存储到会话中,当发布的数据无效时,只需设置发布的默认值即可。 When valid save it into session as i describe above. 有效时,将其保存到如上所述的会话中。

For example how i mean "controller" 例如我的意思是“控制器”

<?php
class MyController extends BaseController {
     public function processStep1Action(){
           $form = new MyForm();
           if($this->request->isPost()){//im using my custom request class 
              if(!$form->isValid($this->request->getPost()){
                  //error messages goes here
                  $form->setDefaultsFromRequest($this->request); // it will set the filled data
              }
              else {
                  $messageClass = new MyMessageContainer();
                  $messageClass->setData($this->request);//inside parse requested data into message class, or parse it as $messageClass->name = $this->request->getPost('name');

                  $this->session->save('step1',$messageClass); //maybe it would be want to serialize it
                  //then redirect to the step 2 or x

              }
           }
     }
}

So in the next step you can access data from sessions $this->session->get('step1'); 因此,在下一步中,您可以从会话$ this-> session-> get('step1');访问数据。 so you can in final step load all posted data and store it into DB. 因此,您可以在最后一步中加载所有发布的数据,并将其存储到数据库中。

I hope this helps! 我希望这有帮助! :) :)

here is my form maybe it can be helpful for you. 这是我的表格,可能对您有帮助。

<?php 

namespace Manager\Library\Forms\User;

use Phalcon\Forms\Form,
    Phalcon\Forms\Element\Email,
    Phalcon\Forms\Element\Select,
    Phalcon\Forms\Element\Password,
    Phalcon\Forms\Element\Check,
    Phalcon\Validation\Validator\Confirmation,
    Phalcon\Validation\Validator\StringLength,
    Phalcon\Forms\Element\Submit,
    Phalcon\Validation\Validator\PresenceOf,
    Model\Group;

class AddUser extends Form {
    public function initialize()
    {
        $email = new Email('email');
        $email->addValidators(array(
            new \Phalcon\Validation\Validator\Email(array(
            'message' => 'Nezadali jste email nebo má nesprávny tvar(email@domena.tld).'
            ))
        ));

                $this->add($email);

        $this->initGroupElement();

                $password = new Password('password');
        $password
            ->addValidator(new StringLength(array('min' => 6,'messageMinimum'   => 'Nezadali jste heslo nebo je příliš krátke, minimální počet znaků je 6.')))
            ->addValidator(new Confirmation(array('with'    => 'password-again',"message"   => "Zadané hesla se neshodují.")));
        $this->add($password);

        $repeatPassword = new Password('password-again');
        $this->add($repeatPassword);

                $this->initializeProfileElements();
                $active = new Check('active',array('value'  => 1));
                $this->add($active);
        $this->add( new Submit('save') );

                \Phalcon\Tag::setDefault('password', '');
                \Phalcon\Tag::setDefault('password-again', '');
    }

        public function initializeEdit(){
            $email = new Email('email');
        $email->addValidators(array(
            new \Phalcon\Validation\Validator\Email(array(
            'message' => 'Nezadali jste email nebo má nesprávny tvar(email@domena.tld).'
            ))
        ));

                $this->add($email);

        $this->initGroupElement();

                $password = new Password('password');

        $this->add($password);

        $repeatPassword = new Password('password-again');
        $this->add($repeatPassword);

                $this->initializeProfileElements();
                $active = new Check('active',array('value' => 1));
                $this->add($active);
        $this->add( new Submit('save') );

                \Phalcon\Tag::setDefault('password', '');
                \Phalcon\Tag::setDefault('password-again', '');
        }

        protected function initGroupElement(){
            $auth = \Core\Auth::getIdentity();
            $groups = new Group();
//            $groups->addColumns(array('id','name'));
            //set global condition about Super Admin
            $groups->addFilter('id', 1,'<>');

            if($auth){
                //set restrictions for main groups
                if((int)$auth->group_id === 1){ //super admingroup
                    //no filter
                }
                else if((int)$auth->group_id === 2){ //admin group
                    $groups->addFilter('id', 1,'>');
                }
                else if((int)$auth->group_id === 6){//Provozovatel group
                    $groups->addFilter('id',array(3,6,7));
                    $groups->addFilter('public', 1,'=',true);
                }
                else { // other groups
                    $groups->addFilter('public', 1);
                }
            }

            $groups = $groups->findFiltered();
            $groupElement = new Select('group');
            foreach($groups as $group){
                $groupElement->addOption(array($group->id => $group->name));
            }

            $this->add($groupElement);

        }

        protected function initializeProfileElements(){
            $forename = new \Phalcon\Forms\Element\Text('forename');
            $this->add($forename);
            $surname = new \Phalcon\Forms\Element\Text('surname');
            $this->add($surname);
            $street = new \Phalcon\Forms\Element\Text('street');
            $this->add($street);
            $postal = new \Phalcon\Forms\Element\Text('postal');
            $this->add($postal);
            $city = new \Phalcon\Forms\Element\Text('city');
            $this->add($city);
            $ic = new \Phalcon\Forms\Element\Text('ic');
            $this->add($ic);
            $dic = new \Phalcon\Forms\Element\Text('dic');
            $this->add($dic);
        }

        public function setDefault($fieldName,$value){
            \Phalcon\Tag::setDefault($fieldName, $value);
        }

        public function setDefaults($object){
            if($object instanceof \Model\User){
                $this->setDefaultsFromObject($object);
            }
            else if($object instanceof \Phalcon\Http\Request){
                $this->setDefaultsFromRequest($object);
            }
        }

        protected function setDefaultsFromObject(\Model\User $user){
            $profile = $user->getRelated('\Model\Profile');   
            \Phalcon\Tag::setDefaults(array(
                'email'     => $user->email,
                'group'     => $user->group_id,
                'active'    => $user->active,
                'forename'  => $profile->forename,
                'surname'   => $profile->surname,
                'street'    => $profile->street,
                'city'      => $profile->city,
                'postal'    => $profile->postal,
                'ic'        => $profile->IC,
                'dic'       => $profile->DIC
            ));
        }

        protected function setDefaultsFromRequest(\Phalcon\Http\Request $request){
            \Phalcon\Tag::setDefaults(array(
                    'email'     => $request->getPost('email'),
                    'group'     => $request->getPost('group'),
                    'active'    => $request->getPost('active')
             ));

            \Phalcon\Tag::setDefaults(array(
                'forename'  => $request->getPost('forename'),
                'surname'   => $request->getPost('surname'),
                'street'    => $request->getPost('street'),
                'city'      => $request->getPost('city'),
                'postal'    => $request->getPost('postal'),
                'ic'        => $request->getPost('ic'),
                'dic'       => $request->getPost('dic')
            ));
        }
}

In addition to Kamil's answer, another option to consider is to use Javascript on the front-end to handle your multi-step form. 除了Kamil的答案外,还可以考虑的另一种选择是在前端使用Javascript处理您的多步骤表单。 This will add some complexity as you will need to have the javascript to handle the form steps and do preliminary validation, but it only requires a single submit where you can validate content within a single method. 这将增加一些复杂性,因为您将需要使用JavaScript来处理表单步骤并进行初步验证,但它只需要一个提交即可在一个方法中验证内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM