Building a Simple Form Using Angular JS and Cygnite PHP Framework


In my previous article I shown you "Howto split large CSV into multiple pieces?”. Today I am writing about Angular JS with Cygnite Framework or You can say Angular JS with PHP. Creating a simple app using some Framework will be great instead using core php, since framework does couple of the job for us. While recently checking Angular Js I found it’s features are really awesome. Let me show you how to build registration form and save data into the mysql database.

Getting Started:

Setting Backend:

Let us install Cygnite Framework first and set configuration to do so. Simply run below command from your terminal to install Cygnite into your local system.

        composer create-project cygnite/cygnite-application cygnite –-prefer-dist

Set up your database connection inside configs/database.php.

For more details please follow  Cygnite website.

Create Table to Store Form Details-

 `name` varchar(100) NOT NULL,
 `password` varchar(16) NOT NULL,
 `email ` varchar(50) NOT NULL,
 `country` varchar(50) NOT NULL,
 `created_at` datetime DEFAULT NULL,

You may also use the power of Cygnite Framework Migration System to build table schema, which I prefer mostly.

Creating Application Controller:

Let us create a Controller to perform all backend operation. I have created AngularController inside Controllers directory and paste below code into it.

namespace Apps\Controllers;

use Cygnite\Application;
use Cygnite\Helpers\Url;
use Cygnite\Libraries\Form;
use Apps\Models\Registration;
use Cygnite\AbstractBaseController;

class AngularController extends AbstractBaseController
     * Your constructor.
     * @access public
    public function __construct()

     * Default method for your controller. Render angular registration page to user.
     * @access public
   public function indexAction()
       $form = $this->generateForm();

               'registration' => $form->getForm()

     * Save your form details to database
    public function registerAction()
       $registration = new Registration();
       $form = json_decode(file_get_contents("php://input"));

       if ($form->submit == 'true') {

           $registration->name = $form->name;
           $registration->password = $form->password;
           $registration->email = $form->email;
           $registration->country = $form->country;
           echo ($registration->save()) ? '1' :'0';

     * Build the form and return form object
     * @return mixed
    private function generateForm()

        return Form::instance(
           function ($form) {
               return $form = $form->open(
                       'role' => 'form',
                       'ng-submit' => 'submitForm()',
                       'class' => 'registration-form'
                   ->addElement('label', 'User Name', array(
                           'class' => 'control-label'
                   ->addElement('text', 'username' , array(
                           'ng-model' => 'name',
                           'placeholder'=> 'User Name',
                           'class' => 'form-control',
                           'ng-required' => 'true'
                   ->addElement('label', 'Password', array('class' => 'col-sm-2 control-label'))
                   ->addElement('password', 'password', array(
                           'ng-model' => 'password',
                           'placeholder'=> 'Password',
                           'class' => 'form-control',
                           'ng-required' => 'true'
                   ->addElement('label', 'Email', array('class' => 'col-sm-2 control-label'))
                   ->addElement('text', 'email', array(
                           'ng-model' => 'email',
                           'placeholder'=> 'Email',
                           'class' => 'form-control',
                           'ng-required' => 'true'))
                   ->addElement('label', 'Country', array('class' => 'col-sm-2 control-label'))
                   ->addElement('text', 'country', array(
                           'ng-model' => 'country',
                           'placeholder'=> 'Country',
                           'class' => 'form-control',
                           'ng-required' => 'true'))
                   ->addElement('submit', 'btnSubmit', array(
                           'value' => 'Register',
                           'class' => 'btn btn-primary'

}//End of your home controller

Creating Model:

Create a Registration model into models directory and paste below code.

namespace AppsModels;

use CygniteApplication;
use CygniteDatabaseSchema;
use CygniteDatabaseActiveRecord;

class Registration extends ActiveRecord

    //your database connection name
    protected $database = 'cygnite';

    protected $primaryKey = 'id';

    public function __construct()
}// End of the Regitration Model

Creating View Page:

Create a simple view page for our angular application. Your view page should be inside /views/angular/angular.view.php.

<!DOCTYPE html>
use Cygnite\Common\UrlManager\Url;
use Cygnite\AssetManager\Asset;
<html lang="en" > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" > <title>Learning Angular js With Cygnite PHP Framework </title> <link rel="shortcut icon" href="<?php echo Url::getBase(); ?>assets/img/cygnite/fevicon.png" > </link> </head> <body ng-app="MyRegistrationApp"> <div class="container"> <div class="container-body"> <!--PAGE TITLE--> <div class="page-header"> <h2>Cygnite Framework with Angular JS</h2> </div> <div id='registration-form' style="width:500px;margin-top:35px;float:left;" ng-controller='RegistrationController'> <!-- SHOW ERROR/SUCCESS MESSAGES --> <div class="alert alert-success"> <a href="javascript:void(0);" class="close" data-dismiss="alert">&times;</a> <span class="success" ng-repeat="msg in messages"> <strong>Thanks!</strong> {{ msg}} </span> </div> <div class="alert alert-error"> <a href="javascript:void(0);" class="close" data-dismiss="alert">&times;</a> <span class="error" ng-repeat="error in errors"><strong>Whoops!</strong> {{ error}} </span> </div> <!-- LOADING ICON --> <p class="text-center" ng-show="loading"><span class="fa fa-meh-o fa-5x fa-spin"></span></p> <!-- Render your Registration Form --> <?php echo $this->registration; ?> </div> <div style="clear:both;"></div> <div align="center"><a href=''>Powered By: (</a></div> </div> </div> <!-- Load your css files --> <?php echo Asset::style('assets/css/cygnite/style.css'); echo Asset::style('assets/css/cygnite/table.css'); echo Asset::style('assets/twitter/bootstrap/css/bootstrap-theme.min.css'); echo Asset::style('assets/twitter/bootstrap/css/bootstrap.min.css'); // Pick a theme, load the plugin & initialize plugin echo Asset::style('assets/js/tablesorter/css/theme.default.css'); // Load your javascript files and Angular Module, Controllers echo Assets::addScript('assets/js/cygnite/jquery.js'); ?> <script type="text/javascript" src="" ></script> <script type="text/javascript"> var base_path = "<?php echo Url::getBase(); ?>"; </script> <?php echo Asset::script('assets/js/angular/app.js'); echo Asset::script('assets/js/angular/controllers/registrationCtrl.js'); ?> <style type="text/css"> .alert-success {display: none;} .alert-error {display: none;color: #000 !important; background-color: #f2dede; border-color: #eed3d7;} .registration-form {width:500px;margin-top:35px;float:left;} .btn {margin-top:15px;} </style> </body> </html>
That’s all we are done with the Cygnite Framework part. Let us move to frontend with angular js to make our application to work.

Frontend Angular Application

Let’s have a look at the application structure in assets folder. 

- assets/
----- js/
---------- controllers // where our angular controllers exists
--------------- registrationCtrl.js 
---------- app.js

Creating Angular Controller:

Let us create a controller called registrationsCtrl.js inside controllers. Controller where we write most of the logic of angular application. You can see our controller has anonymous submitForm function to handle the submit form and bind values to view page.

 app.controller("RegistrationController", function($scope,  $http){

    $scope.errors = [];
    $scope.messages = [];
    var queue = [];

 $scope.submitForm = function() {
        $scope.loading = true;

        var dataArray = {
            'submit': 'true',
            'name': $,
            'password': $scope.password,
            'email': $,
            'country': $

        $'angular/register', dataArray
        ).success(function(data, status, headers, config) {

            $scope.loading = false;

            if (data == '1') {
                // if successful, bind success message to message
                $scope.messages.push("You have Registered Successfully!");
            } else {
                // if not successful, bind errors to error variables
                $scope.errors.push("Error Occured while saving into Database");
        }).error(function(data, status) { // called asynchronously if an error occurs
            // or server returns response with an error status.
            $scope.loading = false;

Creating App.js to link with Application:

You can see we have created angular controller and also cygnite view page, now let us link everything together with app.js using ng-app and ng-controller

Paste below code into your /assets/js/angular/app.js.

  var app = angular.module('MyRegistrationApp',[]);

That’s it! We are done. Go to your browser http://localhost/cygnite/angular/ and hit enter, you will see the page below.

Fill all details on our registration page, information will be saved into database and you will find the below screen.


Hope this simple tutorial gives you overview of creating application using Cygnite Framework and Angular js. You also can add much more features to your app (like editing, displaying data into grid etc.). If you find this article please don’t forget to give a small like, give comments, also share with your others. Keep visiting for new posts. 

No comments:

Post a Comment

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 All rights reserved. Powered By- Sanjoy Dey Productions