Yii2 custom pagination for gridview

Pagination is the process of dividing a document into discrete pages, either electronic pages or printed pages.In this article we discussed the Yii2 pagination how we used the pagination under yii2 framework.

There are two ways we can use the pagination in Yii2.

  • Simple Pagination
  • Custom Pagination



Add this function in your controller file.

function actionIndex()
{
    $query = User::find()->where(['status' => 1]);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    $models = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
    ]);
}

Now come to view part index.php file.

foreach ($models as $model) {
    // display $model here
}
// display pagination
echo LinkPager::widget([
    'pagination' => $pages,
]);

Custom Pagination :

LinkPager is handling the pagination link with properties. Here we customized the link property.
so i have create CustomPagination class in app/components folder and set namespace as app/components.We removed the link and added onclick attribute in every pagination link.



<?php
namespace app\components;

use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\base\Widget;
use yii\data\Pagination;

class CustomPagination  extends \yii\widgets\LinkPager
{
    public function init()
    {
        parent::init();
    }

    public function run()
    {
        parent::run();
    }

    protected function renderPageButton($label, $page, $class, $disabled, $active)
    {
        $options = ['class' => $class === '' ? null : $class];
        if ($active) {
            Html::addCssClass($options, $this->activePageCssClass);
        }
        if ($disabled) {
            Html::addCssClass($options, $this->disabledPageCssClass);

            return Html::tag('li', Html::tag('span', $label), $options);
        }
        $linkOptions = $this->linkOptions;
        $linkOptions['data-page'] = $page;
        $linkOptions['onclick']='submit_form('.$page.')';

        return Html::tag('li', Html::a($label, '#pagination', $linkOptions), $options);
    }
}

Now in Controller.php .

public function index(){
    $query = Tablereport::find();
    $countQuery = clone $query;
    
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
     return $this->render('GridView', [
         'dataProvider' => $dataProvider,
         'pages' => $pages,
    ]);
}

GridView.php
Using 'layout' properties, we can remove the basic link pager.

<?php
use yii\helpers\Html;
use yii\grid\GridView;
use app\components\CustomPagination;
?>
<div class="report-index">
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
         'layout' => "{summary}\n{items}",
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'report_name',
            'report_table',
            'report_query:ntext',
            'created_on',
            // 'created_by',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

    <div id="custom-pagination">
        <?php
            echo CustomPagination::widget([
                'pagination' => $pages,
            ]);
        ?>
    </div>
</div>

How to redirect non Whitelisted IPs in NGINX

We are using the geo module for NGINX to allow specific IPs through,  and redirect all others to a page letting them know that access has been restricted and that they don't have access. This was done using Ubuntu 16.04, but should be similar for other linux distros.

Steps:

You have to install NGINX first.

sudo apt install nginx -y

Now create a file for single configuaration that has the IPs in it that all the site configs will include.

sudo vim /etc/nginx/whitelisted-ips.conf
geo $bad_user {
    default 1;

    # My Home IP
    192.168.1.1/22 0;

    # My Workspace IP
    192.168.1.2/22 0;
}

Create a configuration for the website you wish to filter for.

sudo vim /etc/nginx/sites-enabled/mywebsite.com;

include /etc/nginx/whitelisted-ips.conf

server {
    listen 80;

    # order of specify is important if allowing aliases
    server_name mywebsite.com;

    access_log /var/log/nginx/mywebsite.com-access.log;

    location / {
        if ($bad_user) {
            rewrite ^ http://myother.site.com/access-restricted-landing-page;
        }

        # include the default proxy_params conf in order 
        # to set headers for proxying.
        include /etc/nginx/proxy_params;

        # Send the user off to the backend server. 
        # They will only get here if they are whitelisted.
        proxy_pass http://xxx.xxx.xxx.xxx;
    }
}

Now test your configurations by running:

sudo nginx -t

If it gives you the all clear, have nginx use the configuration with:

sudo nginx -s reload

Now access the backend webserver (http://xxx.xxx.xxx.xxx in this case) is not accessible by the user just going to the IP, or if the user was to falsify their own DNS to go to that IP.The best way to do this is probably to have it's firewall only accept connections from the proxy.

how to install ansible in ubuntu

Ansible is an open source, powerful automation software for configuring, managing and deploying software applications on the nodes without any downtime just by using SSH. This is the server that should act as the "controller" of other servers. You do not need to install ansible on the "slaves" that get controlled.


Native Package System
sudo apt update && sudo apt install ansible -y

Install from PPA
This will install ansible version 2.1.2.0.

sudo apt-get install software-properties-common python-software-properties -y
sudo add-apt-repository ppa:ansible/ansible -y
sudo apt-get update && sudo apt-get install ansible -y


RabbitMQ deployment With Docker

You can use to deploy your own RabbitMQ server using docker. There are several ways to configure your deployment, but this is a generic method to configure RabbitMQ in docker.

  • Deploy with the web interface to manage your server.
  • Specify a username and password for managing the server.
  • Use a volume to keep state across containers being created/destroyed.
  • Uses port 80 for the web interface so that you can just go to the hostname in your browser without having to enter a port number.

Server Requirements : 
  • 512 MB of RAM
  • 1 vCPU
#!/bin/bash

# Settings
CONTAINER_NAME="rabbitmq-container"
DEFAULT_USER="root"
DEFAULT_PASSWORD="yourpassword"
CLUSTER_COOKIE="random"
HOSTNAME="rabbitmq.yourdomain.com"

# Don't change below this line.
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
docker kill $CONTAINER_NAME
docker rm $CONTAINER_NAME

docker run -d \
--restart=always \
--hostname $HOSTNAME \
--name $CONTAINER_NAME \
-p 80:15672 \
-p 4369:4369 \
-p 5671:5671 \
-p 5672:5672 \
-p 15671:15671 \
-p 25672:25672 \
-e RABBITMQ_ERLANG_COOKIE="$CLUSTER_COOKIE" \
-e RABBITMQ_DEFAULT_USER="$DEFAULT_USER" \
-e RABBITMQ_DEFAULT_PASS="$DEFAULT_PASSWORD" \
-v $DIR/rabbitmq-state:/var/lib/rabbitmq \
rabbitmq:3-management



How to restart ubuntu gui.

Sometime my GUI locks up and becomes unresponsive.This is usually shown by something like compiz eating 100% CPU usage in htop when I SSH in.

The easiest way to resolve this is to run this command to restart the lightdm service which handles the GUI.Note that you will be taken back to the login screen.


sudo service lightdm restart


Docker - Login into new TTY with a Running Container

Sometime we need to access the container from another shell in order to run some tail -f log/* or examine some files. so this post will help you to run a another shell with same container id.

You can run a new tty using docker exec -it [container-id] bash command.

To make life easier, I created the script below and placed it at /usr/bin/docker-tty.

#!/bin/bash 

EXPECTED_NUM_ARGS=1;

if [ "$#" -ne $EXPECTED_NUM_ARGS ]; then
    # user didn't specify which container ID, assume the latest one
    CONTAINER_ID=`/usr/bin/docker ps -q --no-trunc | /bin/sed -n 1p`
    /usr/bin/docker exec -it $CONTAINER_ID env TERM=xterm bash
else
    # enter the container the user specified
    /usr/bin/docker exec -it $1 env TERM=xterm bash
fi

Now make it executeable:

sudo chmod +x /usr/bin/docker-tty

Now you can just run docker-tty $CONTAINER_ID to enter into new tty. but if you want to enter the last container you spawned.so you run the command docker-tty without having to lookup the id.

Introducing Laravel Horizon dashboard for queue

Laravel Horizon is an open source software which turbo charges Laravel Redis queues with a beautiful dashboard and code-driven configuration system.The Horizon dashboard is a single page application which is build in using Vue.JS. It provide real-time insights into queue workloads, failed jobs, recent jobs, job retries, throughput and runtime metrics, and process counts.
and it’s totally open source and free for entire Laravel community.


According to Taylor Otwell:

“I built Horizon to scratch my own itch. I need deep insight into my queue throughput, performance, wait times, failures. And, when a customer has a problem, Horizon allows me to quickly find the job that failed.”


Read here : medium.com

Implementing authentication security token in symfony

Symfony provide a guard authentication bundle in which with API keys we handle the authentication responses and user credentials.you want to apply token based authentication system in Symfony and authenticate users through an API key. In this article i will show you how can you work with Guard and authenticate users via API tokens.

symfony authentication security token



1. Create User class & Provider class.

Create a user entity class which implements UserInterface and user provider. For authentication it depends on UserProvider when user submit the information the provider values are checked and further verification of password takes place.

User Entity : 

<?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**

* @ORM\Entity

* @ORM\Table(name="user")

*/

class User implements UserInterface

{

   /**

    * @ORM\Id

    * @ORM\GeneratedValue

    * @ORM\Column(type="integer")

    */

   private $id;

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $username;

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $email;

   /**

    * @ORM\Column(type="string")

    */

   private $password;

   /**

    * @ORM\Column(type="json_array")

    */

   private $roles = array();

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $apiToken;

   public function getId()

   {

       return $this->id;

   }

   public function getUsername()

   {

       return $this->username;

   }

   public function setUsername($username)

   {

       $this->username = $username;

   }

   public function getEmail()

   {

       return $this->email;

   }

   public function setEmail($email)

   {

       $this->email = $email;

   }

   public function getPassword()

   {

       return $this->password;

   }

   public function setPassword($password)

   {

       $this->password = $password;

   }

   /**

    * Returns the roles or permissions granted to the user for security.

    */

   public function getRoles()

   {
       $roles = $this->roles;

       // guarantees that a user always has at least one role for security

       if (empty($roles)) {

           $roles[] = 'ROLE_USER';

       }

       return array_unique($roles);

   }

   public function setRoles($roles)

   {
       $this->roles = $roles;

   }

   /**

    * Returns the salt that was originally used to encode the password.

    */

   public function getSalt()

   {
       return;

   }

   /**

    * Removes sensitive data from the user.

    */

   public function eraseCredentials()

   {

       // if you had a plainPassword property, you'd nullify it here

       // $this->plainPassword = null;

   }

   /**

    * @param string $apiToken

    */

   public function setApiToken($apiToken)

   {

       $this->apiToken = $apiToken;

   }

}


2. You need to register the provider in security.yml

providers:

       api_key_user_provider:

           entity:

               class: AppBundle:User

               property: apikey


3. Now you need to install Guard Bundle.

Guard provides different layers of authentication.It first introduced in symfony 2.8 and after that it’s now become a part of symfony core. With Guard authentication process is handled by only one class: an Authenticator.

You can also install the Guard with composer :

composer require symfony/security-guard

4. Create an Authenticator Class.

Create a new authenticator class which implements GuardAuthenticatorInterface extends the AbstractGuardAuthenticator.This class will read the api token in header request and find the respective user.

This class will read the api token in header request and find the respective user.

Create a new file: (src/AppBundle/Security/TokenAuthenticator.php)

<?php
namespace AppBundle\Security;



use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;


class TokenAuthenticator extends AbstractGuardAuthenticator

{

   /**
    * Called on every request. Return whatever credentials you want to
    * be passed to getUser(). Returning null will cause this authenticator
    * to be skipped.
    */

   public function getCredentials(Request $request)

   {
       if (!$token = $request->headers->get('X-AUTH-TOKEN')) {

           // No token?

           $token = null;

       }

       // What you return here will be passed to getUser() as $credentials

       return array(

           'token' => $token,

       );

   }

   public function getUser($credentials, UserProviderInterface $userProvider)

   {
       $apikey = $credentials['token'];

       if (null === $apikey) {

           return;

       }
       // if null, authentication will fail

       // if a User object, checkCredentials() is called

       return $userProvider->loadUserByUsername($apikey);

   }

   public function checkCredentials($credentials, UserInterface $user)

   {
       // check credentials - e.g. make sure the password is valid

       // no credential check is needed in this case



       // return true to cause authentication success

       return true;

   }

   public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)

   {

       // on success, let the request continue

       return null;

   }

   public function onAuthenticationFailure(Request $request, AuthenticationException $exception)

   {

       $data = array(

           'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

           // or to translate this message

           // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())

       );

       return new JsonResponse($data, Response::HTTP_FORBIDDEN);

   }

   /**

    * Called when authentication is needed, but it's not sent

    */

   public function start(Request $request, AuthenticationException $authException = null)

   {
       $data = array(

           // you might translate this message

           'message' => 'Authentication Required'

       );

       return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);

   }

   public function supportsRememberMe()

   {
       return false;

   }

}

