Menus

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:


            





PHP Programming Tips


INDEX
PHP - add item to beginning of associative array
PHP sizeof() Function
Split multiple lines and input them in separate row in a database
How to print a debug log
PHP prepend leading zero before single digit number
Show a number to 2 decimal places
Comparing Dates in PHP
Adding days to Date in PHP





PHP - add item to beginning of associative array


How can I add an item to the beginning of an associative array? 

For example, say I have an array like this:
$arr = array('key1' => 'value1', 'key2' => 'value2');

Answers:

You could use the union operator:

$arr1 = array('key0' => 'value0') + $arr1;

One way is with array_merge:
<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);  ?>

PHP sizeof() Function

The sizeof() function returns the number of elements in an array.

<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>

Example

for($i=0;$i<sizeof($batch);$i++){                    
   echo '<td>'. $batch[$i]['batch_name'].'</td>';
}


Split multiple lines and input them in separate row in a database



How to explode a multi-line string?


PHP explode() Function

Definition and Usage

The explode() function breaks a string into an array.

Syntax

explode(separator,string,limit)




Depending on your os a newline can be "\n", "\r\n" or "\r".
Give this a shot:
$strip=explode("<br>", nl2br($linkfield));
or maybe safer:
$strip=explode("\n", str_replace(array("\n", "\r\n"), "\n", $linkfield));


$address=explode("\n", str_replace(array("\n", "\r\n"), "\n", $student->present_address));
print_r($address);

Output

 Array ( [0] => SHANEESH P [1] => OPP MUNICIPAL OFFICE [2] => MALAPPURAM [3] => KERALA [4] => INDIA )


<?php
$text = $_POST['userlist'];
$array = explode('\n', $text);
?>



How to print a debug log


file_put_contents('your_log_file', 'your_content');
or
error_log ('your_content', 3, 'your_log_file');

Example 

file_put_contents('error_log', $userid);

Value stored to error_log file in your folder.



PHP prepend leading zero before single digit number


str_pad($number, 2, '0', STR_PAD_LEFT); 

Add zero to before number.

<?pph

$m=1;

$p= str_pad($m, 3, '0', STR_PAD_LEFT);

echo $p;

?>

Output : 001



show a number to 2 decimal places


You can use number_format():
return number_format((float)$number, 2, '.', '');

$padded = sprintf('%0.2f', $unpadded);

echo round(5.045, 2); 


Comparing Dates in PHP


How to compare Dates in php


<?php

$exp_date = "2017-01-10";
$todays_date = date("Y-m-d");

$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);

if ($expiration_date > $today) {
     echo "yes";
} else {
     echo "no";
}


?>


Adding days to Date in PHP


<?php

$Date = date("Y-m-d"); // "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo '<br>';
echo date('Y-m-d', strtotime($Date. ' + 360 days'));

?>