Yii2: Posting Data via Link

This seems to be undocumented (or not so well documented) at the moment. Yii2 provides special supports which allows you to post data via clicking a link.

<?= Html::a('Text', 
    ['/controller/action'], [
    'data-method' => 'POST',
    'data-params' => [
        'param1' => 1,
        'param2' => 2,
    ],
]) ?>

Note:

  • Line 3: Specifying the method, eg ‘GET’, ‘POST’, ‘PUT’
  • Line 4: Data to be posted.

To get posted data in the action:

public function actionAction () {
    $param1 = Yii::$app->request->post('param1', null);
    $param2 = Yii::$app->request->post('param2', null);
}

WordPress: Extra content with Simple Fields

WordPress allows adding extra content to your post or page contents with custom fields. This is useful if the the content is simple text value. You can still use it for other types of data such as image and radio buttons. But it’d be nice if there’s a nice user interface to simplify the process, to allow different types of input and to validate the input.

Continue »

Yii2: Include View Specific JavaScript

To include JavaScript for specific action, either the JavaScript code or file is to be registered in view file.

Method 1: Register JavaScript File

Use registerJsFile().

$this->registerJsFile('@web/js/file.js', [
    'position' => View::POS_END,
]);

Note: optional position. values: POS_HEAD, POS_BEGIN, POS_END.

If order of the file is to be placed after some set of files, for example, css and js files defined in SomeAsset:

use frontend\assets\SomeAsset;
$this->registerJsFile('@web/js/file.js', [
    'depends' => SomeAsset::className(),
]);

Method 2: Register Javascript Code

Continue »

Yii2: Ajax Gridview

Want to navigate through the grids or trying to sort and filter data without waiting for the entire page to load?

You need yii\widgets\Pjax and wrap it around GridView.

In the view:

use yii\grid\GridView;
use yii\widgets\Pjax;
Pjax::begin();
echo GridView::widget([
....
]);
Pjax::end();

This will cause all actions within the Grid to run in Ajax mode, including links.

Continue »