Creating a Form Wizard in PHP using Vue.js

We can create a simple wizard in PHP using Vue.js. This is great for a single page application if you don’t want to mess with a older built PHP application. You can deploy your form wizard using Vue.js and just point the form submit URL wherever you want it to go. Vue.js gives you quick setup time and low overhead with a lesser chance of conflicts. You can build the form simply without using external libraries that you don’t understand. In the end however its just another way to using Vue.js.

PHP Vue Start screen

The wizard we create will have three main pages. The first page allows the user to add some contact information. There are two required fields – name and email. You can also add a phone number.

Wizard first screen

The next screen displays a form allowing the user to post some text content. You can add a post title and add the post in a text area.

Post View

After you have a summary page where the user can submit the information.

The summary view

The Wizard

All of your HTML content is in the wizard.php file. When we create the wizard view we have three main sections, for the three screens of the wizard. Check out the full wizard file here.

<div class="card" v-if="show == 'cardone'" style="height: 350px;"></div>

Each of these views are within a div that as the v-if binding. It checks the show variable to see which view we wanted to be shown. The script for this application is in wizard-script.js. Our vue object is created with all the data elements we will need to create this app.

var myObject = new Vue({
    el: '#app',
    data : {
        cards : 3,
        currentCard:1,
        summary : "",
        name : "",
        email : "",
        contact : "",
        postTitle : "",
        postContent : "",
        backBtnDisabled : true,
        errors: [],
        results : "",
    },

The show variable is a computed property. We can see how it is defined below.

computed: {
        // a computed getter
        show : function(){
            if(this.currentCard == 1){
                return 'cardone';
            }else if( this.currentCard == 2 ){
                return 'cardtwo';
            }else if( this.currentCard == 3){
                return 'cardthree';
            }
        },
    }

So above we check to see which card we are on and return the name of the card to display.

When the forward button is pressed the currentCard variable is updated. The currentCard variable is instantiated at one. So the first view shows first.

    methods : {
        forward: function(){
            if(this.checkform() && this.currentCard  < this.cards){
                this.currentCard++;
            }
            if(this.currentCard == this.cards ){
                this.getFormData();
                console.log('get data');
            }
            this.buttonStatus();
        },
}

In the forward function we validate the form using the checkform function and then we see if the currentCard is less than all the cards. Once this is true we can increment the currentCard. This will allow the computed property show to return the next card to display.

The checkform function carries out validation on our wizard views. Part of this function is shown below. You can view the full file in the repository.

   checkform : function(){
            var status = true;
            this.errors = [];
            if(this.currentCard == '1'){
                if(this.name == ""){
                    this.errors.push("Name can't be empty");
                    status = false;
                }
                if(this.email == ""){
                    this.errors.push("Email can't be empty");
                    status = false;
                }
                if(!this.validEmail(this.email)){
                    this.errors.push("Email must be valid");
                    status = false;
                }
            }
}

The errors variables holds all our errors. We first clear it out. We must then check to see what view we are on and perform the correct validation for that view. If there is a validation error we can push our validation message to the errors array and set the status to false. The status is initially set as true so once false the validation errors will show on the form. The currentCard variable will also not be incremented so the form will stay in place.

Validation errors in form

The errors shown above are displayed using v-if binding on a div element. If the length of the array is greater than zero we display the errors in a list.

  <div v-if="errors.length"
                         style="background-color: indianred; color:white; border: 1px solid #ccc; padding:5px; margin-bottom:5px;">
                        <b>Please correct the following error(s):</b>
                        <ul>
                            <li v-for="error in errors"><span>{{ error }}</span></li>
                        </ul>
</div>

The forward button element is shown below.

<button v-if="currentCard <3" type="button" @click="forward()" class="btn btn-primary">Forward</button>

The @click attribute declares our forward method. The v-if binding checks to see if the currentCard is less than three. If currentCard is greater than or equal to three this element will disappear. Instead we will show a normal submit button that submits the form PHP style. Shown below.

<button v-if="currentCard ==3" class="btn btn-primary">Submit</button>

In order to get our form data – server side – we have to create a object from the variables we binded to the form. The getFormData function allows us to do this. We create a object from the the binded variables and stringify it. We then set it to the variable results.

getFormData: function(){
            var obj = {
                'name' : this.name,
                'email' : this.email,
                'contact' : this.contact,
                'postTitle' : this.postTitle,
                'content' : this.postContent
            };
            this.results = JSON.stringify(obj);
        }

The results variable is binded to a hidden input. When we reach on the summary view we run the getFormData function.

<input v-model="results" type="hidden" name="wizard">

The form data submitted can be accessed via the wizard attribute seen in the input above. Since our form posts the form we can access the data in PHP. This is shown below.

if(isset($_POST["wizard"]) && !empty($_POST["wizard"])){
    var_dump($_POST['wizard']);
}

You can use json_encode to get your data because the output of var_dump looks like below –

string(133) "{"name":"Wynton Franklin","email":"Franklin@gmai.com","contact":"343434","postTitle":"Happy Days","content":"This is a post content"}"

Feel free to review the repository to see the full code of this demo.

Summary

Some of the things we covered in this little wizard demo are :-

  • Submitting a Form using a wizard
  • Adding validation to forms
  • Hiding and showing different views

Again check out the repository and download the code to get a better understanding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s