Thursday 22 August 2019

Setup VueJS in Laravel

Setup VueJS in Laravel

1. You will need to install javascript dependencies by running the following command on your terminal.
     npm install

2. Install some vue libraries that we will need. Run the following command on your terminal.
   npm install  vue-axios —save
   npm install  vue-router  —save
   npm install  vue-loader  —save
   npm install  vue-template-compiler —save


3. Create a file named App.vue in resources/assets/js and put the following content in the file.
   
    <template>
    <div class="panel panel-default">
        <div class="panel-heading">
            <nav>
                <ul class="list-inline">
                    <li>
                        <router-link :to="{ name: 'home' }">Home</router-link>
                    </li>
                    <li class="pull-right">
                        <router-link :to="{ name: 'about' }">About</router-link>
                    </li>                    <li class="pull-right">
                        <router-link :to="{ name: 'contact' }">Contact</router-link>
                    </li>
                </ul>
            </nav>
        </div>
        <div class="panel-body">
            <router-view></router-view>
        </div>
    </div>
  </template>

 
 4. Create another files named Home.vue, About.vue, Contact.vue but now in resources/assets/js/components and put the following code in it respective.
        Home.vue
       
        <template>
            <h1>Laravel 5 Vue Home Page</h1>
        </template>
       
       
        About.vue
       
        <template>
            <h1>About</h1>
        </template>

       
        Contact.vue
       
        <template>
            <h1>Contact</h1>
        </template>


5. Then replace the content of the resouces/assets/js/app.js file with the code below.
        import Vue from 'vue';
        import VueRouter from 'vue-router';
        import App from './App.vue';
        import Home from './components/Home.vue';
        import Home from './components/About.vue';
        import Home from './components/Contact.vue';

        Vue.use(VueRouter);

        const router = new VueRouter({
            routes: [
                {
                    path: '/',
                    name: 'home',
                    component: Home
                },
                {
                    path: '/about',
                    name: 'about',
                    component: About
                },
                {
                    path: '/contact',
                    name: 'contact',
                    component: Contact
                },
            ]
        });

        new Vue({
            el: '#app',
            router: router,
            render: app => app(App)
        });
       

6. Next replace the content of the resources/views/welcome.blade.php template file with the code below.
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="csrf-token" content="{{ csrf_token() }}">
                <title>Laravel</title>

                <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

            </head>
            <body>
                <div class="container">
                    <div id="app"></div>
                </div>
                <script src="/js/app.js"></script>
            </body>
            </html>

           
7. Now run the following command on your terminal.
   npm run dev    
   npm run watch

Sunday 9 October 2016

Yii Grid View Custom Action Link

             [
        'class' => 'yii\grid\ActionColumn',
        'template' => '{view} {update} {delete}',
        'buttons' => [
                'view' => function ($url,$model) {
                        return Html::a(
                                '<span class="btn btn-success btn-rounded btn-xs">View</span>',
                                $url);
                },
                'update' => function ($url,$model,$key) {
                                return Html::a('<span class="btn btn-primary btn-rounded btn-xs">Edit</span>', $url);
                },
                          'delete' => function ($url,$model,$key) {
                                return Html::a('<span class="btn btn-danger btn-rounded btn-xs">Delete</span>', $url, [ 'data' => [
                'confirm' => "Are you sure you want to delete profile?",
                'method' => 'post',
            ],]);
                },
        ],
],

Wednesday 28 September 2016

Allow Access to Specific User role in controller in Yii Framework

Set On Coltroller   


 public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],     'access' => [
                        'class' => \yii\filters\AccessControl::className(),
                        'only' => ['index','create','update','view'],
                        'rules' => [
                            // allow authenticated users
                            [
                                'allow' => true,
                                'roles' => ['@'],
                                'matchCallback' => function ($rule, $action) {
                            if (Yii::$app->user->identity->role==1) {
                                return true;
                            }
                            return false;
                                }
                            ],
                            // everything else is denied
                        ],
                    ],
        ];
    }

Tuesday 27 September 2016

Server Side datatable in Yii Framework

Step 1  view set helper

use yii\helpers\Html;
use yii\helpers\Url;

Step 2 Table design in view 

   <table id="dtofficer" class="table table-striped table-bordered" width="100%" cellspacing="0">
   
        <thead>
            <tr>
                <th>Sr. No.</th>
                <th> Employee Name</th>
                <th> Employee Salary</th>
                <th> Employee Age</th>
           
                <th>Action</th>
            </tr>
        </thead>
 
        <tfoot>
           
    </table>

Step 3 Call Script in view

<?php

