Yii 2.0 Third Party Components

To manage extension using composer, use these commands.

Add:

 $ composer require "vendor/package:*"
 $ composer update

Remove:

 $ composer remove "vendor/package"
 $ composer update

Then, remove references to that package within your app.

Fixing Composer Issues (composer.json )

Issue: When issuing a composer update command, it generates error The “extra.asset-installer-paths” option is deprecated, use the “config.fxp-asset.installer-paths” option.

Solution: Edit composer.json in project to remove

"extra": {
    //...
    "asset-installer-paths": {
        "npm-asset-library": "vendor/npm",
        "bower-asset-library": "vendor/bower"
    }
}

Add:

"config": {
    "process-timeout": 1800,
    "fxp-asset": {
        "installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
},
JQuery UI

To install the JUI extension for Yii2, perform the following steps:

$ composer self-update
$ composer require "fxp/composer-asset-plugin:~1.0"
$ composer update
$ composer require --prefer-dist yiisoft/yii2-jui

Usage: In the view, add a field using the DataPicker widget:

<?= $form->field($model,'action_date')->widget(\yii\jui\DatePicker::className(), [
        'dateFormat' => 'php:Y-m-d',  // 'php:Y-m-d' is the only supported format
        'value' => ($model->isNewRecord ? date("Y-m-d") : $model->date),
        'clientOptions' => [  // Options for JQuery UI widget
            'defaultDate' => '+7', //'2010-01-01',
            'currentText' => 'Today',
            //'dateFormat' => 'php:Y-m-d',  // 'php:Y-m-d' is the only supported format
            'language'   => 'US',
            'country'    => 'US',
            'showAnim'   => 'fold',
            'yearRange'  => 'c-20:c+0',
            'changeMonth'=> true,
            'changeYear' => true,
            'autoSize'   => true,
            'showButtonPanel' => true,
            //'showOn'     => "button",
            //'buttonImage'=> "images/calendar.gif",
            //'htmlOptions'=>[
            //    'style'=>'width:80px;',
            //    'font-weight'=>'x-small',
        ],
        'options' => [  // Options for HTML attributes
            'class' => 'form-control',  // Bootstrap theme
        ],
]) ?> 

Note that and empty string and null will result in an empty text field while 0 will be interpreted as a UNIX timestamp and result in a date displayed as 1970-01-01. It is recommended to add a validation filter in your model that sets the value to null in case when no date has been entered:

public function rules()
{
    return [
        ...
        [['action_date'], 'default', 'value' => null],
        [['action_date'], 'date', 'format' => 'php:d-M-Y H:i a'],
    ];
}

You can format date in your controller, then render the view. In controller:

  $model->birth_date=Yii::$app->formatter->asDate($model->birth_date, "dd-mm-yyyy"); 

See more:

ConsoleRunner

To install the ConsoleRunner extension for Yii2, perform the following steps:

$ composer self-update
$ composer require "vova07/yii2-console-runner-extension: *"

Usage: Option 1: As Imported class:

use vova07\console\ConsoleRunner;
...
class SiteController extends Controller
{
    ...
    public function actionSendEmail($id)
    {
        // Usage:
        //   $cr = new ConsoleRunner(['file' => '@my/path/to/yii']);
        //   $cr->run('controller/action param1 param2 ...');
        $cr = new ConsoleRunner(['file' => Yii::$app->basePath . DIRECTORY_SEPARATOR . 'yii']);  
        $cr->run('email-notification/send-email info@acme.com ' . $msg);
    }
}    

Options 2: As Application component:

// config.php
...
components [
    'consoleRunner' => [
        'class' => 'vova07\console\ConsoleRunner',
        'file' => '@my/path/to/yii' // or an absolute path to console file
    ]
]
...
// some-file.php
Yii::$app->consoleRunner->run('controller/action param1 param2 ...');

See more:

Krajee Kartik's Extensions

To install the JUI extension for Yii2, perform the following steps:

$ composer self-update
$ composer require "fxp/composer-asset-plugin:*"
$ composer update
$ composer require kartik-v/yii2-widgets "*"

See also:

Google Charts
  • Install it:
    • Automatically:
      $ composer require "fruppel/yii2-googlecharts" "*" 
    • Manually: Add reference in [app]/vendor/yiisoft/extensions.php the following:
return array (
  ...
  'fruppel/yii2-googlecharts' => 
  array (
    'name' => 'fruppel/yii2-googlecharts',
    'version' => '1.0.1.0',
    'alias' => 
    array (
      '@fruppel/googlecharts' => $vendorDir . '/fruppel/yii2-googlecharts',
    ),
  ),
  ...
);  

Pie Chart

<?php
use \fruppel\googlecharts\GoogleCharts;
...
?>
 
<?= GoogleCharts::widget([
    'id' => 'my-id',
    'visualization' => 'PieChart',
    'data' => [
        'cols' => [
            [
                'id' => 'topping',
                'label' => 'Topping',
                'type' => 'string'
            ],
            [
                'id' => 'slices',
                'label' => 'Slices',
                'type' => 'number'
            ]
        ],
        'rows' => [
            [
                'c' => [
                    ['v' => 'Mushrooms'],
                    ['v' => 3]
                ],
            ],
            [
                'c' => [
                    ['v' => 'Onions'],
                    ['v' => 1]
                ]
            ],
            [
                'c' => [
                    ['v' => 'Olives'],
                    ['v' => 1]
                ]
            ],
            [
                'c' => [
                    ['v' => 'Zucchini'],
                    ['v' => 1]
                ]
            ],
            [
                'c' => [
                    ['v' => 'Pepperoni'],
                    ['v' => 2]
                ]
            ],
        ]
    ],
    'options' => [
        'title' => 'How Much Pizza I Ate Last Night',
        'width' => 400,
        'height' => 300,
        'is3D' => true,
    ],
    'responsive' => true,
]) ?>

Area Chart

<?php
use \fruppel\googlecharts\GoogleCharts;
...
<?= GoogleCharts::widget([
    'visualization' => 'AreaChart',
        'options' => [
            'title' => 'Company Performance',
            'hAxis' => [
                'title' => 'Year',
                'titleTextStyle' => [
                    'color' => '#333'
                ]
            ],
            'vAxis' => [
                'minValue' => 0
            ]
        ],
    'dataArray' => [
            ['Year', 'Sales', 'Expenses'],
            ['2013',  1000,      400],
            ['2014',  1170,      460],
            ['2015',  660,       1120],
            ['2016',  1030,      540]
    ]
])
?>
TCPDF

Automatic Installation

Automatic installation is NOT recommended (see NOTES below), but these are the steps:

1. Run the following command:

  $ composer require cinghie/yii2-tcpdf "dev-master" 

2. Add reference in [app]/composer.json file, in require section:

"require": {
        ...
        "cinghie/yii2-tcpdf": "dev-master"
    },

NOTE: This installation method tends to remove the [app]/vendor/cinghie/yii2-tcpdf and fails to update correctly, leaving a non-working installation. Follow the manual installation if this happens.

Manual Installation

Manual Installation is the recommended installation method:

1. Remove the “require” reference (“cinghie/yii2-tcpdf”: “dev-master”) in the [app]/composer.json file.

2. Add reference in your configuration [app]/config/web.php (or config.php) file, in component section:

  'component' => [ 
      ...
      // Yii2 TCPDF
      'tcpdf' => [
        'class' => 'cinghie\tcpdf\TCPDF',
      ],
      ...
]

3. Add reference in [app]/vendor/yiisoft/extensions.php the following:

return array (
  ...
  'cinghie/yii2-tcpdf' => 
  array (
    'name' => 'cinghie/yii2-tcpdf',
    //'name' => 'tcpdf',
    'version' => '1.0.0',
    //'bootstrap' => '\cinghie\tcpdf\MyBootstrap',
    'alias' => 
    array (
      '@cinghie/tcpdf' => $vendorDir . '/cinghie/yii2-tcpdf',
    ),
  ),
  ...
);  

4. Create controller action. Eg:

use yii\web\Response;
...
class SiteController extends Controller
{
    public function actionPdfReport()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;  // Raw for PDF output
        return $this->render('pdf-report'); 
    }
}

5. Create view. Eg: [app]/views/site/pdf-report.php

<?php
 
/**
 * @copyright Copyright &copy;2014 Giandomenico Olini
 * @company Gogodigital - Wide ICT Solutions 
 * @website http://www.gogodigital.it
 * @package yii2-tcpdf
 * @github https://github.com/cinghie/yii2-tcpdf
 * @license GNU GENERAL PUBLIC LICENSE VERSION 3
 * @tcpdf library 6.0.075
 * @tcpdf documentation http://www.tcpdf.org/docs.php
 * @tcpdf examples http://www.tcpdf.org/examples.php
 */
 
 
// Load Component Yii2 TCPDF 
\Yii::$app->get('tcpdf');
 
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
 
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Gogogital.it');
$pdf->SetTitle('Yii2 TCPDF Example');
$pdf->SetSubject('Yii2 TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
 
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
 
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'Yii2 TCPDF Example', 'Gogodigital - Wide ICT Solutions | gogodigital.it', array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
 
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
 
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
 
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
 
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
 
// ---------------------------------------------------------
 
// set default font subsetting mode
$pdf->setFontSubsetting(true);
 
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
 
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
 
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
 
// Set some content to print
$html = "<h1>Yii2 TCPDF Works Fine!</h1>";
 
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
 
// ---------------------------------------------------------
 
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('yii2_tcpdf_example.pdf', 'I');
 
//============================================================+
// END OF FILE
//============================================================+
 
// Close Yii2
\Yii::$app->end();
 
?>

6. Test the PDF view:

TinyMCE Editor

Basic example:

<?= $form->field($model, 'introtext')->widget(letyii\tinymce\Tinymce::className(), [
    'options' => [
        'id' => 'testid',
    ],
    'configs' => [ // Read more: http://www.tinymce.com/wiki.php/Configuration
        'plugins' => 'code image link media table hr',
        'toolbar'=> 'undo redo | styleselect | removeformat bold italic | 
                     alignleft aligncenter alignright alignjustify | 
                     bullist numlist outdent indent | link image code',
        'height' => 300,
    ],
]); ?>    

Here is one with more options:

<?= $form->field($model, 'introtext')->widget(letyii\tinymce\Tinymce::className(), [
    'options' => [
        'id' => 'testid',
    ],
    'configs' => [ // Read more: http://www.tinymce.com/wiki.php/Configuration
        // full plugin list: http://www.tinymce.com/wiki.php/Plugins
        //'plugins' => 'advlist anchor autolink autoresize autosave bbcode charmap code 
        //             colorpicker compat3x contextmenu directionality emoticons example 
        //             example_dependency fullpage fullscreen hr image insertdatetime layer 
        //             legacyoutput link lists importcss media nonbreaking noneditable 
        //             pagebreak paste preview print save searchreplace spellchecker 
        //             tabfocus table template textcolor textpattern visualblocks visualchars wordcount',
        'plugins' => 'code image link media table template hr spellchecker', 
        'templates' => [ 
            ['title' => 'Template 1', 'description' => 'Basic Template', 'content' => '<b>Basic Template</b>'], 
            ['title' => 'Template 2', 'description' => 'Dev Template', 'url' => 'development.html']
        ],
        'link_list' => [
            [
                'title' => 'My page 1',
                'value' => 'http://www.tinymce.com',
            ],
            [
                'title' => 'My page 2',
                'value' => 'http://www.tinymce.com',
            ],
        ],
        'image_list' => [
                ['title' => 'Dog', 'value' => 'mydog.jpg'],
                ['title' => 'Cat', 'value' => 'mycat.gif']
            ],
        'image_advtab'=> true,
        'browser_spellcheck' => true,
        'toolbar'=> 'undo redo | styleselect | removeformat bold italic | 
                     alignleft aligncenter alignright alignjustify | 
                     bullist numlist outdent indent | link image media code',
        //'menubar'=> 'tools table view insert edit format',  // set menu order
        'menu' => [ // this is the complete default configuration
            'file'   => ['title' => 'File',   'items' => 'newdocument'],
            'edit'   => ['title' => 'Edit'  , 'items' => 'undo redo | cut copy paste pastetext | selectall'],
            'insert' => ['title' => 'Insert', 'items' => 'link media | template hr'],
            'view'   => ['title' => 'View'  , 'items' => 'visualaid'],
            'format' => ['title' => 'Format', 'items' => 'bold italic underline 
                            strikethrough superscript subscript | formats | removeformat'],
            'table'  => ['title' => 'Table' , 'items' => 'inserttable tableprops deletetable | cell row column'],
            'tools'  => ['title' => 'Tools' , 'items' => 'spellchecker code'],
        ],
        'height' => 300
    ],
]); ?>

NOTE:

  • Upgrade the TinyMCE editor files by simply replacing the folder [app]\vendor\letyii\yii2-tinymce\tinymce with the downloaded TinyMCE version.
  • Add support for media/image file manager using Responsive Filemanager.
Responsive Filemanager (RFM)
  • Unpack and upload folder filemanager to web server (somewhere in web server path, eg. /var/www/filemanager). Eg: If the file manager is needed in the backend, then [app]\backend\web\filemanager.
  • Create [app]/frontend/web/media folder for the media files (and any other uploaded files), and set write permissions (chmod 755).
  • Create [app]/frontend/web/media/thumbs folder, and set write permissions (chmod 755) to see the preview images.
  • Edit configuration file filemanager/config/config.php with appropriate settings:
    • 'upload_dir' ⇒ '/audina/site/frontend/web/media/',
    • 'current_path' ⇒ '../../../frontend/web/media/',
    • 'thumbs_base_path' ⇒ '../../../frontend/web/media/thumbs/',
  • Subscribe to Adobe Creative SDK to get a free app key at My Apps. NOTE: 'Aviary Editor' only works online, so it does not work with localhost.

Call Options:

  • Open Filemanager.
    • Options: type=0 and not set field_id
    • URL: @web/filemanager/dialog.php?type=0&fldr=.
  • Select Image:
    • Options: type=1 and set id of input text in field_id variable.
    • URL: @web/filemanager/dialog.php?type=1&field_id=fieldID.
  • Select Video:
    • Options: type=3 and set id of input text in field_id variable.
    • URL: @web/filemanager/dialog.php?type=3&field_id=fieldID.
  • Select File:
    • Options: type=2 and set id of input text in field_id variable.
    • URL: @web/filemanager/dialog.php?type=2&field_id=fieldID.

Variables:

  • type: The type of filemanager (1 = images files; 2 = all files; 3 = video files).
  • fldr: The custom view folder where to browse files (the root folder remains the same). Default = “”.
  • sort_by: The element to sorting (values: name, size, extension, date). Default = “”.
  • descending: Flag to determine whether descending (descending = 1) or ascending (descending = 0) . Default = “0”.
  • lang: The language code (eg: &lang=en_EN). default = “en_EN”.
  • relative_url: Flag to request relative URLs (eg: &relative_url=1). Otherwise returned URLs will be absolute.

Security

In the filemanager/config/config.php file, there is a security key.

define('USE_ACCESS_KEYS', FALSE);

When set to TRUE, you can only access the RFM using they key in the URL:

  <input type="button" 
        href="../filemanager/dialog.php?field_id=imgField&lang=en_EN&akey=myPrivateKey" 
        value="Files">

When using TinyMCE, add the filemanager_access_key parameter. Eg: TinyMCE config:

  ...
  'filemanager_title'           => 'Media File Manager',
  'filemanager_access_key'      => 'myPrivateKey',
  //'external_filemanager_path' => '/acme/site/backend/web/filemanager/',
  'external_filemanager_path'   =>  Yii::$app->homeUrl . '/'. Yii::$app->params['backendUrl'] . '/filemanager/',
  ...

If requiring access only to a logged users, add all the security checks at beginning of the filemanager/config/config.php file.

Use RFM as Standalone

In a view:

<a type="button" class="btn btn-primary" 
   href="'. Yii::$app->homeUrl .'filemanager/dialog.php?type=1&field_id=fieldImgURL&relative_url=1">
     Media Gallery
</a>

Use RFM in Form Input Field

In a form in view:

<?php
    // Load JS script
    $this->registerJs(getJsFilemanager(), \yii\web\View::POS_END);
 
    // Bootstrap Modal
    $tabImages = '<div class="col-md-10"><br />';
 
    //------------------------------------------------------------
    // Define winModalMediaGallery (Bootstrap Modal Window)
    //------------------------------------------------------------
    $tabImages .= '<!-- Modal -->';
    $tabImages .= '<div class="modal fade" id="winModalMediaGallery" 
                    tabindex="-1" role="dialog" aria-labelledby="winModalMediaGalleryLabel">';
    $tabImages .= '<div class="modal-dialog" role="document" style="width: 1010px;">';
    $tabImages .= '    <div class="modal-content">';
    $tabImages .= '    <div class="modal-header">';
    $tabImages .= '        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                               <span aria-hidden="true">&times;</span></button>';
    $tabImages .= '        <h4 class="modal-title" id="winModalMediaGalleryLabel">Select Image</h4>';
    $tabImages .= '    </div>';
    $tabImages .= '    <div class="modal-body" style="padding: 0px; margin: 0px; width: 1000px;">';
    $tabImages .= '       <iframe id="idGallery" width="1000" height="620" 
                               src="'. Yii::$app->homeUrl . 
                               'filemanager/dialog.php?type=2&field_id=content-intro_image&fldr=&relative_url=1" 
                               frameborder="0" style="overflow: scroll; overflow-x: hidden; overflow-y: scroll; ">
                          </iframe>';
    $tabImages .= '    </div>';
    $tabImages .= '    <div class="modal-footer">';
    $tabImages .= '        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
    $tabImages .= '    </div>';
    $tabImages .= '    </div>';
    $tabImages .= '</div>';
    $tabImages .= '</div>';
 
    //--------------------------------------
    // Intro image (single file)
    //--------------------------------------
    $tabImages .= '<label>Intro Image</label> ';
    // Select Image (using Bootstrap Modal window)
    $tabImages .= '<button id="btnIntroImg" type="button" class="btn btn-default" data-toggle="modal" 
                  data-target="#winModalMediaGallery" data-field="content-intro_image">Select</button>';
    $tabImages .= $form->field($model, 'intro_image')->textInput(['maxlength' => 255])->Label(false);
    $tabImages .= $form->field($model, 'intro_image_float')->dropDownList(
            ['left'=>'Left', 'right'=>'Right', 'none'=>'None']
            //['prompt'=>'--Select One--']    // options
        );
 
    // Image Preview
    $tabImages .= '<div id="cont-img">';
    if (!empty($model['intro_image'])) {
        $tabImages .= '<img id="preview-content-intro_image" src="'.$model['intro_image'].'" width="300" />';
    } else {
        $tabImages .= '<img id="preview-content-intro_image" 
                            src="'.$model['intro_image'].'" style="display:none;" width="300" />';
    }
    $tabImages .= '</div>';
 
    //--------------------------------------
    // Main image (single file)
    //--------------------------------------
    $tabImages .= '<br/><label>Main Image</label>';
    // Select Image (using Bootstrap Modal window)
    $tabImages .= '<button id="btnMainImg" type="button" class="btn btn-default" data-toggle="modal" 
                  data-target="#winModalMediaGallery" data-field="content-main_image">Select</button>';
    $tabImages .= $form->field($model, 'main_image')->textInput(['maxlength' => 255])->Label(false);
    $tabImages .= $form->field($model, 'main_image_float')->dropDownList(
            ['left'=>'Left', 'right'=>'Right', 'center'=>'Center']
            //['prompt'=>'--Select One--']    // options
        );
    // Image Preview
    $tabImages .= '<div id="cont-img">';
    if (!empty($model['main_image'])) {
        $tabImages .= '<img id="preview-content-main_image" src="'.$model['main_image'].'" width="300" />';
    } else {
        $tabImages .= '<img id="preview-content-main_image" 
                            src="'.$model['main_image'].'" style="display:none;" width="300" />';
    }
    $tabImages .= '</div>';  // end cont-img
    $tabImages .= '</div>';
 
    <?= Tabs::widget([
        'items' => [
            [
                'label' => 'Content',
                'content' => $tabContent,
                'active' => true
            ],
            ...
            [
                'label' => 'Images',
                'content' => $tabImages,
            ],
        ],
    ]); ?> 
?>
<?php
function getJsFilemanager()
{
    $jsBlock = '
        // DOM document ready
        $( document ).ready(function() {
            //-------------------------------------------
            // Define modal window show.bs.modal event
            //-------------------------------------------
            $("#winModalMediaGallery").on("show.bs.modal", function(event) {
                var button    = $(event.relatedTarget);     // Button that triggered the modal
                var fieldName = button.data("field");       // Extract info from data-* attributes
                //console.log("show.bs.modal(): field: " + fieldName);
 
                // Update the modal window content. We will use jQuery here, 
                // but you could use a data binding library or other methods instead.
                //var modal = $(this);
                //modal.find(".modal-title").text("New message to " + fieldName);
                //modal.find(".modal-body input").val(fieldName);
 
                // Update Gallery URL with correct target field_id.
                // This is an optional feature, only required when using 
                // multiple input image fields reusing same Bootstrap modal window.
                var url = "'. Yii::$app->homeUrl . 
                           'filemanager/dialog.php?type=2&field_id=" + fieldName + "&fldr=&relative_url=1";
                $("#idGallery").attr("src", url);  // update Filemanager URL
                //console.log("show.bs.modal(): Gallery src: " + modal.find("#idGallery").attr("src"));
            });
        });
 
        function responsive_filemanager_callback(field_id)
        { 
            // Get URL of selected image (which was stored in specified field)
            var url = jQuery("#"+field_id).val();
            //console.log("Updated field [" + field_id + "] with [" + url + "]"); 
 
            //----------------------------
            // Do some work here
            //----------------------------
            jQuery("#"+field_id).val("../../../frontend/web/media/" + url); // prepend gallery base URL to file URL
            //console.log("Updated field [" + field_id + "] with [" + url + "]"); 
 
            $("#preview-"+field_id).attr("src", jQuery("#"+field_id).val()).show();  // preview image
            $("#winModalMediaGallery").modal("toggle");                              // close window
        }  
    ';
 
    return $jsBlock;
}    

See also:

Use RFM in TinyMCE Editor

In a view requiring a text editor, add references to ResponsiveFilemanager in TinyMCE editor:

<?= $form->field($model, 'full_text')->widget(letyii\tinymce\Tinymce::className(), [
    'options' => [
        'id' => 'idFullText',
    ],
    'configs' => [ // Read more: http://www.tinymce.com/wiki.php/Configuration
        //'plugins' => 'advlist anchor autolink autoresize autosave bbcode charmap code 
        //             colorpicker compat3x contextmenu directionality emoticons example 
        //             example_dependency fullpage fullscreen hr image imagetools insertdatetime layer 
        //             legacyoutput link lists importcss media nonbreaking noneditable 
        //             pagebreak paste preview print save searchreplace spellchecker 
        //             tabfocus table template textcolor textpattern visualblocks visualchars wordcount',
        // full list: http://www.tinymce.com/wiki.php/Plugins
        'plugins' => 'code image link media table hr spellchecker imagetools responsivefilemanager', 
        'templates' => [ 
            ['title' => 'Template 1', 'description' => 'Basic Template', 'content' => '<b>Basic Template</b>'], 
            ['title' => 'Template 2', 'description' => 'Dev Template', 'url' => 'development.html']
        ],
        // ResponsiveFileManager plugin settings:
        'filemanager_title'         => 'Media File Manager',
        //'external_filemanager_path' => '/audina/site/backend/web/filemanager/',
        'external_filemanager_path' =>  Yii::$app->homeUrl . '/'. 
                                        Yii::$app->params['backendUrl'] . '/filemanager/',
        'external_plugins'          => [
            //'filemanager'           => '[app]/backend/web/filemanager/plugin.min.js',
            //'responsivefilemanager' => '[app]/vendor/letyii/yii2-tinymce/tinymce/plugins/'.
            //                           'responsivefilemanager/plugin.min.js',
            'filemanager'           => Yii::$app->homeUrl . '/'. 
                                       Yii::$app->params['backendUrl'] . '/filemanager/plugin.min.js',
            'responsivefilemanager' => 
                   str_replace('/frontend/web/', '', str_replace('/backend/web/', '', Yii::$app->homeUrl)) . 
                        '/vendor/letyii/yii2-tinymce/tinymce/plugins/responsivefilemanager/plugin.min.js',
        ],
        // Other:
        'browser_spellcheck' => true,
        'toolbar' => 'responsivefilemanager undo redo | styleselect | removeformat bold italic | 
                      alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | 
                      link image media code',
        //'menubar'=> 'tools table view insert edit format',
        'menu' => [ // this is the complete default configuration
            'file'   => ['title' => 'File',   'items' => 'newdocument'],
            'edit'   => ['title' => 'Edit'  , 'items' => 'undo redo | cut copy paste pastetext | selectall'],
            'insert' => ['title' => 'Insert', 'items' => 'link media image | template hr'],
            'view'   => ['title' => 'View'  , 'items' => 'visualaid visualblocks visualchars'],
            'format' => ['title' => 'Format', 'items' => 'bold italic underline strikethrough 
                                                          superscript subscript | formats | removeformat'],
            'table'  => ['title' => 'Table' , 'items' => 'inserttable tableprops deletetable | cell row column'],
            'tools'  => ['title' => 'Tools' , 'items' => 'spellchecker code'],
        ],
        'dialog' => ['width' => 600],
        'height' => 300
    ],
]) ?> 

Get documentation from:

Install the extension:

$ composer require --prefer-dist onmotion/yii2-gallery "*"

Add module to modules in Yii2 config file:

$config => [
   'components'=> [
       //...
   ],
   'modules' => [ 
       //... 
       'gallery' => [
            'class' => 'onmotion\gallery\Module',
       ],
       //...
    ],
    'params' => $params
];

Apply Yii migration:

$ php yii migrate --migrationPath=@vendor/onmotion/yii2-gallery/migrations

Open gallery in your browser:

http://acme.com/gallery

To customize the view (theme), then modify the configuration:

'components' => [
        //...
        'view' => [
            'theme' => [
                'pathMap' => [
                    // Eg: @app/views/gallery/default/index.php
                    '@vendor/onmotion/yii2-gallery/views' => '@app/views/gallery', 
                ],
            ],
        ],
        //...
    ],

After this, copy directory 'default' from @vendor/onmotion/yii2-gallery/views to @app/views/gallery and change as needed.

yii2-menu Menu Manager

Get documentation from:

Install the extension:

$ composer require devtrekker/yii2-menu dev-master

Add module to modules in Yii2 config file:

return [
  ...
  'modules' => [
     'menu' => [
         'class' => '\devtrekker\menu\Module',
      ],
   ],
];   

Create database schema. Verify that the db config information is correct, then:

$ php yii migrate/up --migrationPath=@vendor/devtrekker/yii2-menu/migrations

Add the menu to the Nav widget in the layout

$menu = new devtrekker\menu\Module([]);
 
NavBar::begin(['brandLabel' => 'Brand','brandUrl' => Url::home(),]);
 
echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-left'],
                    'items' => $menu->NavbarLeft() 
                ]); 
 
echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'],
                    'items' => $menu->NavbarRight()
                ]);
NavBar::end();

Alternatively, if you want to merge a static menu with this dynamic menu:

$menu = new devtrekker\menu\Module([]);
 
NavBar::begin([
    //'brandLabel' => 'Acme, Inc.',
    //'brandLabel' => Yii::$app->params['companyNameShort'],
    //'brandLabel' => '<img src="'.Yii::$app->homeUrl.'img/frontpage/logo.png" style="margin: -10px; height: 40px;" valign="left">',
    //'brandUrl'   => Yii::$app->homeUrl,
    'options' => [
        //'class' => 'navbar navbar-inverse navbar-fixed-top',  // dark theme
        //'class' => 'navbar navbar-default',                   // light theme
        'class' => 'navbar navbar-inverse',                     // dark theme
    ],
    //'submenuOptions' => ['target' => '_blank'],  // to go blank tab for each menu item
]);
$menuItems = [
    ['label' => 'Home', 'url' => ['/site/index']],
    ...
];    
 
// Merge available menu entries into a single menu
//$menuItems = (array_slice($menuItems, 0, 1, true) + $menu->NavbarRight() + array_slice($menuItems, 1, count($menuItems)-1, true));  // insert in a specific index, using array union (duplicate items with numeric keys in 2nd array are ignored)
//$menuItems = (array_slice($menuItems, 0, 1, true) + $menu->NavbarRight() + $menuItems);  // insert in a specific index, using array union (duplicate items with numeric keys in 2nd array are ignored)
//$menuItems = array_merge($menu->NavbarRight(), $menuItems);  // prepend, using array merge (duplicate items with numeric keys get appended)
$menuItems   = ($menu->NavbarRight() + $menuItems);            // prepend, using array union (duplicate items with numeric keys in 2nd array are ignored)
 
echo Nav::widget([ 
    'options' => ['class' => 'navbar-inverse navbar-nav navbar-left'],
    'items' => $menu->NavbarLeft() 
]); 
 
echo Nav::widget([ 
    'options' => ['class' => 'navbar-inverse navbar-nav navbar-right'],
    'encodeLabels' => false,  // to allow icons in labels
    //'items' => $menu->NavbarRight()
    'items' => $menuItems //$menu->NavbarRight()
]);
 
NavBar::end();
yii2-phpexcel PhpExcel (Deprecated: use PHPOffice/PhpSpreadsheet)

Get documentation from:

Install the extension:

$ composer require --prefer-dist moonlandsoft/yii2-phpexcel "*" 
PHPOffice/PhpSpreadsheet

Get documentation from:

Install the extension:

$ composer require phpoffice/phpspreadsheet

Example:

<?php
 
require 'vendor/autoload.php';
 
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
 
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
DatePicker
  • run in your project dir:
    $ php composer.phar global require "fxp/composer-asset-plugin:~1.1.1"
    $ php composer.phar require --prefer-dist yiisoft/yii2-jui "*"
  • update composer: $ composer update
  • In your view file use use yii\jui\DatePicker;.
use yii\jui\DatePicker;
...
<?php 
  // Today 
  $model->publish_up = ($model->isNewRecord ? 
      date('Y-m-d', strtotime(date('Y-m-d'))) : 
      substr($model->publish_up, 0, 10) 
  );
?>
 
<?= DatePicker::widget([
    'model' => $model,
    'attribute' => 'publish_up',
    'language' => 'ru',
    'clientOptions' => [
        'dateFormat' => 'yyyy-mm-dd',
    ],
    'options'=> ['class'=>'form-control'],
]) ?> 
 
<?= $form->field($model, 'publish')->widget(DatePicker::classname(), [
           'language' => 'en',
           'clientOptions' => [
              'defaultDate' => '01-01-2014', 
              'dateFormat' => 'MM-dd-yyyy'
           ],
           'options'=> ['class'=>'form-control'],  // Bootstrap theme
       ]) ?>

Example:

<?php 
  // 3 days from today
  $model->ship_date = ($model->isNewRecord ? 
    date('Y-m-d', strtotime(date('Y-m-d')." +3 Days")) : 
    substr($model->ship_date, 0, 10) ); 
?> 
 
<?= $form->field($model,'ship_date', [
      'template' => '{label}<div class="input-group">
         <span class="input-group-addon glyphicon glyphicon-calendar" 
            aria-hidden="true" 
            onclick="document.getElementById(\'orderform-shipdate\').select();">
         </span>{input}</div>'
    ])->widget(\yii\jui\DatePicker::className(), [
        'dateFormat' => 'php:Y-m-d',  // 'php:Y-m-d' is the only supported format
        'value' => ($model->isNewRecord ? date("Y-m-d") : $model->date),
        'clientOptions' => [  // Options for JQuery UI widget
            'defaultDate' => '+7', //'2010-01-01',
            'currentText' => 'Today',
            //'dateFormat' => 'php:Y-m-d',  // 'php:Y-m-d' is the only supported format
            'language'   => 'US',
            'country'    => 'US',
            'showAnim'   => 'fold',
            'yearRange'  => 'c-20:c+0',
            'changeMonth'=> true,
            'changeYear' => true,
            'autoSize'   => true,
            'showButtonPanel' => true,
            //'showOn'     => "button",
            //'buttonImage'=> "images/calendar.gif",
            //'htmlOptions'=>[
            //    'style'=>'width:80px;',
            //    'font-weight'=>'x-small',
        ],
        'options' => [  // Options for HTML attributes
            'class' => 'form-control',  // Bootstrap theme
        ],
    ]) ?> 

