Quantcast
Channel: Live News for Yii Framework
Viewing all 3361 articles
Browse latest View live

[wiki] When to use Active Record

$
0
0

When to use Active Record is a common question among developers, Yii and overall.

I have about 500K records in my DB tables and each query there are 2 or 3 joins. I was getting data via AR, about a hundred records a time and noticed that using createCommand consumes less memory and CPU. I think with DAO instead of AR it will be faster.

It is true that Active Record consumes memory for storing objects and CPU cycles for instantiate these objects.

Is AR bad? It it for small projects only? We have lots of inserts, about 5000 records an hour and we're using AR for that. Should we re-write?

AR is a pleasure to use when you're managing not that many records at the same time. CRUD is very easy with it. Yii 2 dirty attribute support (only what was modified is saved) off-loads database and mitigates many parallel editing conflicts. If you don't have complex logic in your app and you don't need entity abstractions, AR is an ideal choice.

AR is OK for queries not too complicated when they return no more than a hundred objects. Yes, it is faster and less memory consuming to use query builder or asArray() but working with arrays is significantly less convenient.

For complex queries, such as aggregates or reports, AR isn't recommended. These are easier to express with query builder or SQL. Same goes for import and export routines.


[extension] diecoding/yii2-toastr

$
0
0

Yii2 Toastr - Simple flash toastr notifications for Yii2

Cara Memasang

Melalui console:

composer require --prefer-dist diecoding/yii2-toastr "dev-master"

atau tambahkan:

"diecoding/yii2-toastr": "dev-master"

pada baris require yang terdapat di berkas composer.json. Kemudian jalankan

composer update

[extension] kartik-v/yii2-bootstrap4-dropdown

$
0
0

yii2-bootstrap4-dropdown

  1. Demo
  2. Installation
  3. Usage
  4. License

Stable Version Unstable Version License Total Downloads Monthly Downloads Daily Downloads

Enhanced Bootstrap 4 dropdown widget for Yii2 framework with nested submenu support.

Demo

You can see detailed documentation and demos on usage of this extension.

Installation

The preferred way to install this extension is through composer.

Note: Check the composer.json for this extension's requirements and dependencies. Read this web tip /wiki on setting the minimum-stability settings for your application's composer.json.

Either run

$ php composer.phar require kartik-v/yii2-bootstrap4-dropdown "@dev"

or add

"kartik-v/yii2-bootstrap4-dropdown": "@dev"

to the `require` section of your composer.json file.

Usage

Dropdown Solo Button

Usage of kartik\bs4dropdown\Dropdown widget as a standalone dropdown button.

<?php 
use \yii\helpers\Html;
use kartik\bs4dropdown\Dropdown;
?>
<div class="dropdown">
    <?php
        echo Html::button('Dropdown Button', [
           'id' => 'dropdownMenuButton',
           'class' => 'btn btn-secondary dropdown-toggle'
           'data-toggle' => 'dropdown',
           'aria-haspopup' => 'true',
           'aria-expanded' => 'false'
        ]);
        echo Dropdown::widget([
            'items' => [
                ['label' => 'Section 1', 'url' => '/'],
                ['label' => 'Section 2', 'url' => '#'],
                [
                     'label' => 'Section 3', 
                     'items' => [
                         ['label' => 'Section 3.1', 'url' => '/'],
                         ['label' => 'Section 3.2', 'url' => '#'],
                         [
                             'label' => 'Section 3.3', 
                             'items' => [
                                 ['label' => 'Section 3.3.1', 'url' => '/'],
                                 ['label' => 'Section 3.3.2', 'url' => '#'],
                             ],
                         ],
                     ],
                 ],
            ],
            'options' => ['aria-labelledby' => 'dropdownMenuButton']
        ]);
    ?>
</div>
Dropdown Menu NavBar

Usage of kartik\bs4dropdown\Dropdown widget with Bootstrap 4 NavBar.

use yii\bootstrap4\NavBar;
use yii\bootstrap4\Nav;
use kartik\bs4dropdown\Dropdown;

NavBar::begin(['brandLabel' => 'NavBar Test']);
echo Nav::widget([
    'items' => [
        ['label' => 'Home', 'url' => ['/site/index']],
        [
            'label' => 'Sections', 
            'items' => [
                ['label' => 'Section 1', 'url' => '/'],
                ['label' => 'Section 2', 'url' => '#'],
                [
                     'label' => 'Section 3', 
                     'items' => [
                         ['label' => 'Section 3.1', 'url' => '/'],
                         ['label' => 'Section 3.2', 'url' => '#'],
                         [
                             'label' => 'Section 3.3', 
                             'items' => [
                                 ['label' => 'Section 3.3.1', 'url' => '/'],
                                 ['label' => 'Section 3.3.2', 'url' => '#'],
                             ],
                         ],
                     ],
                 ],
            ],
            'dropDownOptions' => ['aria-labelledby' => 'sectionsMenu'],
            'linkOptions' => [
                'id' => 'sectionsMenu',
                'class' => "nav-link dropdown-toggle{$active1}", 
                'title' => 'Krajee Dropdown Sections',
                'role' => 'button',
                'aria-haspopup' => 'true',
                'aria-expanded' => 'false'
            ]
        ],
        ['label' => 'About', 'url' => ['/site/about']],
    ],
    'dropdownClass' => Dropdown::classname(), // use the custom dropdown
    'options' => ['class' => 'navbar-nav mr-auto'],
]);
NavBar::end();

License

yii2-bootstrap4-dropdown is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

[extension] kartik-v/yii2-filesystem

$
0
0

yii2-filesystem

  1. Usage
  2. Examples
  3. License

Latest Stable Version Latest Unstable Version License Total Downloads Monthly Downloads Daily Downloads

File system utilities for managing files and folders including reading, writing and appending to files. It also includes a Resumable component that provides an object oriented backend to manage resumable and chunk file uploads via resumable.js.

Install

Either run

$ php composer.phar require kartik-v/yii2-filesystem "@dev"

or add

"kartik-v/yii2-filesystem": "@dev"

to the `require` section of your composer.json file.

Usage

Example showing creation of a folder instance and search for all the .csv files within it:

use kartik\filesystem\Folder;

$dir = new Folder('/path/to/folder');
$files = $dir->find('.*\.csv');

Now you can loop through the files and read from or write/append to the contents or simply delete the file:

use kartik\filesystem\File;

foreach ($files as $file) {
    $file = new File($dir->pwd() . DIRECTORY_SEPARATOR . $file);
    $contents = $file->read();
    // $file->write('I am overwriting the contents of this file');
    // $file->append('I am adding to the bottom of this file.');
    // $file->delete(); // I am deleting this file
    $file->close(); // Be sure to close the file when you're done
}

Examples

use kartik\filesystem\Folder;
use kartik\filesystem\File;

/**
 * Create a new folder with 0755 permissions
 */
$dir = new Folder('/path/to/folder', true, 0755);

/**
 * Create a new file with 0644 permissions
 */
