Wednesday, 11 October 2017

Yii2 Pjax Reload Grid view and stay on same page


Yii 2 Pjax -    In order to stay in same page when using Pjax reload() use the below code,

 $.pjax.reload({
container:'.grid-view',
url: $('.grid-view li.active a').attr('href')
});



Yii2 Query Builder Like operator


To use "LIKE" operator in Yii2 query builder, use the below code,

$sql = "SELECT *  FROM  TABLE_NAME  WHERE item_code = :item_code AND DATE_FORMAT(req_date, '%Y-%m') LIKE :period";
                $req_date = '%' . $req_date . '%';
                $command = Yii::$app->db->createCommand($sql);
                $command->bindParam('item_code', $item_code);
                $command->bindParam('period', $req_date);
                $result = $command->execute();

Yii2 Sum Column in Active Record



To get sum of column using active record,
$query = Item::find();
            $query->where(['item_code' => $item_code]);
            $cost = $query->sum('lot_qty');

Wednesday, 10 August 2016

Convert multidimensional array to single dimensional using php


Below is the function to convert multidimensional array into single dimensional array.



function array_flatten($array, $x = NULL) {

        if (!is_array($array)) {
            return false;
        }
        $result = array();

        $x = ($x == '') ? 0 : $x;

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, self::array_flatten($value, $x++));
            } else {
                $result[$x][$key] = $value;
            }
        }
        return $result;

    }



Yii2 href post – Post data using link tag



In Yii2, you can post data using link tag in a form with  data-method post, you can also pass data as params.


Example usage:
Html::a('<i class="fa fa fa-arrow-right"></i> Confirm Details', ['controller/action'], [
                        'class' => 'btn bg-blue btn-flat',
                        'data' => [
                            'method' => 'post',
                            'params' => [
                                'confirm-user' => '1',
                                'user_id' => '10',

                            ],
                        ]
                    ]);

Yii2 from events


In Yii2, below are the form events which we can make use it on front end / client side .

  • beforeValidate,
  • afterValidate,
  •  beforeValidateAttribute,
  • afterValidateAttribute,
  • beforeSubmit,
  •  ajaxBeforeSend,
  • ajaxComplete

Example usage:

$("#FORM-ID").on("afterValidate", function (event, messages) {

    // Now you can work with messages by accessing messages variable
 var attributes = $(this).data().attributes; // to get the list of attributes
    that has been passed in attributes property

  var settings = $(this).data().settings; // to get the settings

});

Yii2 model relation with multiple conditions

In AR Model Relations you can add multiple ON condition using andOnCondition method.
public function getInvoiceItem(){

return $this->hasOne(Invoice::className(), ['order_no' => 'order_no']) 

            ->andOnCondition(['item' => $this->order_item])           

            ->andOnCondition(['user_id' => $this->user_id]);
}


Friday, 25 September 2015

Prevent Form Submission When User Presses the Enter key / Move to next textbox when user presses enter key


 When we filling out the web forms, if we hit the Enter key accidentally, then the form will submit, it makes us frustrating every time.

To prevent this you can use the code below. Instead of submitting, it actually focus / moves to next input boxes when we press Enter key.

$('body').on('keydown', 'input, select, textarea', function(e) {
    var self = $(this)
            , form = self.parents('form:eq(0)')
            , focusable
            , next
            ;
    if (e.keyCode == 13) {
        focusable = form.find('input,a,select,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this) + 1);
        //  console.log(next.attr('type'));
        if (next.length && (next.attr('type') != 'button')) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
});


Wednesday, 22 April 2015

Wordpress admin panel custom landing page after login

Redirect to different landing page after successful login on wordpress admin panel,

/*To make non-admin users redirect to specified landing page*/

function your_login_redirect()
{

if(!is_super_admin()){

            // pick where to redirect to, in the example: Posts page
            return admin_url( 'edit.php' );
        } else {
            return admin_url();
        }
   
}
add_filter( 'login_redirect', 'your_login_redirect');



Wordpress Disable Admin Panel Menus Based on Role

In wordpress admin panel, if you want to hide certain menu's for non-admins , then add the below code in your current theme's functions.php file.


function remove_menus () {
global $menu;

        $restricted = array(__('Dashboard'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'),  __('Plugins'));
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }
}
      /* To hide menus for non -admin users*/
if(!is_super_admin()){
add_action('admin_menu', 'remove_menus');   
}


Sunday, 8 March 2015

Yii2 gridview row options

In Yii2 GridView, if you want to highlight or focus on certain row, you can use rowOptions attribute in your gridview.

Below are the example code.

<?=
GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
      'rowOptions' => function ($model, $index, $widget, $grid) {

                            if ($model->is_read == 1) {
                                return ['class' => 'read'];
                            } else {
                                return [];
                            }
                         },
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
         ['class' => 'yii\grid\ActionColumn']
    ],
]);
?>

Tuesday, 10 February 2015

Yii2 Modify GridView Filters


In Yii2  the filter input fields are automatically generated by the widget component, but we can modify to our needs by using the "filterPosition" property in Gridview widget.


To remove entire filters on Gridview,

'filterPosition'=>' ',

To show the fiters  on  top of each column's header cell,

  'filterPosition'=>'header',

To show the fiters  right below of each column's header cell,

 'filterPosition'=>'body',


To show the fiters  below each column's footer cell,

 'filterPosition'=>'footer',






Yii2 Dataprovider Pagination Set Default Value


To set yii2 data provider default pagination, the code is
    
 $dataProvider = new ActiveDataProvider([
         'query' => $query,
         'pagination'=> ['defaultPageSize' => 50]

     ]) 


    ( or )


  $dataProvider->pagination = ['defaultPageSize' => 50];



Yii2 Dataprovider Default Sorting


To set the default sorting for Yii2 Data provider is

    $dataProvider = new ActiveDataProvider([
         'query' => $query,
         'sort'=> ['defaultOrder' => ['id' => 'DESC']]

     ]) 


    ( or )


   $dataProvider->sort = ['defaultOrder' => ['id' => 'DESC']]; 



Thursday, 5 February 2015

yii2 get logged in user details

 
//To get whole logged user data
$user = \Yii::$app->user->identity;

//To get id of f logged user
$userId = \Yii::$app->user->identity->id



Monday, 17 March 2014

Yii CGridView Update onkeyup

By default Yii filters the table in cgridview, when a user entering data on search textfield and press Enter key or clicking oustside the grid.
I had a strange situation, i want to apply filter on keyup in cgridview for all pages,

Below is the code to apply filter on keyup in  yii cgridview.

    $(function() {
        $('body').on('keyup', '.filters > td > input', function() {
           
            var focusedId = $(document.activeElement).attr('id');
            var grid_id = $('#' + focusedId + '.form').closest("div").attr('id');
           
            $('#' + grid_id).yiiGridView('update', {
                data: $(this).serialize(),
                complete: function(jqXHR, status) {
                   
                    if (status == 'success') {
                        var tmpStr = $('#' + focusedId + '.form').val();
                        $('#' + focusedId + '.form').focus();
                        $('#' + focusedId + '.form').val('');
                        $('#' + focusedId + '.form').val(tmpStr);
                    }
                   
                }
            });
            return false;
        });

    });

Tuesday, 17 December 2013

Get date of seventh day from today using javascript

Here, i posted the code below to get the date of seventh day from today using javascript.

Code:

 step:1
 var date = new Date();   //to get current day's date with GMT
//i.e, the variable date outputs as Tue Dec 17 2013 00:48:41 GMT+0530 (India Standard Time)

 step:2 
 date.setDate(date.getDate() + 7);
//Now the variable date holds the timestamp of the seventh'day from today i.e, 1387826522433

  step:3
 var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg); 
 //just checking with a alert , 
 alert(dateMsg); 
//Now variable  dateMsg outputs with format as 2013-12-24,

Finally ,we displayed the date of the seventh day from today using javascript.
 
 alert(dateMsg);


Monday, 9 December 2013

Creating Skeleton App for Yii in Ubuntu

To install Yii, you need to get the latest version and extract it somewhere in your  server’s web root,

 probably here i extract it in  /opt/lampp/htdocs/

here i renamed the extract folder name as yii-1.1.14, after that you have to change the permission of the folder as 0755 to execute yiic file, so that it is executable.


root@mindzls002-desktop:/home/mindzls002# sudo chmod -R 0755 /opt/lampp/htdocs/yii-1.1.14/

Before creating your skeleton app , we want to verify that your server satisfies Yii's requirements.
Yii requires PHP 5.1, so the server must have PHP 5.1 or above installed and available to the web server.

 To check that your server meets the requirements, simply run the below url in your web browser,

      http://localhost/yii-1.1.14/requirements/
 If your server the passes the requirements, then the run the below command in your terminal,

root@mindzls002-desktop:/home/mindzls002#  /opt/lampp/bin/php  /opt/lampp/htdocs/yii-1.1.14/framework/yiic.php  webapp  /opt/lampp/htdocs/cabel

In the above code,

i) first path refers to location of php,
ii)  second path refers to the location of yiic.php (i.e. the file located in the folder         that we extract in your web root initially)
iii) third path refers to where we want to create a skeleton app. Here i created a skeleton app named cabel.

After you run the above code in terminal , a message is prompted in terminal for verification as

  Create a Web application under '/opt/lampp/htdocs/cabel'? (yes|no) [no]:

  type yes and hit enter. The terminal runs the following codes,

mkdir /opt/lampp/htdocs/cabel
   generate index.php
      mkdir /opt/lampp/htdocs/cabel/css
   generate css/main.css
   generate css/form.css
   generate css/screen.css
   generate css/ie.css
   generate css/bg.gif
   generate css/print.css
      mkdir /opt/lampp/htdocs/cabel/images
      mkdir /opt/lampp/htdocs/cabel/protected
   generate protected/yiic
      mkdir /opt/lampp/htdocs/cabel/protected/tests
      mkdir /opt/lampp/htdocs/cabel/protected/tests/unit
      mkdir /opt/lampp/htdocs/cabel/protected/tests/report
   generate protected/tests/phpunit.xml
      mkdir /opt/lampp/htdocs/cabel/protected/tests/functional
   generate protected/tests/functional/SiteTest.php
   generate protected/tests/WebTestCase.php
      mkdir /opt/lampp/htdocs/cabel/protected/tests/fixtures
   generate protected/tests/bootstrap.php
      mkdir /opt/lampp/htdocs/cabel/protected/runtime
   generate protected/yiic.php
      mkdir /opt/lampp/htdocs/cabel/protected/data
   generate protected/data/schema.sqlite.sql
   generate protected/data/testdrive.db
   generate protected/data/schema.mysql.sql
      mkdir /opt/lampp/htdocs/cabel/protected/vendor
      mkdir /opt/lampp/htdocs/cabel/protected/components
   generate protected/components/Controller.php
   generate protected/components/UserIdentity.php
   generate protected/.htaccess
      mkdir /opt/lampp/htdocs/cabel/protected/views
      mkdir /opt/lampp/htdocs/cabel/protected/views/layouts
   generate protected/views/layouts/main.php
   generate protected/views/layouts/column1.php
   generate protected/views/layouts/column2.php
      mkdir /opt/lampp/htdocs/cabel/protected/views/site
   generate protected/views/site/index.php
      mkdir /opt/lampp/htdocs/cabel/protected/views/site/pages
   generate protected/views/site/pages/about.php
   generate protected/views/site/contact.php
   generate protected/views/site/error.php
   generate protected/views/site/login.php
      mkdir /opt/lampp/htdocs/cabel/protected/commands
      mkdir /opt/lampp/htdocs/cabel/protected/commands/shell
      mkdir /opt/lampp/htdocs/cabel/protected/migrations
      mkdir /opt/lampp/htdocs/cabel/protected/config
   generate protected/config/console.php
   generate protected/config/main.php
   generate protected/config/test.php
      mkdir /opt/lampp/htdocs/cabel/protected/extensions
      mkdir /opt/lampp/htdocs/cabel/protected/controllers
   generate protected/controllers/SiteController.php
   generate protected/yiic.bat
      mkdir /opt/lampp/htdocs/cabel/protected/messages
      mkdir /opt/lampp/htdocs/cabel/protected/models
   generate protected/models/LoginForm.php
   generate protected/models/ContactForm.php
      mkdir /opt/lampp/htdocs/cabel/themes
      mkdir /opt/lampp/htdocs/cabel/themes/classic
      mkdir /opt/lampp/htdocs/cabel/themes/classic/views
   generate themes/classic/views/.htaccess
      mkdir /opt/lampp/htdocs/cabel/themes/classic/views/system
      mkdir /opt/lampp/htdocs/cabel/themes/classic/views/layouts
      mkdir /opt/lampp/htdocs/cabel/themes/classic/views/site
      mkdir /opt/lampp/htdocs/cabel/assets
   generate index-test.php

Your application has been created successfully under /opt/lampp/htdocs/cabel.

 Then Bingo, yii has successfully created the skeleton app for your project.
 Now you have to change the folder permission of the created skeleton app folder(cabel) to run it on browser.

run the below code in terminal,
root@mindzls002-desktop:/home/mindzls002# chmod -R 0555 /opt/lampp/htdocs/cabel/
root@mindzls002-desktop:/home/mindzls002# chmod -R 0777 /opt/lampp/htdocs/cabel/protected/

Finally you have created the yii skeleton app, now run the below url in your web browser to view the welcome screen,

    http://localhost/cable/

 that's it, 




    

   
   














Saturday, 2 November 2013

Simple FAQ System Using Php


This is a basic and simple faq like Q&A application developed using php and Codeigniter.

For design twitter bootstrap is used.

Features Included, below are some,

Admin can Manage
1) Users
2) Question categories
3) User posted questions and answers
4) Users

User can
1) Ask a question
2) Post an answer to question others posted.
3) also add an comment to answer.
4) View the list of question and answers posted by him

General
1) Only logged in user can post a question or answer.
2) Pagination included.

This is only a minimal version not yet a completed version.
You can download it from here,  FAQ System Using Php

Friday, 24 May 2013

Install Laravel 4 on Ubuntu


Recently i willing to learn laravel framework because of its rich features towards web development and that borrows a lot from Rails.In previous i have used the CodeIgniter for my projects.

This post is mainly for beginners, To Install laravel 4 on ubuntu 12.04

Installing Composer:

To install composer via terminal , type the command

# curl -sS https://getcomposer.org/installer | php

Move the composer to usr/local/bin to access composer globally

# mv composer.phar /usr/local/bin/composer
check if the composer is available globally by simply type
#  composer

Installing Laravel:

To install laravel via Git Clone repository first you have to install Git on your machine , if Git is installed in your machine then clone Laravel git repository as

# git clone https://github.com/laravel/laravel.git /opt/lampp/htdocs/lara_test1
 here lara_test1 our newly created project directory for installing laravel , To view the files inside the newly created project folder
#  cd  /opt/lampp/htdocs/lara_test1
#  ls
 To install composer to our project directory
#  composer install
while installing composer if the error thrown such as 
               Laravel requires the Mcrypt PHP extension.
 then you have to install the mycript library , for that simply use
# sudo apt-get install php5-mcrypt
and after that again re-install composer , it may fix issues.

And finally  open your web browser and simply go to
  http://localhost/lara_test1/public/
 Also , dont forget to change the persmission of folders within app/storage .
 

 Every thing goes fine, you welcome with laravel's  default message with Logo.


You have arrived.