See also: MaskedInput

yii2-timepicker TimePicker / DateTimePicker

Get documentation from:

Install the extension:

$ composer require "janisto/yii2-timepicker" "*"

Use control in view:

<?= \janisto\timepicker\TimePicker::widget([
         //'language' => 'es',
        'model'     => $model,
        'attribute' => 'due_date',
        'mode'      => 'datetime',
        'clientOptions'=>[
            'dateFormat' => 'yy-mm-dd',
            'timeFormat' => 'HH:mm',
            'showSecond' => false,
        ]
]) ?>
<?= $form->field($model, 'due_date')->widget(\janisto\timepicker\TimePicker::className(), [
    // All options: http://trentrichardson.com/examples/timepicker/#tp-options
    //'language'  => 'es',
    //'model'     => $model,
    //'attribute' => 'due_date',
    'name'      => 'due_date',
    'mode'      => 'datetime',
    'clientOptions'   => [
        'dateFormat'  => 'yy-mm-dd',
        //'timeFormat' => 'HH:mm',  // 24 hr (Army Time)
        'timeFormat'  => 'hh:mm tt',
        'showSecond'  => false,
        //'hourGrid'    => 4,
        //'minuteGrid'  => 15,
        'stepHour'    => 1,
        'stepMinute'  => 15,
        'hourMin' => 8,
        'hourMax' => 20,
 
        // DropDown settings
        'controlType' => 'select',  // combobox instead of slider
        'oneLine' => true,
    ]
])->label('Due Date')->textInput(['placeholder' => 'YYYY-MM-DD HH:MM']) ?>
yii2-podium Forum

Install Role Base Authentication Control (RBAC) in Yii2 for the advanced application: Yii 2.0 Role Based Access Control (RBAC).

Make sure these roles get added to User model:

...
class User extends ActiveRecord implements IdentityInterface
{
    // Roles
    const ROLE_ADMIN      = 1;   // Super user. Also required by yii2_podium forum.
    const ROLE_MODERATOR  = 9;   // Moderate forum. Required by yii2_podium forum.
    const ROLE_MEMBER     = 10;  // Basic site use.  Same as ROLE_USER. Required by yii2_podium forum.
    ...
}

Add these lines to the [app]/common/config/main.php file:

return [
  ...
  'bootstrap' => ['log', 'podium'],
  'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=host_address;dbname=database_name',
        'username' => 'username',
        'password' => 'password',
        'charset' => 'utf8',
        'enableSchemaCache' => true
    ],
  ],
  'modules' => [
    'podium' => [
        'class' => 'bizley\podium\Module',
        //'allowedIPs' => ['192.168.0.*'], // optional
        'userComponent' => 'inherit',
        'rbacComponent' => 'inherit', // optional
        'adminId' => 1, // optional
        'userPasswordField' => 'password_hash', //'user_pass_hash', // optional
    ],
  ],
];  

Table Creation

Start installation: Go to the http://localhost/[app]/podium/install url of your application.

Configuration

  • Sign in to Podium using administrator account.
  • Go to the Administration section and then click the Settings tab.
  • Modify all necessary fields (make sure you set proper Podium “From” email address - otherwise there might be a problem with sending emails).

Cron Job

Add and customize the following cron job:

*/2 * * * * php /path/to/your/application/yii podium/queue/run &>/dev/null

This will try to send up to 100 emails every other minute.

Yii2 Authorizenet Gateway Extension

Installation

The preferred way to install this extension is through composer.

Either run:

php composer.phar require --prefer-dist tenbulls/yii2-authorizenet "dev-master"

Or add this to the require section of your composer.json file.

"tenbulls/yii2-authorizenet": "dev-master"

Example

Include the any of required classes in the controller using it, the funcions calls can be use exactly the shown in Authorize.Net PHP SDK.

use AuthorizeNetAIM;  // Advanced Integration Method (AIM)
use AuthorizeNetARB;  // Automated Recurring Billing (ARB)
use AuthorizeNetCIM;  // Customer Information Manager (CIM)
use AuthorizeNetCP;   // Card Present (CP)
use AuthorizeNetDPM;  // Direct Post Method (DPM)
use AuthorizeNetSIM;  // Server Integration Method (SIM)
use AuthorizeNetSOAP; // Simple Object Access Protocol (SOAP)
use AuthorizeNetTD;   // Transaction Details (TD)

Once the extension is installed, simply use it in a controller :

use AuthorizeNetAIM;
...    
define("AUTHORIZENET_API_LOGIN_ID", "YOURLOGIN");
define("AUTHORIZENET_TRANSACTION_KEY", "YOURKEY");
define("AUTHORIZENET_SANDBOX", true);   // Test Mode
 
class OrderController extends Controller
{
    ...
    public function actionPay()
    {
        $sale = new AuthorizeNetAIM;
        $sale->amount   = "5.99";
        $sale->card_num = '4111111111111111';
        $sale->exp_date = '0418';
        $response = $sale->authorizeAndCapture();
        if ($response->approved) {
            echo "Success! Transaction ID:" . $response->transaction_id;
        } else {
            echo "ERROR:" . $response->error_message;
        } 
    }
 
}    

Parameters

$loginid    : Your Authorize.net Login ID 
$trankey    : Your Authorize.net Transaction Key 
$ccnum      : The system removes any spaces in the string to meet Authorize.net requirements 
$ccexpmonth : 2 digit month string 
$ccexpyear  : 2 or 4 digit year string 
$ccver      : The 3 or 4 digit card verificaton code found on the back of Visa/Mastercard and the front of AmEx
$live       : Whether to process as a live or test transaction - true : Live Transcation - false : Test Transaction
$amount     : Total amount of the transaction. This must include both tax and shipping if applicable. 
$tax        : Tax amount charged (if any) 
$shipping   : Shipping cost (if any) 
$desc       : Description of the transaction to be logged into Authorize.net system 
$billinginfo: Associative Array containing values for customer billing details 
$email      : Customer email 
$phone      : Customer phone 
$billinginfo: Associative Array containing values for customer shipping details 
$invoicenum : The merchant-assigned invoice number for the transaction
$testmode   : transaction is a test (true) or not (false). Use Visa test credit card number “4222222222222, 
                   and to test the AVS response reason code (eg. number 27), submit the test transaction with 
                   the credit card number “4222222222222” and the amount matching the AVS code (eg “27.00.)