$file = new File('/path/to/file.php', true, 0644);

/**
 * addPathElement: Returns $path with $element added, with correct slash in-between.
 */
$path = Folder::addPathElement('/a/path/for', 'testing');
// $path equals /a/path/for/testing

/**
 * cd: Change directory to $path. Returns false on failure.
 */
$folder = new Folder('/foo');
echo $folder->path; // Prints /foo
$folder->cd('/bar');
echo $folder->path; // Prints /bar
$false = $folder->cd('/non-existent-folder');

/**
 * chmod: Change the mode on a directory structure recursively. 
 *        This includes changing the mode on files as well.
 */
$dir = new Folder();
$dir->chmod('/path/to/folder', 0644, true, ['skip_me.php']);

/**
 * copy: Recursively copy a directory.
 */
$folder1 = new Folder('/path/to/folder1');
$folder1->copy('/path/to/folder2');
// Will put folder1 and all its contents into folder2

$folder = new Folder('/path/to/folder');
$folder->copy([
    'to' => '/path/to/new/folder',
    'from' => '/path/to/copy/from', // Will cause a cd() to occur
    'mode' => 0755,
    'skip' => ['skip-me.php', '.git'],
    'scheme' => Folder::SKIP  // Skip directories/files that already exist.
]);

/**
 * create: Create a directory structure recursively. Can be used to create 
 *         deep path structures like /foo/bar/baz/shoe/horn
 */
$folder = new Folder();
if ($folder->create('foo' . DS . 'bar' . DS . 'baz' . DS . 'shoe' . DS . 'horn')) {
    // Successfully created the nested folders
}

/**
 * delete: Recursively remove directories if the system allows.
 */
$folder = new Folder('foo');
if ($folder->delete()) {
    // Successfully deleted foo and its nested folders
}

/**
 * find: Returns an array of all matching files in the current directory.
 */
// Find all .png in your webroot/img/ folder and sort the results
$dir = new Folder(WWW_ROOT . 'img');
$files = $dir->find('.*\.png', true);
/*
Array
(
    [0] => cake.icon.png
    [1] => test-error-icon.png
    [2] => test-fail-icon.png
    [3] => test-pass-icon.png
    [4] => test-skip-icon.png
)
*/

/**
 * findRecursive: Returns an array of all matching files in and below the current directory.
 */
// Recursively find files beginning with test or index
$dir = new Folder(WWW_ROOT);
$files = $dir->findRecursive('(test|index).*');
/*
Array
(
    [0] => /var/www/demo/index.php
    [1] => /var/www/demo/test.php
    [2] => /var/www/demo/img/test-skip-icon.png
    [3] => /var/www/demo/img/test-fail-icon.png
    [4] => /var/www/demo/img/test-error-icon.png
    [5] => /var/www/demo/img/test-pass-icon.png
)
*/

/**
 * read: Returns an array of the contents of the current directory. The returned
 *       array holds two sub arrays: One of directories and one of files.
 */
// Recursively find files beginning with test or index
$dir = new Folder(WWW_ROOT);
$files = $dir->findRecursive('(test|index).*');
/*
Array
(
    [0] => /var/www/demo/index.php
    [1] => /var/www/demo/test.php
    [2] => /var/www/demo/img/test-skip-icon.png
    [3] => /var/www/demo/img/test-fail-icon.png
    [4] => /var/www/demo/img/test-error-icon.png
    [5] => /var/www/demo/img/test-pass-icon.png
)
*/

License

yii2-filesystem is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.

[extension] mludvik/yii2-tags-input

$
0
0

yii2-tags-input

  1. Installation
  2. Usage

Yii2 integration for developit/tags-input.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require mludvik/yii2-tags-input:"~1.0"

or add

"mludvik/yii2-tags-input": "~1.0"

to the require section of your composer.json.

Usage

<?php use mludvik\tagsinput\TagsInputWidget; ?>

<?= $form->field($model, 'tags')->widget(TagsInputWidget::className()) ?>

[extension] ayrozjlc/yii2-counterup

$
0
0

Yii2 Counter-Up

  1. Installation
  2. Usage

AssetBundle for jQuery Counter-Up Plugin https://github.com/NawaraGFX/Counter-Up

Installation

Composer
composer require --prefer-dist "ayrozjlc/yii2-counterup:*"

or add

"ayrozjlc/yii2-counterup": "dev-master"

to the `require` section of your composer.json file.

Usage

in view (for example: `@app/views/layouts/main.php`)

// ...
use ayrozjlc\counterup\CounterUpAsset;
// ...
CounterUpAsset::register($this);

or add to your `assets/AppAsset.php`

public $depends = [
    // ...
    '\ayrozjlc\counterup\CounterUpAsset',
];

Add the class "counter" to the number that will be given the animation:

<span class="counter"> 1000 </ span>

[extension] odaialali/yii2-qrcode-reader

$
0
0

THIS REPO IS ONLY FOR EXPIREMENT, DO NOT USE IN REAL PROJECTS

Yii2 QR Code Reader

  1. Installation
  2. Usage

Yii2 widget for reading qr code using laptop or phone camera

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require odaialali/yii2-qrcode-reader "*"

or add

"odaialali/yii2-qrcode-reader": "*"

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your code by :

echo odaialali\qrcodereader\QrReader::widget([
	'id' => 'qrInput',
	'successCallback' => "function(data){ $('#qrInput').val(data) }"
]);

[wiki] A collection of outstanding JQuery plugins


[extension] queueyii

$
0
0

QueueYii Extension

Simple queue processor extension for Yii 1.1.*

Requirements
  • PHP 5.3 >
  • Yii 1.1.*
Installation

Download the extension package.

Unzip in extension folder

Add in your config/console.php:

    ...
    'import' => array(
        ...,
        'application.extensions.*',
    ),
    'classMap' => array(
        'queue' => 'application.extensions.queueyii.command.queueCommand
    )
Example Job

Your jobs class should like this:

<?php

/**
 * Class ExampleJob
 */
class ExampleJob extends Job
{
    /**
     * @var string
     */
    private $string;

    public function __construct($string)
    {
        $this->string = $string;
    }

    /**
     * Exec example job
     */
    public function exec()
    {
        // add you code here
        echo "Running job " . $this->string;
    }
}
Adde jobs to queue

You can add a new job on queue with this code:

Jobs::enqueue(new ExampleJob('string');
Running the queue

Using the yiic, you can run the queue, running this command:

php yiic queue listem --delay=5

You can parse the param delay, for add one interval between the jobs. The param delay is not required.

[wiki] How to customize your grid columns visible and order by user themselves

$
0
0
  1. Goal
  2. Sample Picture
  3. Add code in controller
  4. Add code in model
  5. Adjust your view code
  6. a.Register JS
  7. b.Show Config Columns link
  8. c.Add partial render code in your view file
  9. d.That partial render real file
  10. Some Help Functions

Goal

Cusomized your grid columns by user themselves, allow user to hide/show columns or re-order the columns sequences.

Sample Picture

The final result look like below, you can hide/show any columns. You can type the order to re-sort the columns after save the config. You can input -1 to put it in first columns. After save, the index will reorder from 1 to the max.

The export to excel function will affected by the final resorted columns in case you use my export grid to excel extends hzlexportgrid too, Since that export extention just depends on the grid columns configs, and that columns been customized by user themselves just now.

Sample Picture

Add code in controller

Below code will help you save user configs or reset it and redirect to the destination

Some helper function list details in last session, you can deep dive HzlUtil::xxxFunction later

//your other controller code
if (isset($_POST['columnsVisibleConfigArr'])) {
            HzlUtil::saveConfigColumns(NPIPartRegion::BuyerViewColumnSetting, $_POST['columnsVisibleConfigArr']);
            //we need save to user config
        }
        if (isset($_POST['resetColumnsVisibleConfigArr'])) {
//            HzlUtil::dump($_POST['resetColumnsVisibleConfigArr']);
            HzlUtil::deleteConfigColumns(NPIPartRegion::BuyerViewColumnSetting);
            $this->redirect(array("NPIPartRegion/searchNPI"));//you can set to your index file
        }

Add code in model

I assume your grid column get from your model. such as $model->yourGridColumn() instead input in your view file directly.

public function BuyerColumns($specificId)
    {
//you can ignore/remove $specificId parameter, it just use in my own code:)
        $columnsByRole =  array(
//'id',
//'Part_Id',
            'id',
//            'Is_Primary',
            array(
                'name' => 'Is_Primary',
                'header' => 'Is_Primary',
                'value' => '$data->Is_Primary==1?"Yes":"No"',
                'filter' => NPIPart::itemAlias('Yes_No'),
                'cssClassExpression' => '$data->Is_Primary==1?"green":"grey"'
            ),
//... many other arrays
'Note',
            'Platform_GSM_Note',
//    'Update_At',
            array('name' => 'Create_At', 'header' => 'Region_Create_At')
        );

//Need read columns settings
//This is the key codes, it try to get existing configs, and try to merge into current grid columns
        $settings = Yii::app()->settings;
        $userId = "User" . yii::app()->user->id;
        $configColumns = $settings->get($userId, NPIPartRegion::BuyerViewColumnSetting);
        //and adjust default grid columns by the saved customized columns settings.
        $columnsByRole = HzlUtil::mergeConfigColumns($columnsByRole, $configColumns);
        return $columnsByRole;
}

Adjust your view code

So, you complete adjust your controller, and model, not it is the time to adjust your view code.

It is quite similar as search funtion, you click the "Config Column" link, it will expand the columns for user to setting, click the save config button, will adjust grid immediately

a.Register JS

Add below code into view file, it try to register the JS. Note, the #npipart-region-grid id need change to your own grid id. You can paste below code right after your old JS code in your view file

Yii::app()->clientScript->registerScript('config-columns', "
$('.config-columns-button').click(function(){
	$('.config-columns').toggle();
	return false;
});
$('.config-columns form').submit(function(){
	$('#npipart-region-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
        $('.config-columns').toggle();
        //return false;
});
");

$columnsByRole = $model->BuyerColumns($specificId);

$columnsByRole will use in your grid. The parameter $specificID you can ignore or remove. $model->BuyerColumns($specificId) defined before, you can replace by your own get columns function:) just need to do some special handles in that function. It state before, let me highlight again below:

//your get column function need add below at the end
        $settings = Yii::app()->settings;
        $userId = "User" . yii::app()->user->id;
        $configColumns = $settings->get($userId, NPIPartRegion::BuyerViewColumnSetting);
        //and adjust default grid columns by the saved customized columns settings.
        $columnsByRole = HzlUtil::mergeConfigColumns($columnsByRole, $configColumns);
        return $columnsByRole;

b.Show Config Columns link

Add below code under the search link, it try to show the "Config Columns" link. You can adjust style by yourself, just need keep that 'class' => 'config-columns-button'

<?php echo str_repeat("&nbsp",10).CHtml::link('<b><font color = "red"> </font>Config Columns<font color = "red"> </font></b>', '#', array('class' => 'config-columns-button')); ?>

c.Add partial render code in your view file

Usually you have search code in your view file, please add below config columns code right after it. It try to partial render the _columnsVisibleConfig.php .

<div class="config-columns" style="display:none" >
    <!--<div class="search-form1" >-->
    <?php
    $this->renderPartial('_columnsVisibleConfig', array(
        'model' => $model,
        'columnsVisibleConfigArr'=>HzlUtil::getConfigColumns($columnsByRole),
        'gridLength' => 14  //you can adjust the number here, for example in case 54 columns, then the config will show as 4 grids, since 14*4=56 > 54.  Thanks.
    ));
    ?>
</div><!-- search-form -->


//other your codes
//your grid may be like below
$this->widget(
        'bootstrap.widgets.TbExtendedGridView', array(
    'id' => 'npipart-region-grid',
    'filter' => $model,
    'fixedHeader' => true,
    'type' => 'bordered hover',
    //'headerOffset' => 40,
    // 40px is the height of the main navigation at bootstrap
    'dataProvider' => $model->search(true, $specificId),
    'template' => "{pager}{summary}{items}{summary}{pager}",
    'enablePagination' => true,
    'columns' => $columnsByRole,  //note here, we use the columns which been handled in advance.
    'pager' => array(
        'class' => 'bootstrap.widgets.TbPager',
        'displayFirstAndLast' => true,
    ),
        )
);


d.That partial render real file

Usually it put in your view folder, name as _columnsVisibleConfig.php And then you can partial render this file in your view file.

<?php
$tempGridLength = $gridLength; 
?>

<div class="form">
    <div class="span18" style="font-size:83%">
        <?php
        echo CHtml::beginForm();
        $tempJ = 0;
        foreach ($columnsVisibleConfigArr as $tempI => $tempItem):
            if ($tempJ % $tempGridLength == 0) { //echo grid head
                echo '
                <div class="span3">
                <div class="grid-view">
                <table class="items" >
                <tr>
                    <th style="width:20%">Order#</th>
                    <th>Column Name</th>
                    <th>Hide</th>
                </tr>';
            }
            if ($tempJ % 2 == 0)
        {echo '<tr class = "even" style = "height:80%" > ';}
            else
        {echo '<tr class = "odd" style = "height:80%">';}
            ?>
            <td ><?php echo CHtml::textField("columnsVisibleConfigArr[$tempI][order]", $tempItem["order"], ['min' => 1, 'max' => 100, 'style'=>"width:30%;font-size:83%"]); ?></td>
            <td ><?php echo CHtml::textField("columnsVisibleConfigArr[$tempI][name]",$tempItem["name"],['readonly'=>'readonly','style'=>"width:80%;font-size:83%" ]); ?></td>
            <td><?php echo CHtml::checkBox("columnsVisibleConfigArr[$tempI][hide]",$tempItem["hide"],[]) ?></td>
            </tr>
            <?php
            $tempJ += 1;
            if ($tempJ == $tempGridLength) {
            echo '
                </table>
                </div>'.
                                CHtml::submitButton('Save Column Config',['style'=>"width:50%;font-size:83%"]).'
                </div> ';
                $tempJ = 0;
          }
        endforeach;
        if ($tempJ <> $tempGridLength) {
            echo '
                </table>
                </div>' .
                CHtml::submitButton('Save Column Config',['style'=>"width:50%;font-size:83%"]) . '
                </div> ';
        }
        ?>
        <?php

        echo str_repeat("&nbsp",10)."<font color = 'red'>Reset to Default Columns Config?! </font>".CHtml::checkBox("resetColumnsVisibleConfigArr",false,[]);
        echo CHtml::endForm(); ?>
    </div>
</div>

Some Help Functions

You can put it in your public component file or other file which you can access later. In my example, I put into components/HzlUtil.php file

// get columns name form gived grid columns
    public static function getConfigColumns($columns = [])
    {
        if (!is_array($columns)) {
            return [];
        }
        $columnsVisibleConfigArr = [];
        foreach ($columns as $i => $item) {
            $thisColumn = [];
            if (is_array($item)) {
                if (isset($item['header'])) {
                    $thisColumn['name'] = str_replace("&nbsp", "", $item['header']);
                } elseif (isset($item['name'])) {
                    $thisColumn['name'] = $item['name'];
                }
                if (isset($item['visible'])) {
                    $thisColumn['hide'] = !$item['visible'];
                } else {
                    $thisColumn['hide'] = false;
                }
            } else {
                $thisColumn['name'] = $item;
                $thisColumn['hide'] = false;
            }
            $thisColumn['order'] = $i + 1;

            $columnsVisibleConfigArr[] = $thisColumn;
        }
        return $columnsVisibleConfigArr;
    }


//we leverage CmsSettings extension to save configs to DB.  Detail info like below, you can search from Yii forum to install in your yii1.0 system in advance. Thanks.
//Actually, I just copy that file in components folder
/**
 * CmsSettings
 * 
 * @package OneTwist CMS  
 * @author twisted1919 (cristian.serban@onetwist.com)
 * @copyright OneTwist CMS (www.onetwist.com)
 * @version 1.2
 * @since 1.0
 * @access public
 *
 * 1.1e - Special thanks to Gustavo (http://www.yiiframework.com/forum/index.php?/user/6112-gustavo/)
 */

    public static function saveConfigColumns($gridCategory = '', $gridConfig = [])
    {
        usort($gridConfig, function ($a, $b) {
            $al = intval($a["order"]);
            $bl = intval($b["order"]);
            return $al == $bl ? 0 : ($al > $bl ? 1 : -1);
        });
        foreach ($gridConfig as $i => $item) {
            $gridConfig[$i]["order"] = $i + 1;
            if (!isset($item["hide"])) {
                $gridConfig[$i]["hide"] = false;
            } else if ($item["hide"]) {
                $gridConfig[$i]["hide"] = true;
            }
        }
//we leverage the CmsSettings extention here
        $settings = Yii::app()->settings;
        $userId = "User" . yii::app()->user->id;
        $settings->set($userId, $gridCategory, $gridConfig);
    }

    public static function deleteConfigColumns($gridCategory = ''){
        $settings = Yii::app()->settings;
        $userId = "User" . yii::app()->user->id;
        $settings->delete($userId, $gridCategory);
        HzlUtil::setMsg("Success Delete Config","Success delete the columns config.");
    }

    //  configColumns: each item contain order,name,hid fields
    public static function mergeConfigColumns($defaultColumns, $configColumns)
    {
        if (empty($configColumns)) {
            return $defaultColumns;
        } else {
            $FinalColumnsByRole = [];
            foreach ($configColumns as $i => $item) {
                foreach ($defaultColumns as $j => $defaultItem) {
                    $thisDefaultItemName = 'NotExistingN/A';
                    if (is_array($defaultItem)) {
                        if (isset($defaultItem['header'])) {
                            $thisDefaultItemName = str_replace("&nbsp", "", $defaultItem['header']);
                        } elseif (isset($defaultItem['name'])) {
                            $thisDefaultItemName = $defaultItem['name'];
                        }
                    } else {
                        $thisDefaultItemName = $defaultItem;
                    }
                    if ($thisDefaultItemName == $item['name']) {//find that column
                        if ($item['hide']) {
                            if (is_array($defaultItem)) {
                                $defaultItem['visible'] = false;
                                $FinalColumnsByRole[] = $defaultItem;
                            } else {
                                $newDefaultItem = [];
                                $newDefaultItem['name'] = $defaultItem;
                                $newDefaultItem['visible'] = false;
                                $FinalColumnsByRole[] = $newDefaultItem;
                            }
                        } else {
                            $FinalColumnsByRole[] = $defaultItem;
                        }
                        unset($defaultColumns[$j]);//this is important
                        break;
                    }
                }
            }
            //need append left default to final columns
            foreach ($defaultColumns as $j => $defaultItem) {
                $FinalColumnsByRole[] = $defaultItem;
            }
            return $FinalColumnsByRole;
        }
    }

[extension] aminkt/yii2-app-api

[extension] carono/yii2-migrate

$
0
0

Scrutinizer Code Quality Latest Stable Version Total Downloads License Build Status Code Coverage

[[ENG](README.md)] [[RUS](README_RUS.md)]

MigrationTrait

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

To expand the migration capabilities, you must add a trait \carono\yii2migrate\traits\MigrationTrait or extend the migration class from \carono\yii2migrate\Migration

public function tableOptions()

Return the array with the settings for creating tables, where the key is the name of the db driver.
When creating tables through createTable(), if no properties are specified, they will be picked up from this function `php

public function tableOptions()
{
    return [
        'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'
    ];
}

public function newTables()
-
Return an array where the key is the name of the table, and the values are columns with types.  
If you call the **$this->upNewTables()** function, all specified tables will be created via createTable()  
If you call the function **$this->downNewTables()**, all specified table will be deleted using dropTable()
```php
    public function newTables()
    {
        return [
            '{{%logs}}' => [
                'data' => $this->string(),
                '@tableOptions' => [
                    'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=MyISAM'
                ]
            ]
        ];
    }
    
    public function safeUp()
    {
        $this->upNewTables();
    }
    
    public function safeUp()
    {
        $this->downNewTables();
    }

pubic function newColumns()

Return an array where the key is the name of an existing table and the values are columns with types.
If you call the function $this->upNewColumns(), all specified columns will be created using addColumn()
If you call the function $this->downNewColumns(), all specified columns will be deleted after dropColumn() `php

public function newColumns()
{
    return [
        '{{%company}}' => [
            'address' => $this->string(),
            'is_active' => $this->boolean()
        ]
    ];
}

public function safeUp()
{
    $this->upNewColumns();
}

public function safeUp()
{
    $this->downNewColumns();
}    

public function newIndex()
-
Return an array where the key is the name of an existing table and the values are the index parameters via $this->index()    
If you call the **$this->upNewIndex()** function, all specified indexes will be created via createIndex()  
If you call the function **$this->downNewIndex()**, all specified columns will be deleted using the dropIndex()
```php
    public function newIndex()
    {
        return [
            '{{%company}}' => [
                $this->index()->columns(['name'])->unique(true)
            ],
        ];
    }
    
    
    public function safeUp()
    {
        $this->upNewIndex();
    }
    
    public function safeUp()
    {
        $this->downNewIndex();
    }        

Working with foreign keys

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

Create a table, specifying a foreign key, by table name only `php $this->createTable('{{%user}}', [

'id' => $this->primaryKey(),
'company_id' => $this->foreignKey('{{%company}}')

]); `

Adding a foreign key column `php $this->addColumn('{{%user}}', 'company_id', $this->foreignKey('{{%company}}')); `

Adding a foreign key to an existing column `php $this->alterColumn('{{%user}}', 'company_id', $this->foreignKey('{{%company}}')); `

Adding foreign key with auto name `php $this->addForeignKey(null, '{{%user}}', 'photo_id', '{{%photo}}', 'id'); `

Delete foreign key by column name `php $this->dropForeignKeyByColumn('{{%user}}', 'company_id'); `

Working with indexes

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

Create an index with an automatic name `php $this->createIndex(null, '{{%user}}', 'name'); `

Deleting an index by column name `php $this->dropIndexByColumn('{{%user}}', 'name'); `

(!) It is necessary to pay attention, if there are several columns on the index, then it is necessary to specify them in the necessary sequence. If there are several indexes with such a set and sequence, all of them will be deleted. (!) Does not work correctly with postgreSQL (https://github.com/yiisoft/yii2/issues/16639) `php $this->createIndex(null, '{{%user}}', ['name', 'surname']); $this->dropIndexByColumn('{{%user}}', ['name', 'surname']); `

Pivot tables

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

To implement many-to-many tables, you can use the $this->pivot() function, a table with 2 keys will be created. The names of the keys in the PivotTable are generated automatically, so they can be set via refColumn() and sourceColumn()

Create a PivotTable by creating a table. The result is the table {{%user}}[id] {{%pv_user_photos}}[user_id, photo_id] `php $this->createTable('{{%user}}', ['id' => $this->primaryKey(), 'photos' => $this->pivot('{{%photo}}')]); `

Create a PivotTable by adding a column. `php $this->addColumn('{{%user}}', 'photos', $this->pivot('{{%photo}}')); `

Specify the name of the PivotTable `php $this->addColumn('{{%user}}', 'photos', $this->pivot('{{%photo}}')->tableName('{{%album}}')); `

PivotTrait

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

Trait to help work with pivot tables.

$company - table model Company (requires trait PivotTrait)
$user - model of table User
PvCompanyDirector - a pivot table of the two models: company and user
Pivot table - a table which contains 2 primary key

Added to the table PvCompanyDirector a bunch of the end user company `php $company->addPivot($user, PvCompanyDirector::class, $attributes = []); `

Get the PvCompanyDirector model for the company-user bundle `php $company->getPivot($model, PvCompanyDirector::class, $condition = []); `

Removed a bunch of the user-company `php $company->deletePivot($model, PvCompanyDirector::class); `

Remove all users from PvCompanyDirector for this company `php $company->deletePivots(PvCompanyDirector::class); `

Save to a temporary link variable so that you can use them later `php $company->storagePivot($user, PvCompanyDirector::class, ['hire_at' => '2010-01-01 00:00:00']); $users = $company->getStoragePivots(PvCompanyDirector::class)); // Список моделей, что добавили ранее `

The preservation of the ties of a temporary variable.
$clear - completely clears all links before adding `php $company->savePivots($clear); // Save all links added via storagePivot `

The change in behavior of the migration class

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

public function createIndex($name, $table, $columns, $unique = false)

  • $name you can specify null to generate the index name automatically

public function createTable($table, $columns, $options = null)

  • $columns supports the $this->foreignKey() and $this->pivot()
  • if $options is not specified, options are pulled from $this->tableOptions, if there are no options, then from @tableOptions to $columns

public function alterColumn($table, $column, $type)

  • $type supports type $this->foreignKey()

public function addColumn($table, $column, $type)

  • $type supports type $this->foreignKey() and $this->pivot()

public function addPrimaryKey($name, $table, $columns)

  • $name you can specify null to generate the index name automatically

public function dropColumn($table, $column)

  • Before deleting the table, foreign keys are cleared

An example of a complete migration

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)
<?php

use yii\db\Migration;
use \yii\db\Schema;
/**
 * Class m180712_120503_init
 */
class m180712_120503_init extends Migration
{
    use \carono\yii2migrate\traits\MigrationTrait;

    public function tableOptions()
    {
        return [
            'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'
        ];
    }

    public function newTables()
    {
        return [
            '{{%logs}}' => [
                'data' => $this->string(),
                '@tableOptions' => [
                    'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=MyISAM'
                ]
            ],
            '{{%user}}' => [
                'id' => $this->primaryKey(),
                'name' => $this->string(),
                'parents' => $this->pivot('{{%user}}') // Create a pivot table on itself
            ],
            '{{%photo}}' => [
                'id' => $this->primaryKey(),
                'user_id' => $this->integer()
            ],
            '{{%company}}' => [
                'id' => $this->primaryKey(),
                'name' => $this->string(),
                // Create a pivot table {{%pv_company_directors}}
                'directors' => $this->pivot('{{%user}}', 'director_id')->columns(
                    [
                        'hire_at' => $this->dateTime(),
                        // A foreign key with SET NULL rule is when you remove data from {{%user}}
                        'hired_id' => $this->foreignKey('{{%user}}', null)->onDeleteNull()->unsigned()
                    ]
                ),
                '@tableOptions' => [
                    'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'
                ]
            ],
            '{{%pv_company_user_photo}}' => [
                // Create a PivotTable of several keys
                'company_id' => $this->foreignKey('{{%company}}', null, Schema::TYPE_PK),
                'user_id' => $this->foreignKey('{{%user}}', null, Schema::TYPE_PK),
                'photo_id' => $this->foreignKey('{{%photo}}', null, Schema::TYPE_PK),
            ]
        ];
    }

    public function newColumns()
    {
        return [
            '{{%company}}' => [
                // Create a FK to user
                'user_id' => $this->foreignKey('{{%user}}'),
                // Create a pivot table employees
                'users' => $this->pivot('{{%user}}')->tableName('{{%employees}}')
            ]
        ];
    }

    public function newIndex()
    {
        return [
            '{{%company}}' => [
                $this->index()->columns(['name'])->unique(true)
            ],
        ];
    }

    public function safeUp()
    {
        $this->upNewTables();
        $this->upNewColumns();
        // Add a FK to an existing column
        $this->alterColumn('{{%photo}}', 'user_id', $this->foreignKey('{{%user}}'));
        $this->upNewIndex();
        $this->createIndex(null, '{{%user}}', 'name');
    }

    public function safeDown()
    {
        $this->dropIndexByColumn('{{%user}}', 'name');
        $this->downNewIndex();
        // Remove the FK on the column name
        $this->dropForeignKeyByColumn('{{%photo}}', 'user_id');
        $this->downNewColumns();
        $this->downNewTables();
    }
}

The resulting database schema

  1. public function tableOptions()
  2. pubic function newColumns()
  3. public function createIndex($name, $table, $columns, $unique = false)
  4. public function createTable($table, $columns, $options = null)
  5. public function alterColumn($table, $column, $type)
  6. public function addColumn($table, $column, $type)
  7. public function addPrimaryKey($name, $table, $columns)
  8. public function dropColumn($table, $column)

schema.png

[wiki] How to organize Design "things" in Yii 2 (themes and layout)

$
0
0
  1. Via "theming"
  2. Using layouts
  3. Both
  4. UseCase one
  5. UseCase two

Sometimes the App needs a nicer look & feel, so its necessary to organize the assets for this and Yii can help a lot to make it easy. In this article I provide tips for handling multiple "Designs". I use these three features:

  • AssetBundle
  • Layouts
  • Themes

What do you need for desingning your website:

  • CSS files
  • JS files
  • some Images or other media.

Lets call it "DesignAssets"

What Yii needs:

  • one or more Layout files
  • the view files
  • AssetBundle set in the layout-file

Lets call it "DesignTemplates".

So how to bundle these and where is the best place to put them in your application directory?

Via "theming"

  • myYiiApp
    • ...
    • designs
      • myDesign1
        • put here all your "DesignTemplates" (AssetBundle,layout, and view folder/files, when using themes)

Using layouts

  • myYiiApp
    • ...
    • views
      • layouts
        • myDesign1.php (layout file)
      • ...

Both

  • myYiiApp

    • ...
    • web

      • designs
        • myDesign1
          • put here all your "DesignAssets" (css, js, img, etc.)
    • ...

So you can work with the default security file-rights for the correct purpose.

UseCase one

Write an App and distribute it to some Customer. Here can it be necessary that every customer wants a personal design.

Solution: Using themes

you config in your web.php or main.php (advanced template) whats documented here

if you need special "DesignAssets"

put your "DesignAssets" und the web directory myYiiApp/web/designs/myDesign1/css and js and img folders

customize your myYiiApp/designs/myDesign1/assets/MyDesignAsset.php

and your layout file myYiiApp/designs/myDesign1/layout/main.php

thats it.

UseCase two

you need several designs for e.g. controllers. so my remmmendation is using layouts, because easy switching in controller action.

Solution with layouts

there is no need to configure anything in the config files

if you need special "DesignAssets"

put your "DesignAssets" und the web directory myYiiApp/web/designs/myDesign1/css and js and img folders

create and customize your myYiiApp/assets/MyDesignAsset.php

and your layout file myYiiApp/views/layout/mydesign1.php

in your controller action set your layout.

public function actionIndex() {
    $this->layout = 'mydesign1';
}

may it helps your start with designing Yii.

[extension] kl83/yii2-ymaps

$
0
0

Yii2 toolset for working with Yandex Map

  1. Installation
  2. Usage
  3. Interactivity
  4. License

Widgets list:

  • CoordsInput: selection of coordinates on the map;
  • StreetInput: jui autocomplete with street names of specified city.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require kl83/yii2-ymaps @dev

or add

"kl83/yii2-ymaps": "@dev"

to the require section of your composer.json file.

Usage

CoordsInput
<?= $form->field($model, 'coords')->widget('kl83\ymaps\CoordsInput', [
  'options' => [], // Html-attributes of container
  'ymapsClientOptions' => [], // Yandex map JS settings
  'placemarkClientProperties' => [], // Placemark JS properties
  'placemarkClientOptions' => [], // Placemark JS options
]) ?>
StreetInput
<?= $form->field($model, 'street')->widget('kl83\ymaps\StreetInput', [
  'options' => [], // Html-attributes
  'city' => '', // Search streets in specified city
]) ?>

Interactivity

CoordsInput

Finds the specified address on the map, and moves the placemark to it.

$('.widget').coordsInput('search', 'Some address');
StreetInput

Get or set the city to search on.

$('.widget').streetInput('city'); // Get
$('.widget').streetInput('city', 'Some city'); // Set

License

MIT License

[extension] ayrozjlc/yii2-disable-submit-form

$
0
0

Yii2 Disable Buttons

  1. Installation
  2. Register Asset
  3. Usage

Yii2 asset to automatically disable submit buttons on Yii2 ActiveForm.

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist "ayrozjlc/yii2-disable-submit-form:*"

or add

"ayrozjlc/yii2-disable-submit-form": "*"

to the require section of your composer.json file.

Register Asset

Register the ayrozjlc\disablesubmit\DisableSubmitFormAsset, preferably on your AppAsset dependencies

class AppAsset extends yii\web\AssetBundle
{
    public $depends = [
        'ayrozjlc\disablesubmit\DisableSubmitFormAsset',
        // other dependencies
    ];
}

or add in view

// ...
use ayrozjlc\disablesubmit\DisableSubmitFormAsset;
// ...
DisableSubmitFormAsset::register($this);

Usage

add in view `php $customScript = " $('#id-form').disableForm({

disabled_text : 'message',
// block : true // to activate plugin blockui
// block_div : '#element' // by default it is applied to the parent element of the form

});"; $this->registerJs($customScript, \yii\web\View::POS_READY); `


[extension] aneeshikmat/yii2-time-down-counter

$
0
0

yii2-time-down-counter

  1. Screenshot from normal result
  2. Screenshot for templete 1
  3. Screenshot for templete 2
  4. Features
  5. Decencies
  6. Installation:
  7. Usage
  8. screenshot for html result for point 5 and 6:

Widget for yii2, to start count down timer with a lot of options, This widget build dependence of timeDownCounter JS library

Total Downloads Latest Stable Version

Screenshot from normal result

Yii2 timeDownCounter screenshot_t1

Screenshot for templete 1

Yii2 timeDownCounter screenshot_temp1

Screenshot for templete 2

Yii2 timeDownCounter screenshot_temo2

And you can custmize you'r template as yourr like, we give you an option to build and control your design or use our simple design and change color, distance ...etc as you like.

Features

  1. Countdown timer work with days, houres, minutes and seconds
  2. Appilty to get timer html with fully html item container, or semi or none.(in other word you will get result dirctly or with html wrappring).
  3. Countdown timer can be stop to custmize styling or to get template to init it as default value.
  4. You have an option to determine the sperator for timer.
  5. You can handling time over message.
  6. You have an option to determind if timer will display d-h-m-s or h-m-s or m-s.
  7. its an javascript functon and you dont need to include any other js/css lib.
  8. You can set script to execute when timer is over

Decencies

Nothing.

Installation:

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist aneeshikmat/yii2-time-down-counter "v1.0.0-stable"

or add

"aneeshikmat/yii2-time-down-counter": "v1.0.0-stable"

to the require section of your composer.json file.

Usage

To use this widget you need to add this code to your html:

<?php
    use aneeshikmat\yii2\Yii2TimerCountDown\Yii2TimerCountDown;
?>

<body>
............
<div class="row">
    <div class="alert alert-success">
        Using Widget With Default Option
    </div>
    <div class="col-xs-12">
        <div id="time-down-counter"></div>
        <?= Yii2TimerCountDown::widget() ?>
    </div>
</div>

As you see, its very simple, and now we will be explaning this code, and then go to display all option may be use to help us, In prev code we call Yii2TimerCountDown widget.(if you write this syntax dirctly without determind any option, you will git time over message).

Now let's go to explain all possible option:


<?php
  $callBackScript = <<<JS
            alert('Timer Count Down 6 Is finshed!!');
JS;
?>

        <div id="time-down-counter-2"></div>
        <?= Yii2TimerCountDown::widget([
            'countDownIdSelector' => 'time-down-counter-2',
            'countDownDate' => strtotime('+1 minutes') * 1000,// You most * 1000 to convert time to milisecond
            'countDownResSperator' => ':',
            'addSpanForResult' => false,
            'addSpanForEachNum' => false,
            'countDownOver' => 'Expired',
            'countDownReturnData' => 'from-days',
            'templateStyle' => 0,
            'getTemplateResult' => 0,
            'callBack' => $callBackScript
        ]) ?>

1) countDownIdSelector: This option give you apilty to change default timer wrapper, its usfall if you have more than one timer in the same page, default selctor value is 'time-down-counter', and this selector must be an ID.

2) countDownDate: This option will accept count down date in millisecond, if you keep it empty the default value will be current time so that the count down over message will be print. Note: you need to set time in millisecond like this strtotime("+1 day") 1000; OR strtotime("2018-11-10 15:47:25") 1000.

3) countDownResSperator: This option give you apilty to change time Sperator, default sperator is `:`.

4) countDownReturnData: This option give you apilty to display full timer result (days, hours, minutes, seconds), or (hours, minutes, seconds) or (minutes, seconds), and accpet options is ('from-days' is default, 'from-hours', 'from-minutes'). Note: This option will keep timer work nomraly without removed any value, just hide / show option.

5) addSpanForResult: This option give you apilty to set each number groub in tag contain general class called item-counter-down.

6) addSpanForEachNum: This option give you apilty to set each number in timer in tag contain general class called inner-item-counter-down.

screenshot for html result for point 5 and 6:

Yii2 timeDownCounter screenshot_temo2

7) contDownOver: This option give you apilty to update message for count down over (when timer is finshed).

8) getTemplateResult: This option give you apilty to stop count down timer, the default value is 0 and thats mean timer work, 1 is mean stop timer and display timer result, 2 is mean stop timer and display html timer result. These option give you abilty to design / styling timer on browser dirctly, since the timer is work depednace of Interval function, and second option is usfall when you need to get result to set default value in html, since js need some time to start timing.

example if we use getTemplateResult: 2 : <div id="time-down-counter">30<span class="timeDownSperator">:</span>23<span class="timeDownSperator">:</span>59<span class="timeDownSperator">:</span>58</div> 9) templateStyle: This option give you apilty to use one of templates set by default in this widget, and you can override these template in you'r css files...etc, theres 3 values for this option (0 no template and its default, 1, 2). Note: If you set template 1 or 2 the addSpanForResult & addSpanForEachNum will be change to true!.

10) callBack: this option used to set script will be render after timer end. (Callback function)

[extension] aneeshikmat/form-complete-ratio

$
0
0

formCompleteRatio

  1. Screenshot from real project
  2. Screenshot for widjet when you setup this code for templete 1
  3. Screenshot for widjet when you setup this code for templete 2
  4. Features
  5. Decencies
  6. Installation:
  7. Usage

formCompleteRatio Widget for yii2, to Calculate ratio for any form filled by user (Profile Complete Ratio As Example)

Screenshot from real project

Yii2 formCompleteRatio screenshot_t1

Screenshot for widjet when you setup this code for templete 1

Yii2 formCompleteRatio screenshot_temp1

Screenshot for widjet when you setup this code for templete 2

Yii2 formCompleteRatio screenshot_temo2

Features

  1. Calculate Ratio For Forms/Models Filled And Saved In Database
  2. Work On Relational Forms/Models
  3. You have an option to determine needed fields to Calculate ratio.
  4. You have an option to determine the result style as a number only, number with %, or a template.
  5. You have an option to determine group of fields to Calculate ratio if any one of them is filled add ratio like all the group is filled.(Note: this group will get weight as 1 field only).
  6. You have an option to get ratio for one or more of rows from relational table.
  7. Works on basic & advance yii2 templete

Decencies

  1. Yii2
  2. Twitter bootstrap assets

Installation:

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist aneeshikmat/form-complete-ratio "*@dev"

or add

"aneeshikmat/form-complete-ratio": "*@dev"

to the require section of your composer.json file.

Usage

To use this widjet you need to add this code to your view:

/* you need to add needed field in your model to Calculate ratio, In our example these field in Signup() model */
public $formRatioField = [
        'id', 'name', 'email', 'phone', 'street'....etc
    ];

use aneeshikmat\yii2\FormCompleteRatio\FormCompleteRatio;// on top view page
<?= FormCompleteRatio::widget([
    'mainModel'         => new Signup(),
])?>

As you see, its very simple, and now we will be explaning this code, and then go to display all option may be use to help us, In prev code we create FormCompleteRatio widget, mainModel is used to determind the model or form we need to Calculate ratio for it, Signup here is an model, and in this example we assign new model and thats mean we will get 0 ratio. Look at this is image for result:

Yii2 formCompleteRatio screenshot_new_model

Second option is used when we need to get ratio, so that we need to find needed record for current user, let us see this example:

<?= FormCompleteRatio::widget([
            'mainModel'         => Signup::findOne(['id' => 1]),
            'withPercentage'    => true,
        ])?>

As you see, we use findOne, and we use withPercentage to set % after ratio number. Look at this image for result:

Yii2 formCompleteRatio screenshot_update_model

And now let us to see all posiople option we can use it:

<?= FormCompleteRatio::widget([
            'mainModel'         => Signup::findOne(['id' => 1]),
            'templateStyle'     => 1,
            'withPercentage'    => true,
            'formRatioField'            => ['id', 'name', 'email', 'phone'],
            'ignoreMainModelRatioField' => true,
            'templateOption'    => [
                'templateClassWrapper' => 'col-xs-4',// Block Class
                'templateBlockId'      => 'form-complete-ratio',
                'urlText'              => 'Update',// Url Text
                'url'                  => 'javascript:void(0);',// Url
                'title'                => 'Nice Option',// Main Block Title
            ]
        ])?>

templateStyle: This option has 3 different value (0, 1, 2) and the default option is 0 and thats mean without any template, 1 will render simple templete like image in "Screenshot for widjet when you setup this code for templete 1", and 2 it will render simple templete like image in "Screenshot for widjet when you setup this code for templete 2", and the dependency of these options that you can edit or update to any style you need.

withPercentage: This option can be false or true, and it means concat % with ratio number or no, the different options is false, and true for template 1 only

templateOption: This option has an options may be used to custmize templete 1, or template 2.

formRatioField: This option is very important and one of the main options in this widjet, we can set this option directly in this widjet to the desired field, or we can set it in our model without invoking it , so that we can override the field ratio or use initiated field set in model...but if you set it in widjet you need to set ignoreMainModelRatioField to true. formRatioField it accepts only array, and this array may have these options like: 1) ['field1', 'field2',....etc]:in this style our class will check if all fields are filled or not, if 3 from 4 is filled our class will return a percentage 75%.

2) ['field1', ['field2', 'field3']]: in this style we set nested array, and that will mean if either field2 OR field3 is filled then field2 and field3 both is fill, in another word we can say field1 weight is 1, and field2 & field3 weight 1, so that if field2 is filled by user without filling field1 and the ratio of field 2 and field3 will be 50%, its useful in many cases such as, if the user has a social media links and he either set facebook or tw it will be ok to display a message "your profile is complete".

3) ['field-1', ['model' => '/dir/ModelClassName', 'conditions' => ['field_db_name' => val]]]: in this style we need to Calculate ratio with related models, the 'model' will contain a class path like \app\models\SocialMedia, and conditions will have a rule we need to set in order to get the needed row, to get the related rows like is_deleted = 0..etc, you can also use {{id}} in condtions val as a replacmnet for the id in mainModel, its useful when you try to render relationed rows depending on FK..or any other way, also in this style we will Calculate ratio just if we find model row without checking field in this model, if you need to Calculate ratio dependacy of related fields ..go to the next point.

4) ['id', 'name', 'email', 'phone', ['model' => '\app\models\SocialMedia', 'oneOrMore' => 'more', 'modelItem' => [['tw', 'fb'], 'website'], 'conditions' => ['signup_id' => '{{id}}']]]: in this style we add oneOrMore to determie the ratio, we will Calculate the dependency of all rows found in model or just for one row..so that you have two options more for all rows, one only to fetch field from one row only, also if you use oneOrMore you need to use modelItem, this option has an array of fields like point 1 or 2.

to downlaod simple fully demo you can access this url: http://2nees.com/formCompleteRatio.php

and this is screenshot for demo: Yii2 formCompleteRatio screenshot_new_model

[news] New member joining Yii team as primary Yii 3.0 developer

$
0
0

Andrii Vasyliev, @hiqsol joined Yii team. Andrii uses Yii daily for his team projects and is very interested in framework moving forward.

He's from Kiev, Ukraine and is part of HiQDev team same as another long term Yii team member, Dmytro Naumenko (@SilverFire).

His primary focus will be refreshing Yii architecture splitting it into more packages to achieve more frequent independent releases and making Yii core more robust.

[extension] yii2-lacaixa

$
0
0

Yii2 lacaixa Module

  1. Installation
  2. Usage

Yii2 lacaixa module to integrate the payment gateway (TPV Virtual) Redsys to be integrated into virtual web shops that have been developed under Yii2.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist kholmatov/yii2-lacaixa "*"

or add

"kholmatov/yii2-lacaixa": "*"

to the require section of your composer.json file.

Usage

Setting configuration file `

kholmatov/yii2-lacaixa/config.php

Once the extension is installed, simply use it in your code by:
```php
echo \kholmatov\lacaixa\RedsysWDG::getFormData($DS_MERCHANT_ORDER,$DS_MERCHANT_AMOUNT,$languageCode,$ProductDescription);

or get result on Json format: `php echo \kholmatov\lacaixa\RedsysWDG::getFormDataJson($DS_MERCHANT_ORDER,$DS_MERCHANT_AMOUNT,$languageCode,$ProductDescription); ` Put this example code in any controller script for testing success url in action (URLOK):

    
    ...
    
    public function actionOk(){
        $get = Yii::$app->request->get();
        if(isset($get) && isset($get['Ds_SignatureVersion']) && isset($get['Ds_MerchantParameters']) && isset($get['Ds_Signature'])):
            
            $rs = \kholmatov\lacaixa\RedsysWDG::checkData($get['Ds_SignatureVersion'],$get['Ds_MerchantParameters'],$get['Ds_Signature']);
            if($rs){
                $rsParam = \kholmatov\lacaixa\RedsysWDG::decodeData($get['Ds_MerchantParameters']);
                $myParam = json_decode($rsParam,true);
                print_r($myParam);
                  ....
               }
        endif;

        //return $this->redirect(array('/'));
    }
    
    ...

Put this example code in any controller script for testing cancel or error url in action (URLKO):

    
    ...
    
    public function actionKo(){
       $get = Yii::$app->request->get();
          if(isset($get) && isset($get['Ds_SignatureVersion']) && isset($get['Ds_MerchantParameters']) && isset($get['Ds_Signature'])):
            $rs = \kholmatov\lacaixa\RedsysWDG::checkData($get['Ds_SignatureVersion'],$get['Ds_MerchantParameters'],$get['Ds_Signature']);
            if($rs){
                       $rsParam = RedsysWDG::decodeData($get['Ds_MerchantParameters']);
                       $myParam = json_decode($rsParam,true);
                       print_r($myParam);
                      ... 
            }
          endif;
       
          //return $this->redirect(array('/'));
    }
    
    ...
    

[news] Replacing the forum software, moving to Discourse

$
0
0

A few month ago we have replaced the old Yii Framework website with a rewritten version in Yii 2. While developing the new site, we also discussed the replacement of the old IPB forum software with a more modern solution, but replacing the forum together with the site would have been too much work to do at once.

From a long discussion, which started already a few years ago, we have now evaluated different forum software and decided to go with Discourse, which is an open source forum software made by the people who created also StackOverflow. We are going to replace the old forum with a Discourse instance starting tomorrow (September 4, 2018).

Here is a list of things that are going to change:

  • User accounts will be managed by the website, there is no duplicate login as we have it now, and all users are signed in to the forum via SSO.
  • Forum categories, topics and posts are migrated from the old forum, so no content will be lost (we might re-arrange the categories though).
  • Links from the old forum should all be redirected to the new location. If you hit broken links, please report those to us!
  • Watched topics and watched forums are not going to be migrated, so if you want to get notified about new posts, make sure to visit the new forum and configure your notification settings as well as update watched topics.
  • User badges on the website do not include the forum posts anymore, instead we are using the Badge system by Discourse, which has a lot more badges than we had before.
  • Discourse allows you to configure it to behave like a mailing list, so if you prefer to take part in Yii discussions from your email client, you can do that now.

In case you have problems logging in to the new forum, please use the Contact form or Chat to get help.

There is a forum topic for discussion on this announcement.

Viewing all 3361 articles
Browse latest View live