You can read the whole method of guard here

5. Configuring The Authenticator.

To configure the authenticator I need to update the firewall:

security:
   # ...
   firewalls:
       # ...
       main:
           anonymous: ~
           logout: ~
           guard:
               authenticators:
                   - AppBundle\Security\TokenAuthenticator



After that register the authenticator as a service in service.yml:

services:
   api_key_authenticator:
       class: AppBundle\Security\TokenAuthenticator
       arguments: ["@router"]


Everthing is done now check the response in url.

curl -H "X-AUTH-TOKEN: username" http://yourappurl.com

How to use template in angular component

Angular template is a mix of custom elements and HTML.In this post i will show you how we used the it inline and external template.

There are two ways we can add template in our component.

1. Inline Templates : Inline templates are directly in the component decorator. Template literals with back-ticks allow multi-line strings.


import { Component } from '@angular/core';

@Component({
    selector: 'app-inline-template-example',
    template: `
        <h2>Inline Template</h2>
        <p>
            Here your text
        </p>`
})
export class InlineTemplateComponent {}

2. External Template : External templates define the HTML in a separate file and reference the file in templateUrl.


import { Component } from '@angular/core';

@Component({
    selector: 'app-external-template-example',
    templateUrl: 'external.html'
})
export class ExternalTemplateComponent {}