Available fields (and data structure):

AuthorizeNetAIM Object
(
    [_x_post_fields:protected] => Array
        (
            [version] => 3.1
            [delim_char] => ,
            [delim_data] => TRUE
            [relay_response] => FALSE
            [encap_char] => |
            [amount] => 0
            [card_num] => 4007000000027
            [exp_date] => 1219
        )
 
    [_additional_line_items:AuthorizeNetAIM:private] => Array
        (
        )
 
    [_custom_fields:AuthorizeNetAIM:private] => Array
        (
        )
 
    [verify_x_fields] => 1
    [_all_aim_fields:AuthorizeNetAIM:private] => Array
        (
            [0] => address
            [1] => allow_partial_auth
            [2] => amount
            [3] => auth_code
            [4] => authentication_indicator
            [5] => bank_aba_code
            [6] => bank_acct_name
            [7] => bank_acct_num
            [8] => bank_acct_type
            [9] => bank_check_number
            [10] => bank_name
            [11] => card_code
            [12] => card_num
            [13] => cardholder_authentication_value
            [14] => city
            [15] => company
            [16] => country
            [17] => cust_id
            [18] => customer_ip
            [19] => delim_char
            [20] => delim_data
            [21] => description
            [22] => duplicate_window
            [23] => duty
            [24] => echeck_type
            [25] => email
            [26] => email_customer
            [27] => encap_char
            [28] => exp_date
            [29] => fax
            [30] => first_name
            [31] => footer_email_receipt
            [32] => freight
            [33] => header_email_receipt
            [34] => invoice_num
            [35] => last_name
            [36] => line_item
            [37] => login
            [38] => method
            [39] => phone
            [40] => po_num
            [41] => recurring_billing
            [42] => relay_response
            [43] => ship_to_address
            [44] => ship_to_city
            [45] => ship_to_company
            [46] => ship_to_country
            [47] => ship_to_first_name
            [48] => ship_to_last_name
            [49] => ship_to_state
            [50] => ship_to_zip
            [51] => split_tender_id
            [52] => state
            [53] => tax
            [54] => tax_exempt
            [55] => test_request
            [56] => tran_key
            [57] => trans_id
            [58] => type
            [59] => version
            [60] => zip
        )
 
    [_api_login:protected] => APILOGINHERE
    [_transaction_key:protected] => TRANSKEYHERE
    [_post_string:protected] => 
    [VERIFY_PEER] => 1
    [_sandbox:protected] => 1
    [_log_file:protected] => 
)

Response

$response : Array (1 based) containing the Payment Gateway Reasons fields  
 
// Important Response Values 
$response[1]  = Response Code (1 = Approved, 2 = Declined, 3 = Error, 4 = Held for Review) 
$response[2]  = Response Subcode (Code used for Internal Transaction Details) 
$response[3]  = Response Reason Code (Code detailing response code) 
$response[4]  = Response Reason Text (Text detailing response code and response reason code) 
$response[5]  = Authorization Code (Authorization or approval code - 6 characters) 
$response[6]  = AVS Response (Address Verification Service response code - A, B, E, G, N, P, R, S, U, W, X, Y, Z)
                (A, P, W, X, Y, Z are default AVS confirmation settings - Use your Authorize.net Merchant Interface to change these settings)
                (B, E, G, N, R, S, U are default AVS rejection settings - Use your Authorize.net Merchant Interface to change these settings)
$response[7]  = Transaction ID (Gateway assigned id number for the transaction) 
$response[8]  = Transaction Invoice Number (Merchant assigned invoice number for the transaction) 
$response[9]  = Transaction Description (Merchant assigned description for the transaction) 
$response[10] = Transaction Amount (Merchant assigned amount for the transaction) 
$response[11] = Payment method (CC, ECHECK)
$response[12] = Transaction type (AUTH_CAPTURE, AUTH_ONLY, CAPTURE_ONLY, CREDIT, PRIOR_AUTH_CAPTUREVOID)
$response[13] = Customer ID (Merchant-assigned)
$response[14] = First name associated with the customer’s billing address
$response[15] = Last name associated with the customer’s billing address
$response[16] = Company associated with the customer’s billing address
$response[17] = Street for customer’s billing address
$response[18] = City for customer’s billing address
$response[19] = State for customer’s billing address
$response[20] = ZIP Code for customer’s billing address
$response[21] = Country for customer’s billing address
$response[22] = Phone for customer’s billing address
$response[23] = Fax for customer’s billing address
$response[24] = Email
$response[25] = First name for shipping address
$response[26] = Last name for shipping address
$response[27] = Company name for shipping address
$response[28] = Street for shipping address
$response[29] = City for shipping address
$response[30] = State for shipping address
$response[31] = ZIP Code for shipping address
$response[32] = Country for shipping address
$response[33] = Tax
$response[34] = Duty
$response[35] = Freight
$response[36] = Tax Exempt
$response[37] = Purchase Order Number
$response[38] = MD5 Hash (Gateway generated MD5 has used to authenticate transaction response) 
$response[39] = Card Code Response (CCV Card Code Verification response code:
                M = Match, N = No Match, P = No Processed, S = Should have been present, U = Issuer unable to process request)
$response[40] = Cardholder Authentication Verification Response
$response[51] = Account Number (Last 4-digits Cr Card Number with XXXX prefix)
$response[52] = Card Type (Visa, MasterCard, American Express, Discover)
$response[53] = Split Tender ID
$response[54] = Requested Amount
$response[55] = Balance on card

For more information about the Authorize.net AIM response consult their AIM Implementation Guide at http://developer.authorize.net/guides/AIM/ and go to Section Four : Fields in the Payment Gateway Response for more details.

Available response:

AuthorizeNetAIM_Response Object
(
    [_response_array:AuthorizeNetAIM_Response:private] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 13
            [3] => The merchant login ID or password is invalid or the account is inactive.
            [4] => 
            [5] => P
            [6] => 0
            [7] => 
            [8] => 
            [9] => 0.00
            [10] => 
            [11] => auth_capture
            [12] => 
            [13] => 
            [14] => 
            [15] => 
            [16] => 
            [17] => 
            [18] => 
            [19] => 
            [20] => 
            [21] => 
            [22] => 
            [23] => 
            [24] => 
            [25] => 
            [26] => 
            [27] => 
            [28] => 
            [29] => 
            [30] => 
            [31] => 
            [32] => 
            [33] => 
            [34] => 
            [35] => 
            [36] => 
            [37] => F68A9C87C1E1472521704EF38C21F647
            [38] => 
            [39] => 
            [40] => 
            [41] => 
            [42] => 
            [43] => 
            [44] => 
            [45] => 
            [46] => 
            [47] => 
            [48] => 
            [49] => 
            [50] => 
            [51] => 
            [52] => 
            [53] => 
            [54] => 
            [55] => 
            [56] => 
            [57] => 
            [58] => 
            [59] => 
            [60] => 
            [61] => 
            [62] => 
            [63] => 
            [64] => 
            [65] => 
            [66] => 
            [67] => 
            [68] => 
        )
 
    [approved] => 
    [declined] => 
    [error] => 1
    [held] => 
    [response_code] => 3
    [response_subcode] => 2
    [response_reason_code] => 13
    [response_reason_text] => The merchant login ID or password is invalid or the account is inactive.
    [authorization_code] => 
    [avs_response] => P
    [transaction_id] => 0
    [invoice_number] => 
    [description] => 
    [amount] => 0.00
    [method] => 
    [transaction_type] => auth_capture
    [customer_id] => 
    [first_name] => 
    [last_name] => 
    [company] => 
    [address] => 
    [city] => 
    [state] => 
    [zip_code] => 
    [country] => 
    [phone] => 
    [fax] => 
    [email_address] => 
    [ship_to_first_name] => 
    [ship_to_last_name] => 
    [ship_to_company] => 
    [ship_to_address] => 
    [ship_to_city] => 
    [ship_to_state] => 
    [ship_to_zip_code] => 
    [ship_to_country] => 
    [tax] => 
    [duty] => 
    [freight] => 
    [tax_exempt] => 
    [purchase_order_number] => 
    [md5_hash] => F68A9C87C1E1472521704EF38C21F647
    [card_code_response] => 
    [cavv_response] => 
    [account_number] => 
    [card_type] => 
    [split_tender_id] => 
    [requested_amount] => 
    [balance_on_card] => 
    [response] => |3|,|2|,|13|,|The merchant login ID or password is invalid or the account is inactive.|,||,|P|,|0|,||,||,|0.00|,||,|auth_capture|,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,|F68A9C87C1E1472521704EF38C21F647|,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||,||
    [error_message] => AuthorizeNet Error:
                Response Code: 3
                Response Subcode: 2
                Response Reason Code: 13
                Response Reason Text: The merchant login ID or password is invalid or the account is inactive.
 
)

Notes

This component is meant to abstract payment processing on a website. As varying sites require different requirements for information, security, or card processing (like changing Address Verification requirement) the component does not try to provide any logic to determine if a transaction was successful. It is up to the user implementing this code to process the response array and provide response accordingly.

Troubleshooting

Error 13: The merchant login ID or password is invalid or the account is inactive. Categories: Integration , Server Integration Method (SIM) , Advanced Integration Method (AIM)

Answer

Response Reason Code: 13

Response Reason Text: The merchant Login ID is invalid or the account is inactive.

This error indicates you are either posting the incorrect API Login ID within your script, connecting to a server that does not recognize your account, or using an account that is inactive. Please follow these steps to ensure that your software is connecting correctly:

  • If you are submitting your transactions using the HTTP POST method, make sure you are including your name-value pairs in the HTTP body. Do not use parameterized URLs: our servers will not recognize parameters in a URL submitted via HTTP POST, and there are security concerns with using parameterized URLs to submit sensitive details.
  • Please check your script and verify you are posting the correct API Login ID for your account. Make sure to manually type the API Login ID, to reduce the risk of copying errors. If you are not posting the correct API Login ID, or if you are not sending an API Login ID, please edit the script and confirm that the field x_login is set to the API Login ID that you may obtain from the Authorize.Net Merchant Interface. For further information on the API Login ID, Transaction Key, or Test Mode, please check out our online video tutorials at http://www.authorize.net/videos.

References

Font Awesome
  • Download FA libraries from http://fontawesome.io/icons
  • Copy libraries to [app]/web/fonts/font-awesome:
  • Add references to AppAssets in [app]/assets/AppAsset.php
    <?php
    namespace app\assets;
     
    use yii\web\AssetBundle;
     
    /**
     * @author Qiang Xue <qiang.xue@gmail.com>
     * @since 2.0
     */
    class AppAsset extends AssetBundle
    {
        public $basePath = '@webroot';
        public $baseUrl = '@web';
        public $css = [
            'css/site.css',
            'fonts/font-awesome/css/font-awesome.min.css',  // Add Font Awesome support
        ];
        public $js = [
        ];
        public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap\BootstrapAsset',
        ];
    }
  • Use font icons in view:
    <?= Html::a('<i class="fa fa-clone" aria-hidden="true"></i> ' . Yii::t('app', 'Clone'), 
        ['clone', 'id'=>$model->id], 
        ['class' => 'btn btn-default']
    ) ?>
Barcoding (yii2-barcode-generator)

Run

$ php composer.phar require --prefer-dist vilochane/yii2-barcode-generator "dev-master" 

Or add the following to @app/composer.json:

"require": {
  "vilochane/yii2-barcode-generator": "dev-master"
  //...
}  

Run $ composer update to add component to your project.

Usage:

<?php
use barcode\barcode\BarcodeGenerator as BarcodeGenerator;
 
<!--This element id should be passed on to options-->
<div id="showBarcode"></div>
 
$optionsArray = [
    'elementId' => 'showBarcode',   // div or canvas id
    'value'     => '4797001018719', // value for EAN 13 be careful to set right values for each barcode type
    //'value'     => str_pad("{$model->serialnum}", 12, "0", STR_PAD_LEFT), // eg if using a model
    'type'      => 'ean13',         // supported types: ean8, ean13, upc, std25, int25, code11, code39, code93, 
                                    //                  code128, codabar, msi, datamatrix
];
echo BarcodeGenerator::widget($optionsArray);
?>

References:

Mermaid JS support

Edit asset references in @app/assets/AppAsset.php:

<?php
namespace app\assets;
 
use yii\web\AssetBundle;
 
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        'lib/mermaid/mermaid.min.js',  // Add support for Mermaid JS
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

Add mermaid code to a view. Eg: Flowchart sample:

<div class='mermaid'>
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
</div>    
Yii2 Shopping Cart