$this->registerCssFile(Yii::$app->urlManager->baseUrl . '/css/dk/dataTables.bootstrap.css');
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/css/dk/jquery.dataTables.min.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/css/dk/dataTables.bootstrap.min.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/css/dk/datatables.responsive.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/css/dk/fnReloadAjax.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
$urlOne = Url::to(['site/officerdata']);
$script = <<< JS
    $(document).ready(function() {
       
        var dataTable = $('#dtofficer').DataTable({
        "processing": true,
        "serverSide": true,
       
        "ajax": {
            url: "$urlOne",
            type: "post",
            error: function()
            {
               alert('error');
            }
         
        }
    });
       
        $('#dtofficer tbody').on( 'click', '.selrow', function () {
            $("#fmfirereport-fire_detail_id").val($(this).text());
            });
    });
JS;
$this->registerJs($script);
?>

Step -4 Controller

public function actionOfficerdata() {
        
        $requestData = $_REQUEST;
        
        $columns = array(
            0 => 'id',
            1 => 'employee_name',
            2 => 'employee_salary',
            3 => 'employee_age'
             );
        
       $sql = "SELECT  * from employee where 1=1";
       
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        
        $totalData = count($data);
        $totalFiltered = $totalData;
     
        // $sql.="WHERE 1=1";
        
        if (!empty($requestData['search']['value']))
        {
            $sql.=" AND ( employee_name LIKE '" . $requestData['search']['value'] . "%' ";
            $sql.=" OR employee_salary LIKE '" . $requestData['search']['value'] . "%'";
            $sql.=" OR employee_age LIKE '" . $requestData['search']['value'] . "%')";
          
        }
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        $totalFiltered = count($data);
       
        $sql.=" ORDER BY " . $columns[$requestData['order'][0]['column']] . "   " . $requestData['order'][0]['dir'] . "  LIMIT " . $requestData['start'] . " ," . 
        $requestData['length'] . "   ";
       
        $result = Yii::$app->db->createCommand($sql)->queryAll();
       
        $data = array();
        $i=1;
        
        foreach ($result as $key => $row)
        {
          
            $nestedData = array();
            $url = Url::to(['employee/update', 'id' => $row['id']]);
            $nestedData[] = $i;
            $nestedData[] = $row["employee_name"];
            $nestedData[] = $row["employee_salary"];
            $nestedData[] = $row["employee_age"];
            $nestedData[] = '<a href="'.$url.'"><span class="glyphicon glyphicon-pencil"></span></a>';
             $data[] = $nestedData;
             $i++;
        }
        
        $json_data = array(
            "draw" => intval($requestData['draw']), 
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data   // total data array
        );

        echo json_encode($json_data);
    }

Monday 19 September 2016

Yii2 Create Dropdown select options with custom Query

         $gisv = Yii::$app->db->createCommand("SELECT u.id as id, CONCAT_WS(' ',dep.dep_name,des.des_name, name) as name FROM `user` as u inner join mst_department dep on dep.d_id=u.department_id inner join mst_designation des on des.ds_id=u.designation_id  where u.role=3");
                                   
  $geb = $gisv->queryAll();
                                 
    $keuzeData = ArrayHelper::map($geb, 'id', 'name');
                       
              echo $form->field($model, 'employee_id')->dropDownList($keuzeData, ['prompt' => '--Select Employee--'])->label(false);
                                       

Wednesday 3 August 2016

Export Excel using sql query

$select = $_REQUEST['sql'];

mysql_query('SET NAMES utf8;');
$export = mysql_query($select);
//$fields = mysql_num_rows($export); // thanks to Eric
$fields = mysql_num_fields($export); // by KAOSFORGE
//$report_title='<Row><Cell ss:StyleID="2"><Data ss:Type="String">dileep</Data></Cell><Row>';
$col_title='';
$data ='';
for ($i = 0; $i < $fields; $i++) {
    $col_title .= '<Cell ss:StyleID="2"><Data ss:Type="String">'.mysql_field_name($export, $i).'</Data></Cell>';
}

$col_title = '<Row>'.$col_title.'</Row>';

while($row = mysql_fetch_row($export)) {
    $line = '';
    foreach($row as $value) {
        if ((!isset($value)) OR ($value == "")) {
            $value = '<Cell ss:StyleID="1"><Data ss:Type="String"></Data></Cell>\t';
        } else {
            $value = str_replace('"', '', $value);
            $value = '<Cell ss:StyleID="1"><Data ss:Type="String">' . $value . '</Data></Cell>\t';
        }
        $line .= $value;
    }
    $data .= trim("<Row>".$line."</Row>")."\n";
}

$data = str_replace("\r","",$data);
date_default_timezone_set('Asia/Kolkata');
header("Content-Type: application/vnd.ms-excel;");
header("Content-Disposition: attachment; filename=export_".date('d-m-Y H:i:s').".xls");
header("Pragma: no-cache");
header("Expires: 0");

$xls_header = '<?xml version="1.0" encoding="utf-8"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author></Author>
<LastAuthor></LastAuthor>
<Company></Company>
</DocumentProperties>
<Styles>
<Style ss:ID="1">
<Alignment ss:Horizontal="Left"/>
</Style>
<Style ss:ID="2">
<Alignment ss:Horizontal="Left"/>
<Font ss:Bold="1"/>
</Style>

</Styles>
<Worksheet ss:Name="Export">
<Table>';

$xls_footer = '</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Selected/>
<FreezePanes/>
<FrozenNoSplit/>
<SplitHorizontal>1</SplitHorizontal>
<TopRowBottomPane>1</TopRowBottomPane>
</WorksheetOptions>
</Worksheet>
</Workbook>';

print $xls_header.$col_title.$data.$xls_footer;
exit;

Dynamic Box with JQuery

<script src="jquery-1.10.2.min.js" type="text/javascript" /></script>
<script>
$(document).ready(function(){
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><td><select class="select" name="select[]"><option value="">-select-</option><option value="a">a</option><option value="b">b</option><option value="c">c</option></select> &nbsp; <input type="text" class="selval" name="selval[]" readonly /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});

});

$(document).on('change','.select',function() {
var selval = $(this).val();
$(this).parent('td').find('.selval').val(selval);
//alert(selval);
});
</script>



    <table class="form-table" id="customFields">
<tr valign="top">

<td>
<select class="select" name="select[]">
    <option value="">-select-</option><option value="a">a</option><option value="b">b</option><option value="c">c</option></select> &nbsp; <input type="text" class="selval" name="selval[]" readonly /> &nbsp;
<a href="javascript:void(0);" class="addCF">Add</a>
</td>
</tr>
</table>

Tuesday 2 August 2016

Yii CRUD Generator

This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified data model.
Model Class-      app\models\TahsileMaster
Search Model Class- app\models\TahsileMastersearch
Controller Class- backend\controllers\TahsileController
View Path-

Link for merg

Yii Set .htaccess for direct access project (frontend) & admin(backend)

Step 1.
Options +FollowSymlinks
RewriteEngine On

# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/  <------
RewriteCond %{REQUEST_URI} ^/(admin)  <------
RewriteRule ^.*$ backend/web/index.php [L]


RewriteCond %{REQUEST_URI} ^/(assets|css)  <------
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/  <------
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

Note : if you are trying in local server then replace ^/ with ^/project_name/ where you see arrow sign. Remove those arrow sign <------ after setup is done.


Step 2.
create file Request.php in
common\components
and put below code:


<?php


namespace common\components;


class Request extends \yii\web\Request
{


   public $web;
   public $adminUrl;


   public function getBaseUrl()
   {
       return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
   }


   /*
     If you don't have this function, the admin site will 404 if you leave off
     the trailing slash.


     E.g.:


     Wouldn't work:
     site.com/admin


     Would work:
     site.com/admin/


     Using this function, both will work.
    */


   public function resolvePathInfo()
   {
       if ($this->getUrl() === $this->adminUrl)
       {
           return "";
       } else
       {
           return parent::resolvePathInfo();
       }
   }


}


Step 3.  put code
Installing component. Write below code in frontend/config/main.php and backend/config/main.phpfiles respectively.


//frontend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/frontend/web'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

// backend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/backend/web',
    'adminUrl' => '/admin'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],
For Short URL:-
add rules in url manager
         'rules' =>
            [
                'country-add'=>'country/create',
                 'country-view/<id:\d>' => 'country/view', 
           ] 

Monday 4 July 2016

Database Migrate in Yii

-> After Database Connctive
CMD in
D:\wamp\www\Yii2\>yii migrate
Yii Migration Tool (based on Yii v2.0.6)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
       m130524_201442_init

Apply the above migration? (yes|no) [no]:yes
*** applying m130524_201442_init
   > create table {{%user}} ... done (time: 1.185s)
*** applied m130524_201442_init (time: 1.335s)
Migrated up successfully.

D:\wamp\www\Yii2\>

Theme Installing

#   frontend->assets->AppAsset.php
Put here css & js links
like as

public $css = [
       //'css/site.css',
       'assets/css/bootstrap.css',
       'assets/css/font-awesome.css',
       'assets/js/morris/morris-0.4.3.min.css',
       'assets/css/custom-styles.css',
            'http://fonts.googleapis.com/css?family=Open+Sans',
   ];
   public $js = [
       'assets/js/jquery-1.10.2.js',
       'assets/js/bootstrap.min.js',
       'assets/js/jquery.metisMenu.js',
       'assets/js/morris/raphael-2.1.0.min.js',
       'assets/js/morris/morris.js',
       'assets/js/custom-scripts.js',
   ];
put links files on web folder

# set views in layout  main & index  

Setup VueJS in Laravel

Setup VueJS in Laravel 1. You will need to install javascript dependencies by running the following command on your terminal.      npm i...