You can also follow the official style guide of angular html template.

Angular 5 Template Expressions and Interpolation

Interpolation use the {{ expression }} to render the value to the template.Interpolation uses template expressions in double curly braces to display data from the component class and template reference variables.

Interpolation with Curly Braces :

{{ }} contain template expressions which allow us to read object values from component properties.Double curly braces are similar to javascript and include feature such as ternery operator,concatenation and airthmetic.


import { Component } from '@angular/core';

@Component({
  selector: 'app-employee',
  template: `
    <h2>{{heading}}</h2>
    <p>
      Name: {{employee.sex === 'm' ? 'Mr' : 'Ms'}}
      {{employee.name.first + ' ' + employee.name.surname}}
    </p>`
})
export class EmployeeComponent {

  heading = 'Employee Details';

  employee: any = {
    name: {
      first: 'John',
      surname: 'Doe'
    },
    sex: 'm'
  };
}

How to install symfony 4 php framework

Symfony 4 was released in last year so it introducing a new workflow based on the tool "Symfony Flex", that replaces and improves the Symfony Installer and the Symfony Standard Edition, it enables a distribution composition based project instead of inheritance. According to Symfony developers, this new way to work is easier, more flexible, and even powerful.

Install Symfony4 in ubuntu


The first thing that you need to know is that as usual with a major release of Symfony, the project structure has changed. 

Bundles are now loaded in the /config/bundles.php file instead of the Kernel. Symfony 4 is using the  environment variables file instead of app/config/parameters.yml

There are many changes comparing it with Symfony 3 but you can easily upgrade your symfony 3 application to 4 follow the url. here

Lets create a hello world using symfony framework.

Requirements : 
  • Composer should be installed in your machine.
  • PHP >= 7.1: Symfony requires at least this version of PHP to work.
steps to create a project:

To create your first Symfony 4 project, following the standard documentation, we won't use the Symfony Installer or the standard edition, but with the flex version that can be downloaded from the symfony/skeleton package. This package contains the basic structure for any Symfony 4 based project and can be installed using the following command:


SymfonyWorld is your project name you can change it according to your project.


composer create-project symfony/skeleton SymfonyWorld

Switch to directory :

cd SymfonyWorld

Run the command.
php bin/console server:run

Now navigate to the browser and open http://127.0.0.1:8000 and check the hello from the symfony.







String interpolation in angular 5

In this lesson i will show you how to change the content of your component dynamically using angular.

String interpolation in angular 5


Note : when we are mention angular.js it means we are talking about angular 1 and angular means the new version of angular which is 2 and now 5.

After installing angular 5 in your machine lets create a new component.


ng generate component server

or 

ng g c server

it will generate the file in you src/app/server directory.

Now open server.component.ts

In this file we will change the serverId and serverStatus dynamically . Here i take these argument value static but it change dynamically also.

here we create the properties by specifying the types using TypeScript in this way.

    serverId : number = 10;
    serverStatus : string = 'offline';


import { Component } from '@angular/core';

@Component({
    selector:'app-server',
    templateUrl:'./server.component.html',
})
export class ServerComponent {
    serverId : number = 10;
    serverStatus : string = 'offline';

    getServerStatus(){
        return this.serverStatus;
    }

}

In server.component.html, we will be using double curly braces {{}} which will enable us to type TS expressions in between. {{}} is used for the string interpolation in angular.

open the server.component.html

<p>The {{ 'server' }} component id is {{ serverId }} and status {{ getServerStatus() }}.</p>

Now string interpolations display the value {{ 'server' }} and {{ serverId }} . we can use {{ 'server' }} or without '' {{ server }}.

The next thing is to add the component tag in your main app.component.html file.


<app-server></app-server> 

Now Run your app and navigate to the browser.

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular