sirin k

Nintriva

1 note

How to Write & use a custom Component in Yii2.0

This is a simple example in Yii2.0 to understand how you can write a custom component and use it inside your app.(basic template)

Step1:Make a folder named “components” in your project root folder.

step2:
write your custom component inside components folder eg:MyComponent.php

namespace app\components;
 
 
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
 
class MyComponent extends Component
{
 public function welcome()
 {
  echo "Hello..Welcome to MyComponent";
 }
 
}

Step3:Add your component inside the config/web.php file

eg:

'components' => [
 
         'mycomponent' => [
 
            'class' => 'app\components\MyComponent',
 
            ],
           ]

Step4:You are done!. Now you can use your component method “welcome” inside any of your app controller actions. eg:controllers/TestController.php

namespace app\controllers;
use Yii;
 
class TestController extends \yii\web\Controller
{
    public function actionWelcome()
    {
       Yii::$app->mycomponent->welcome();
    }
 
}

Thanks. happy coding… Sirin K

Nintriva

www.nintriva.com

0 notes

Yii Module specific URL rules

Sometimes ,We may have a set of URL Re-Writing Rules specifically for our modules..To achieve this follow the below Steps.

Step1:Add the below code into config/main.php

<code>

'onBeginRequest'=>function($event){
                    $route=Yii::app()->getRequest()->getPathInfo();
                    $module=substr($route,0,strpos($route,’/’));
                      
                       
                    if(Yii::app()->hasModule($module))
                    {
                      
                      $module=Yii::app()->getModule($module);
                      
                      if(isset($module->urlRules))
                      {
                        
                        $urlManager=Yii::app()->getUrlManager();
                        $urlManager->addRules($module->urlRules);
                      }
                    }
                    
                    return true;
                      },

<code>

Step2:Add a public varaible “$urlRules” inside your module file.

eg:

 <code>

  public $urlRules=array(
                        ‘api/<controller:\w+>/<id:\d+>’=>’api/<controller>/view’,
                ’api/<controller:\w+>/<action:\w+>/<id:\d+>’=>’api/<controller>/<action>’,
                ’api/<controller:\w+>/<action:\w+>’=>’api/<controller>/<action>’,
        
         );

  </code>

Thats it. you are done..

happy coding

0 notes

Implement pagination in your AngularJs app with Sails.Js backend by following just simple 8 Steps

Its very simple in Angular to add a pagination your Grid view..by following the below simple steps.

Step1:Add AngularUI js script file  into your html file.ie

         <script src=”http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js”></script>

Step2:Add it as an angular module.
         eg:

         var app = angular.module(‘app’, [‘ui.bootstrap’]);

Step3: Add the below code at the bottom of your GridView

         <pagination total-items=”totalItems” items-per-page=”items_per_page” ng-model=”currentPage” ng-change=”pageChanged()”></pagination>

Step4:Now set up 2 variables(1.items_per_page,2.currentPage) in your main controller.

       eg:

       function UserCtrl($scope,$http,$API,$resource,$location,$log) {

            $scope.items_per_page = 10;
            $scope.currentPage = 1;

       }

Step5:Add a pageChanged listener into your controller

       eg:

       function UserCtrl($scope,$http,$API,$resource,$location,$log) {

            $scope.items_per_page = 10;
            $scope.currentPage = 1;

            $scope.pageChanged = function() {
           
                    $API.index(“user”,$scope); /* See step4 to get see the defenition  */
    
          };

       }

Step6.define your $API factory to make an API call to your Sails.Js Action which returns the paginated result based on 2 arguments(1.page,2.limit)

        eg:
    app.factory(‘$API’, function($http) {
    
            var host = “http://localhost:1337/”;
            
        return {
           
              index:function(model,$scope) {
              
                      var url=host+model+”/index?page=”+$scope.currentPage+”&limit=”+$scope.items_per_page;
                      
                      
                        $http({method: ‘GET’, url: url}).
                  success(function(data, status, headers, config) {
                  
                    $scope.users=data;
                  
                  }).
                  error(function(data, status, headers, config) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                  });
                    
              },
                       count:function(model,$scope) {
              
                      var url=host+model+”/count”;
                       $http({method: ‘GET’, url: url}).
                  success(function(data, status, headers, config) {
                  
                   $scope.totalItems=data.count;
              
                  
                  }).
                  error(function(data, status, headers, config) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                  });
                      
                
              },              
               };    
    });

Step7:Alter your Controller like below
               function UserCtrl($scope,$http,$API,$resource,$location,$log) {

            $scope.items_per_page = 10;
            $scope.currentPage = 1;

            $API.index(“user”,$scope);
            $API.count(“user”,$scope);

          

            $scope.pageChanged = function() {
           
                    $API.index(“user”,$scope); /* See step4 to get see the defenition  */
    
            };

         }
Just added 2 API calls. one is to get the data’s from the API and another to get the total record counts.

Step8:Add 2 Actions in your sails.js controller. like below
<code>
 count:function (req, res) {
    
           

          User.count().done(function(error,count){
        
        
        //res.header(“Access-Control-Allow-Origin:*”);
         return res.json({
      
    
              count: count,
              
            });
      });
 
   },
     index:function (req, res) {
    
           var page=req.param(“page”,null);
       var limit=req.param(“limit”,null);

      if(page&&limit)
      {
            User.find().paginate({page:page,limit:limit})
      
         .done(function(error,data){
        
         return res.json(data);
        });
      }
      else
          return res.json([ ]);
 
   },
</code>

In the above code the action index will work iff you pass the page & limit paramters.(eg:1&10) and action count will return the total no.of records in your table.
Hope this may help Someone.

Sirin K
Nintriva

0 notes

Accepting Cross Domain Requests in Sails.Js Builtin Rest API & Custom controller actions

In Sails.Js By Default the cross-domain API calls are restricted but you can enable/accept JSONP calls by changing jsonp: true in config/controllers.js file.Now you are free to make the built in Sails.js API calls from any other server to your Sails.js App.

Now you have solved this issue for the Sails.JS BuiltIn REST API but you still gonna face this same problem for your custom controller actions written inside Sails.Js But you can easily resolve this by editing  allRoutes to “true”(by default it will be false) in file:  config/core.js

This change is gonna affect for all of your controller actions in your sails.js app and if in case you dont want that instead just to allow cross domain requests  for one or two actions you achieve that by overriding this settings inside file config/routes.js like below

   ’/user/count’:{
                         controller:’UserController’,
                         action:’count’,
                            cors: {
                                       origin: ‘*’    
                                    }
 
                        }

In the above example i have given the origin:’*’ that means for any other domains but you specify one or more domains as comma separated.

Note:JSONP not gonna work for the above change too but normal AJAX call from your Javascript will work for sure.

eg: origin: "http://sailsjs.org, http://sailsjs.com",

I would recommend a wiki here:https://github.com/balderdashy/sails-docs/blob/bc148104378f1ad590a69220c25f60fe41a59790/config.cors.md about core.js in sailsJS for more details..

eg:Cross Domain calls:

Normal http call: 

 $http({method: ‘GET’, url: ‘http://localhost:1337/user/count?callback=JSON_CALLBACK’}).
              success(function(data, status, headers, config) {
                alert(angular.toJson(data));
            // this callback will be called asynchronously
            // when the response is available
              }).
              error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
              });

JSONP call:$http.jsonp(url,{
                                  method:’GET’
                                })
                .success(function(data){
               
                   
                })
                .error(function(){
                 
                
                 });

Hope this may Help Someone.