Building a Simple Form Using Angular JS and Cygnite PHP Framework






Introduction:

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-


CREATE TABLE IF NOT EXISTS `registration` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5;




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()
    {
        parent::__construct();
    }

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

       $this->render('angular')->with(
           array(
               '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(
                   'registration',
                   array(
                       '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'
                       )
                   )
                   ->close()
                   ->createForm();
           }
       );
   }

}//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()
    {
        parent::__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>
<?php
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='http://www.appsntech.com'>Powered By: (www.appsntech.com)</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="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" ></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/
-------angular/
---------- 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': $scope.name,
            'password': $scope.password,
            'email': $scope.email,
            'country': $scope.country
        };


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

            $scope.loading = false;

            if (data == '1') {
                $(".alert-success").show();
                // if successful, bind success message to message
                $scope.messages.push("You have Registered Successfully!");
            } else {
                $(".alert-error").show();
                // 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;
            $scope.errors.push(status);
            console.log(data);
        });
    }
});



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.





Conclusion:

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. 





How to split Large CSV file into multiple pieces?

In my previous article I wrote about “Latest PHP frameworks in 2014?”. Today I am going to share with you another real time experience of mine, which I faced couple of days back.  

Recently I came across the task where I need to import large csv records into mysql database. It’s quite tough because your phpmyadmin will not allow you to import large file. That csv contains around 10 million records. You may think don't I use mysql LOADINFILE ? Due to some restriction I avoided and choosed my next option as csv spliting. First thing I tried to open that file, but it shows “File not loaded completely”. The reason you get this error because excel can only handle 65,536 lines per sheet and it will not open remaining records.  I even tried to import it directly via phpmyadmin but maximum time limit exceeded, then next thing I increased php max execution time but it was taking much time to process that file.

So you can solve this problem simply by splitting the large csv file into smaller fragments. By doing that script will consume time limit.

You can simply download FXFisherman’s CSV Spliter program and run the program in your windows system. Installation no longer required.

Once you run you will see this screen below-



              Now you may browse your csv file which you want to split, specify how many numbers of lines you want to have per csv and also another way you can simply specify max number of pieces. Now simply click “Split Now!”.

It will start splitting your csv into number of pieces. When process is completed you should see screen like below.
                

Now you can find a folder contains chunks of csv file into it, in the same directory. Thank God!  Saved My Day. 

I was able to import 3 millions of records at the end of the day.

Do you have any other better or faster way to accomplish this job?

Hope this article is useful, if so please don’t forget to give a small like or share with your friends. Keep visiting for new posts and also if you find my articles are useful you may join us simply following us.
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 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions