Menus

Thursday 10 December 2015

Array of database result to mannually display in table


Generate report of table format.

Code placed on controller action
Objective of this report for generating month wise admission count each year.

               $sql = $sql = "SELECT YEAR( date_of_join ) as eyear , MONTH( date_of_join ) as emonth , COUNT(  `admission_number` ) as totalstudents FROM  `students` WHERE YEAR(  `date_of_join` ) BETWEEN 2013 AND 2015 GROUP BY YEAR( date_of_join ) , MONTH( date_of_join ) ORDER BY YEAR( date_of_join ) , MONTH( date_of_join ) ASC ";                        
               
              $models = Students::findBySql($sql)->all();


Above this query generating result as 


eyearemonthtotalstudents
20131195
20132147
20133171
20134206
20135303
20136286
20137186
20138181
20139231
201310278
201311398
201312296
20141179
2014269
20143117
20144134
20145235
20146422
20147212
20148271
20149378
201410451
201411339
201412289
20151188
20152220
20153198
2015484
20155165
20156402
$model array represent the above result.

I want to expect result is 


COMPARISON REPORT
LOGICLAB DISTANCE EDUCATION
Year/MonthJanFebMarAprMayJunJulAugSepOctNovDecTotal
20131951471712063032861861812312783982962878
2014179691171342354222122713784513392893096
20151882201988416540226517421011700
Total56243648642470311106636266117307375867674



Answer 

One Solution


<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;

$this->title = 'Comparison Report';
$this->params['breadcrumbs'][] = ['label' => 'Comparison Report Criteria', 'url' => ['studentreport/comparisonrpt']];
$this->params['breadcrumbs'][] = $this->title;

//set heading. 
$caption = 'COMPARISON REPORT';
$caption .=  '<BR>'.Yii::$app->params['center_name'];
$caption .=  ' '.Yii::$app->params['center_caption'];

?>
          
<!-- Main content -->
<section class="invoice">
            
     <table  class="table" >           
                <tr style= "background-color: #bfcfd2" ><td colspan="14"><b><?=$caption?></b></td></tr>                    
                <tr style= "background-color: #F2F2F2"><td>Year/Month</td>
                        <td>Jan</td>
                        <td>Feb</td>
                        <td>Mar</td>
                        <td>Apr</td>
                        <td>May</td>
                        <td>Jun</td>
                        <td>Jul</td>
                        <td>Aug</td>
                        <td>Sep</td>
                        <td>Oct</td>
                        <td>Nov</td>
                        <td>Dec</td>
                        <td>Total</td> </tr>
                        
 <?php                
                //total colums print with show university
                $dataList=ArrayHelper::map($model, 'eyear', 'eyaer');
                foreach ($dataList as $key => $value) {
                    echo '<tr><td>'.$value.'</td>';
                    for($i=1;$i<=12;$i++){
                        echo '<td id='.$value.$i.'>0</td>';
                    }
                    echo '<td id='.$value.'>0</td></tr>';  //for print row toatal.
                }
                    
                 //bootam row.
                echo '<tr style= "background-color: #4CAF50"><td>Total</td>';
                for($i=1;$i<=12;$i++){
                    echo '<td id='.$i.'>0</td>';
                }   
                echo '<td id="gtotal">0</td></tr>';
                                
                //1.isplay University counts, 2.row total, 3.column total, 4. Grand total. 
                foreach ($model as $key => $value) {                    
                    echo "<script> document.getElementById('".$value['eyear'].$value['emonth']."').innerHTML = ".$value['totalstudents']." </script>";                    
                    echo "<script> "                    
                    . "document.getElementById('".$value['eyar']."').innerHTML = parseInt(document.getElementById('".$value['eyear']."').innerHTML) + ". $value['totalstudents'].";"
                    . "document.getElementById('".$value['emonth']."').innerHTML = parseInt(document.getElementById('".$value['emonth']."').innerHTML) + ". $value['totalstudents'].";"
                    . "document.getElementById('gtotal').innerHTML = parseInt(document.getElementById('gtotal').innerHTML) + ". $value['totalstudents']        
                    . "</script>";                                        
                }
                ?>
                </table>            
        </section>









Saturday 24 October 2015

Yii2 Pjax Tutorial



Yii2 Pjax Tutorial

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, YouTube, and Facebook.


YII2 PJAX

pjax is a jQuery plugin that allows quick website navigation by combining ajax and pushState. It works by sending a special request to the server every time a link is clicked or a form is submitted. The server sends back the content that needs to be updated, pjax replaces old content with new content and pushes the new URL to browser history, without the need to update the whole page.




Regular requests download the whole page. Pjax can ask the server to send only the required part of the content.


Steps using pjax in yii2 framework


1 Add one line in the beginning of your view.


<?php
use yii\widgets\Pjax;
?>

Add two lines around the content that needs partial updating.


<?php Pjax::begin(); ?>
Content that needs to be updated
<?php Pjax::end(); ?>






Ajax Search With the GridView





Getting Values From a Table Using Ajax






Submitting Forms Using Ajax



























Friday 16 October 2015

Yii2 ListBox Field


ListBox Field



Using below we can create the list box base on model attribute of yii2.0 framework. We added the following options like prompt, size, disabled, style etc

public static string activeListBox ( $model, $attribute, $items, $options = [] )
$modelyii\base\Model
The model object
$attributestring
The attribute name or expression. See getAttributeName() for the format about attribute expression.
$itemsarray
The option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using yii\helpers\ArrayHelper::map().
Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in the labels will also be HTML-encoded.
$optionsarray
The tag options in terms of name-value pairs. The following options are specially handled:
  • prompt: string, a prompt text to be displayed as the first option;
  • options: array, the attributes for the select option tags. The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags. For example,
    [
        'value1' => ['disabled' => true],
        'value2' => ['label' => 'value 2'],
    ];
    
  • groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', except that the array keys represent the optgroup labels specified in $items.
  • unselect: string, the value that will be submitted when no option is selected. When this attribute is set, a hidden field will be generated so that if no option is selected in multiple mode, we can still obtain the posted unselect value.
  • encodeSpaces: bool, whether to encode spaces in option prompt and option value with&nbsp; character. Defaults to false.
  • encode: bool, whether to encode option prompt and option value characters. Defaults totrue. This option is available since 2.0.3.
The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.
returnstring
The generated list box tag



Listbox with prompt text
<?= $form->field($model, 'population')-> listBox(
   array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
   array('prompt'=>'Select')
   ); ?>

Listbox with size

<?= $form->field($model, 'population')-> listBox(
   array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
   array('prompt'=>'Select','size'=>3)
   ); ?>


Listbox with disabled, style properties
<?= $form->field($model, 'population')-> listBox(
   array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
   array('disabled' => true,'style'=>'background:gray;color:#fff;'))
   ->label('Gender'); ?>



Setting default values in List box

<?php $model->offerCategory = ['monday', 'tuesday'] ?>
<?=$form->field($model, 'offerCategory')->listBox([
        'monday' => 'Monday',
        'tuesday' => 'Tuesday',
        'wednesday' => 'Wednesday',
        'thursday' => 'Thursday',
        'friday' => 'Friday',
        'saturday' => 'Saturday',
        'sunday' => 'Sunday'
        ],['multiple' => 'true',
    ]) ?>
//$mymodels = array of models doesnt work of course
$form->field($mymodels, 'post_types')->listBox($items);



data items call function from students modules

<?= echo $form->field($model, 'batch')->listBox(Students::getBatch(), [
                          'multiple' => true,
                          'size' => 7,])
                          ->label(FALSE);

            ?> 




Example Yii2 listbox multi-select field 


Create related function as getWeekdaysList in Appointment.php modules.



public static function getWeekdaysList()
        {
            return [
                'monday' => 'Monday',
                'tuesday' => 'Tuesday',
                'wednesday' => 'Wednesday',
                'thursday' => 'Thursday',
                'friday' => 'Friday',
                'saturday' => 'Saturday',
                'sunday' => 'Sunday',
            ];
        }

Then in my _form.php


<?= $form->field($model, 'weekdays')->listBox(app\models\Appointment::getWeekdaysList(), [
    'multiple' => true,
    'size' => 7,
]) ?> 


Access values in controller action


public function actionFeepaidcontacts()
    {....
        ...
        if ($model->load(Yii::$app->request->post())){
                                                  //your code pasted here.
                echo $model->weekdays[0];            or
                
                foreach ($model->weekdays as $key => $value) {
                     echo $value;          //print selected weekdays
                }
                
        }
        ....
        ....    
     }    
*Selected listbox items stored as form of one dimensional array.



Related links: