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

[extension] koperdog/yii2-treeview

$
0
0

TreeView widget

  1. Installation
  2. Usage

Widget to display the nested sets tree as a grid

Based on GridView

PackagistPackagist VersionPHP from Packagist

preview

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist koperdog/yii2-treeview "*"

or add

"koperdog/yii2-treeview": "*"

to the require section of your composer.json file.

Usage

Add to your model field: `php public $children = null; `

Has the same settings as GridView.
echo koperdog\yii2treeview\TreeView::widget([
	'dataProvider'  => $dataProvider,
	//'depthPrefix' => ' — ', //see Additional options
	//'depthRoot'   => 1, //see Additional options
	//'collaplse'   => true, //see Additional options
	'columns' => [
	  'id',
	  'name',
	  'created_at:datetime',
	  // ...
	],
    ]);
The column classes the same as GridView
['class' => '\koperdog\yii2treeview\base\CheckboxColumn'],
['class' => '\koperdog\yii2treeview\base\ActionColumn'],
['class' => '\koperdog\yii2treeview\base\RadioButtonColumn'],
['class' => '\koperdog\yii2treeview\base\SerialColumn'],
Additional options ##### depthPrefix - Prefix that displays depth (default " — ") ##### depthRoot - Offset from the root (default 0) ##### collaplse - if true, it will add the class "closed" to the node elements, and "tree-collapse" to the root of the tree (default false)

[extension] error-tracker/yii2-log-target

$
0
0

Error Tracker Yii2 Log Target

  1. Who is this for?
  2. Installation
  3. Configuration
  4. Using Yii2's log functions
  5. Disabling
  6. Contributing
  7. Credits

Who is this for?

This is for Yii2 developers that need to integrate their applications with Error Tracker. This extension uses the Yii2 log component to send errors and warnings direct to Error Tracker.

Installation

Install this package with composer.

composer require error-tracker/yii2-log-target

Configuration

To configure the log target in your application, add the below config. Whenever there is a server side error this will be added to the file log as it normally would. Additionally this will be sent to the error tracker dashboard, for easy searches, alerts and other handy tools.

'log' => [
    'targets' => [
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['error', 'warning'],
        ],
        [
            'class' => 'ErrorTracker\Yii2\ErrorTrackerTarget',
            'levels' => ['error', 'warning'],
            'app_key' => 'YOUR_APP_KEY'
        ],
    ],
],

When an error is reported onto Error Tracker, it will be saved with a Reference. This is your user's session id, and is also the id you can use to trace the error in your file log where you can find more information about that error error.

Using Yii2's log functions

You can use Yii2's error and warning methods to log errors to Error Tracker without throwing exceptions. This will still be logged in the same way, and will additionally and automatically sent if you have the log target configured. The below code will send an error without throwing an exception.

try {
    $this->willBreake();
} catch (\Exception $e) {
    Yii::error($e->getMessage(), $e->getName());
}

Disabling

Disable your log target by using the method documented by Yii2. Optionally disable the target by setting the enabled property in the configuration. The below config only enables the logger if your application is in a production environment.

[
    'class' => 'ErrorTracker\Yii2\ErrorTrackerTarget',
    'levels' => ['error', 'warning'],
    'app_key' => 'YOUR_APP_KEY',
    'enabled' => YII_ENV_PROD,
],

Contributing

Getting set up

Clone the repo and run composer install. Then start hacking!

Testing

All new features of bug fixes must be tested. Testing is with phpunit and can be run with the following command.

composer run-script test
Coding Standards

This library uses psr2 coding standards and squizlabs/php_codesniffer for linting. There is a composer script for this:

composer run-script lint
Pull Requests

Before creating a pull request with your changes, the pre-commit script must pass. That can be run as follows:

composer run-script pre-commit

Credits

This package is created and maintained by Practically.io

[extension] luyadev/luya-mailjet

$
0
0

LUYA Logo

LUYA Mailjet

  1. Installation
  2. Basic Send Mail
  3. MJML to HTML

LUYA Build Status Total Downloads Latest Stable Version Test Coverage Maintainability

LUYA and Yii Framework integration for Mailjet service.

Contains:

  • Yii Framework BaseMailer for Transaction E-Mails trough API.
  • Interface for Subscription Mail Sync including CLI command for Synchronisation.
  • A PHP library to convert MJML content into Mailjet Passport json format.
  • LUYA Admin Module to convert MJML into HTML based on MJML.io API.
  • LUYA Active Window to retrieve informations about a given User E-Mail.
  • A Widget to subscribe to a List with double opt in (can be disabled).
  • SMS Sending helpers

Installation

Install the extension through composer:

composer require luyadev/luya-mailjet

Add to config:

[
    'components' => [
        'mailjet' => [
            'class' => 'luya\mailjet\Client',
            'apiKey' => '...',
            'apiSecret' => '...',
        ],
        'mailer' => [
            'class' => 'luya\mailjet\Mailer',
        ],
    ]
]

Basic Send Mail

Sending transactional E-Mail:

Yii::$app->mailer->compose()
    ->setFrom('from@domain.com')
    ->setTo('to@domain.com')
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('<b>HTML content</b>')
    ->send();

Send a transactional E-Mail based on the Template id stored in Mailjet:

$mail = $this->app->mailer->compose()
    ->setTemplate(484590)
    ->setVariables(['lastnbame' => 'Lastname Value'])
    ->setTo(['to@domain.com'])
    ->send();

MJML to HTML

With version 1.3 of LUYA Mailjet library there is an admin module you can configured in order to parser MJML into HTML, therefore add the module to your configuration and provide mjml.io API keys:

'modules' => [
    'mailjetadmin' => [
        'class' => 'luya\mailjet\admin\Module',
        'mjmlApiApplicationId' => 'ApplicationIdFromMjml.io',
        'mjmlApiSecretKey' => 'ApplicationSecretFromMjml.io',
    ]
]

Afterwards you can retrieve and render the HTML of MJML template with:

luya\mailjet\models\Template::renderHtml('slug', ['foo' => 'bar']);

[news] Yii 2.0.31

$
0
0

We are very pleased to announce the release of Yii Framework version 2.0.31. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.

Version 2.0.31 is a minor release of Yii 2.0 that fixes PHP 7.4 compatibility, a number of bugs and adds two important enhancements.

  • Yii 3-like DI container configuration was enhanced to allow configuring application core components.
  • RFC 7239 Forwarded header support for trusted proxies was added. It could be enabled through request configuration.

Additionally, basic and advanced application templates are now using Codeception 4.0.

Thanks to all Yii community members who contribute to the framework, translators who keep documentation translations up to date and community members who answer questions at forums.

There are many active Yii communities so if you need help or want to share your experience, feel free to join them.

A complete list of changes can be found in the CHANGELOG.

[extension] xandrkat/yii2-simply

$
0
0

yii2-simply

This extension is a simplification of HTML helper Yii Framework 2.0.

Html Class

This class extends the Yii Html Helper . The helper functions available in this class are:

  • Html::bebin{anyTag}([\'whithot class as key\']),
  • Html::end{anyTag}()
  • Html::{anyTag}('content', [\'whithot class as key\'])
As
<?=\xandrkat\simply\Html::beginDiv(['container']).'any text'.\xandrkat\simply\Html::endDiv()?>
// result <div class="container">any text</div>

// or
<?=\xandrkat\simply\Html::beginDiv(['class' => 'container']).'any text'.\xandrkat\simply\Html::endDiv()?>
// result <div class="container">any text</div> 

// or
<?=\xandrkat\simply\Html::beginDiv(['container', 'class' => 'bg-primary']).'any text'.\xandrkat\simply\Html::endDiv()?>
// result <div class="container bg-primary">any text</div> 

// or simple tag
<?=\xandrkat\simply\Html::p('any content', ['text-center'])?>
// result <p class="text-center">any content</p>

// or
<?=\xandrkat\simply\Html::p('any content', ['class' => 'text-center'])?>
// result <p class="text-center">any content</p>

// or
<?=\xandrkat\simply\Html::p('any content', ['text-success', 'class' => 'text-center'])?>
// result <p class="text-success text-center">any content</p>
Or
use xandrkat\simply;

<?=Html::beginDiv(['container']).'any text'.Html::endDiv()?>
// result <div class="container">any text</div>

// or
<?=Html::beginDiv(['class' => 'container']).'any text'.Html::endDiv()?>
// result <div class="container">any text</div> 

// or
<?=Html::beginDiv(['container', 'class' => 'bg-primary']).'any text'.Html::endDiv()?>
// result <div class="container bg-primary">any text</div> 

// or simple tag
<?=Html::p('any content', ['text-center'])?>
// result <p class="text-center">any content</p>

// or
<?=Html::p('any content', ['class' => 'text-center'])?>
// result <p class="text-center">any content</p>

// or
<?=Html::p('any content', ['text-success', 'class' => 'text-center'])?>
// result <p class="text-success text-center">any content</p>
Attention

Html::a(), Html::img() etc. inherits yii\helpers\Html

License

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

[extension] koperdog/yii2-sitemanager

$
0
0

Settings Module

  1. Installation
  2. Usage

Settings for multilanguage, multidomain site

PackagistPackagist Version

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist koperdog/yii2-sitemanager "*"

or add

"koperdog/yii2-sitemanager": "*"

to the require section of your composer.json file.

Add the component to your common config:

...
'components' => [
    // ...
    'settings' => [
        'class' => 'koperdog\yii2sitemanager\components\Settings',
    ],
    // ...
]
... 

also you should add component to bootstrap config:

...
'bootstrap' => ['settings'],
...

and add the module to backend config:

'modules' => [
    'manager' => [
        'class' => 'koperdog\yii2sitemanager\Module',
    ],
],

Then start the migration (console): `php php yii migrate --migrationPath=@vendor/koperdog/yii2-sitemanager/migrations `

Usage

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

autoloaded settings: `php \Yii::$app->params['setting_name']; `

If you are not sure if the setting is autoload: `php \Yii::$app->settings->get('setting_name'); `

CRUD and URL config #### CRUD settings: go to /manager #### CRUD domains: go to /manager/domains #### CRUD languages: go to /manager/languages also, if you want use standart CRUD, you can add to Url rule config: ```php // ... 'rules' => [ 'manager' => 'manager/default/index', 'manager//' => 'manager//', 'manager/' => 'manager//index', 'manager/' => 'manager/default/', ], // ... ```

[news] Gii extension 2.1.3 released

$
0
0

We are very pleased to announce the release of Gii extension version 2.1.3.

This release fixes issue with RTL naming for foreign keys such as id_user that was causing problems in generated code.

Also, it improves some aspects of generated code. float types are now recognized and generated and annotations for nullable types are now there:

/**
 * @property string|null $car_number
 */

See the CHANGELOG for details.

[extension] mehulpatel/vspl

$
0
0

mehulpatel/vspl

  1. Installation
  2. Usage

Yii2 audit record and database changes details

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist mehulpatel/vspl:"dev-master"

or

php composer.phar require --prefer-dist mehulpatel/vspl:"dev-master"

or add

"mehulpatel/vspl": "dev-master"

to the require section of your composer.json file.

Migration or Table
you need to import "audit_entry.sql" directly in your DB.
Module

Add Audit Entry module in your config file

....
'modules' => [
    ......
    'auditlog' => [
                'class' => 'mehulpatel\mod\audit\AuditEntryModule'
    ],
    ......
],
....
Component

Add DateTimeHelper components in your config file

....
'components' => [
    ......
    'dateTimeConversion' => [
                'class' => 'mehulpatel\mod\audit\components\DateTimeHelper'
    ],
    ......
],
....

Usage

Use get audit log activities or records, attached "AuditEntryBehaviors" with your models as belows:

use mehulpatel\mod\audit\behaviors\AuditEntryBehaviors;
use yii\db\ActiveRecord;

class User extends ActiveRecord {

    public function behaviors(){
        return [ 
            ....
            'auditEntryBehaviors' => [
                'class' => AuditEntryBehaviors::class
             ],
             ....
        ];
    }
}

[extension] sjaakp/yii2-locator

$
0
0
  1. Yii2-locator
  2. Installation
  3. Usage
  4. Methods
  5. Properties
  6. Tile Names
  7. Geocoder Names
  8. Marker Types

Yii2-locator

Leaflet-wrapper for Yii2 PHP framework

Latest Stable Version Total Downloads License

This is a wrapper of the Leaflet JavaScript geomapping library for the Yii 2.0 PHP Framework. It's an Yii2 Widget that can be used to display geographical data stored in an ActiveRecord, as well as to update it. Yii2-locator optionally has a search facility. It can use several providers, for the map tiles as well as for the geocoding service.

A demonstration of yii2-locator is here.

Installation

The preferred way to install yii2-locator is through Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-locator": "*"

Or run:

composer require sjaakp/yii2-locator "*"

You can manually install yii2-locator by downloading the source in ZIP-format.

GeoJSON

Yii2-locator handles data in GeoJSON format. Some databases store these directly. Others, like MySQL and MariaDB, use their own format for spatial data. My Yii2-spatial extension can be used to transform MySQL format to GeoJSON and vice versa. In that case, the model should be extended from sjaakp\spatial\ActiveRecord in stead of the usual yii\db\ActiveRecord.

Usage

A typical usage scenario is like this: suppose we have a database table with some geographical data, let's say the table tower. If we use MySQL or MariaDB, the model Tower is extended like this:

class Tower extends sjaakp\spatial\ActiveRecord    {
    public static function tableName()
    {
        return 'tower';
    }
    // ...
}    

The table tower has, among others, the following fields:

  • location: POINT the location of the tower,
  • mapcenter: POINT the center of the map,
  • mapzoom: int the zoom level of the map.
View

In a yii2 view, displaying a map of a tower is simple as this:

<?php
use sjaakp\locator\Locator;
/**
 * @var app\models\Tower $model
 */
?>
...
<?php
    $map = Locator::begin([
        'height' => 480,
        // ... other options ...
    ]);
    
    $map->modelCenter($model, 'mapcenter'); // set the map's center
    
    $map->modelZoom($model, 'mapzoom'); // set the map's zoom level

    $map->modelFeature($model, 'location'); // place a marker at the tower's location

    Locator::end();
?>
...
Index

Displaying a map with all the towers in, say, the index view, can be accomplished with:

<?php
use sjaakp\locator\Locator;
/**
 * @var yii\data\ActiveDataProvider $dataProvider
 */
?>
...
<?php 
    $map = Locator::begin([
        'leafletOptions' => [
            'center' =>  [48.8, 2.3],   // Paris
            'zoom' => 5,
            // ... more options ...
        ],
    ]);

    $map->modelFeatures($dataProvider, 'location'); // provide the tower locations

    Locator::end();
?>
...
Active Locator

In a create or update view, Locator can be used in a form:

<?php
use yii\widgets\ActiveForm;
use sjaakp\locator\Locator;
/**
 * @var app\models\Tower $model
 */
?>
...
<?php $form = ActiveForm::begin(); ?>
...
<?php
    $map = Locator::begin([
        // ... Locator options ...
    ]);
    
    $map->activeCenter($model, 'mapcenter'); // allow the map's center to be chenged

    $map->activeZoom($model, 'mapzoom'); // allow the map's zoom level to be changed

    $map->activeMarker($model, 'location'); // allow the model's location to be changed

    $map->finder(); // add an interactive Search control to the map

    Locator::end();
?>
...
<?php ActiveForm::end(); ?>
...

Methods

  • tileLayer($data) - Add a tile to the map. $data: string|array: tile provider name, or name with options. See Tile names. Return: $this.
  • center($lat, $lng = null) - Set the center of the map. $lat and $lng are the latitude and longitude, float. $lat can also be an array [<lat>, <lng>]. Return: $this.
  • modelCenter($model, $attribute) - Set the center of the map to the value of $attribute in $model. This should be a GeoJSON Feature. Return: $this.
  • activeCenter($model, $attribute) - Create an ActiveField for the center of the map, coupled to the value (a GeoJSON Feature) of $attribute in $model. Return: $this.
  • zoom($z) - Set the zoom level of the map. $z: integer. Return: $this.
  • modelZoom($model, $attribute) - Set the zoom level of the map to the value of $attribute in $model. Return: $this.
  • activeZoom($model, $attribute) - Create an ActiveField for the zoom level of the map, coupled to the value of $attribute in $model. Return: $this.
  • feature($feature) - Add a GeoJSON Feature to the map. Return: $this.
  • modelFeature($model, $attribute) - Add the value of $attribute in $model as a GeoJSON Feature to the map. Return: $this.
  • modelFeatures($dataProvider, $attribute) - Add multiple GeoJSON features to the map, provided by ActiveDataProvider $dataProvider, using attribute $attribute. Return: $this.
  • marker($lat = null, $lng = null, $options = [ ]) - Add marker to the map. Return: $this.

    • If $lat == null: marker appears at the first click point on the map.
    • If $lat and $lng are floats: these are the latitude and longitude.
    • If $lat is an array: [<latitude>, <longitude>].

    $options Options for the marker:

    • 'type': the type of the marker. If not set: 'Marker'.
    • Other options are passed to the marker's constructor.
  • modelMarker($model, $attribute, $options = [ ]) - Set the location of the marker to the value (a GeoJSON Feature) of $attribute in $model. Return: $this.
  • activeMarker($model, $attribute, $options = [ ]) - Create an ActiveField for the marker location, coupled to the value of $attribute in $model. Return: $this.
  • geocoder($options) - Set the geocoder of the map. Return: $this.

    • $options is string: the [name](#geocoder names) of the geocoder provider.
    • $options is array: first item is name, rest are geocoder options.
  • finder($geocoder = null, $position = 'topright') - Add a Search Control, using $geocoder, to the map, with specified position. Return: $this.
  • getVar() - Get the name of the JavaScript variable assigned to the Leaflet map. For advanced uses.

Locator is an Yii2 Widget, so it inherits all of its methods.

Chainable

Most of Locator's methods return this, so they are chainable. This means that the absolute minimum code to display a map in a view would be something like:

<?php
use sjaakp\locator\Locator;

...
<?php
    Locator::begin([
        // ... options ...
    ])->modelCenter($model, 'mapcenter')
        ->modelZoom($model, 'mapzoom')
        ->modelFeature($model, 'location')
        ->end();
?>
...

Properties

  • $height int|string|false Height of the Locator element. If int in pixels, if string any other valid CSS-value. If false, the height is not set. Notice that in that case the height must be set with some other means, otherwise the map will have a height of zero, and be invisible. Default: 400.
  • $tile string|array Name or configuration of the first tile layer. Default: 'OpenStreetMap'.
  • $marker array Type and options for the default marker. Default: [ 'type' => 'DotMarker' ].
  • $options array HTML options of the map container. Use this to explicitly set the ID. Default: [ ] (empty array).
  • $leafletOptions array JavaScript options of the map. Default: [ ] (empty array).
  • $cluster null|true|array Options for MarkerClusterer. If null: no clustering. If true: clustering with default options. Default: null.
  • $popup null|true|array Options for popups. If null: no popups. If true: popups with default options. Default: null.
  • $scale null|int Display a Scale Control on the map. Can be null (no Scale Control), SCALE_METRIC, SCALE_IMPERIAL or SCALE_BOTH. Default: SCALE_METRIC.
  • $urlTemplate string URL template used when marker is clicked. If not set, nothing happens. If $popup is set, a popup is shown with contents from the resulting URL. Otherwise a jump is performed to the URL. '{xxx}' is replaced by the Marker option with the name 'xxx'. Typical use: $urlTemplate = 'view/{id}'. Default: null.
  • $fly bool Whether to use 'fly-animation' when a Marker is placed after find.
  • $tileNamespace string Namespace of the Tile* classes, defining the tile layers. Use this to add your own tile layer.

Locator is an Yii2 Widget, so it inherits all of its properties.

Tile Names

Locator retrieves its map tiles from a tile provider or map provider. Tiles are identified by the name of the provider, or by an array with the name as the first item and options in the rest of the array. This value is used in the $tile property, and in the tileLayer() method. A map can have more than one tile layers, which make sense if they are partly transparent, like the tiles from OpenSeaMap.

Some providers offer tiles in a few variants. They are indicated with a suffix to the provider name, seperated by a dot. For example: 'OpenStreetMap' and 'OpenStreetMap.BlackAndWhite'.

Commercial tile providers expect some sort of API key. This should be added to the options. Often, an API key can be obtained free of charge for small or non-commercial applications.

Out of the box, Locator supports several tile providers. They each have a PHP class file in the src/tiles directory. Currently, the following tile providers are supported (there may be more in the future):

NameVariantsRequired option
OpenStreetMapBlackAndWhite, HOT
OpenMapSurferRoads, Hybrid, AdminBounds, ContourLines, Hillshade
OpenTopoMap
OpenSeaMap
Wikimedia
CartoLight, Dark, Voyager
StamenToner, TonerBackground, TonerHybrid, TonerLines, TonerLabels, TonerLite, Watercolor, Terrain, TerrainBackground, TerrainLabels
EsriWorld
Herelots (see TileHere.php) [ 'apiKey' => '...' ]
TomTomBasic, Hybrid, Labels[ 'key' => '...' ]
Kadaster (Netherlands only)grijs, pastel
Amsterdamlight, zw

If $tile is not set, Locator uses tiles from OpenStreetMap.

Geocoder Names

Locator's Search functionality uses information from a geocoding service. The service is set by the first parameter of the finder() method. This can be a string which is the name of the geocoding service, or an array with the name as first item, followed by options.

Generally, there will be no options, apart from the API key some providers expect. Other options may be added.

Currently, Locator supports the following providers (there may be more in the future):

NameRequired option
Nominatim, by OpenStreetMap
GeoNames[ 'username' => '...' ]
Here[ 'apiKey' => '...' ]
TomTom[ 'key' => '...' ]
Kadaster (Netherlands only)

Notice that some providers may stipulate that you should use their service only on map tiles of the same provider.

If you don't explicitly set a geocoder, Leaflet-search uses Nominatim.

Marker Types

In the property $marker, and in methods like marker(), modelMarker() etc. the marker type can be set. This is an array with [ 'type' => '<marker type>' ], supplemented with marker options (dependent on the type). For instance:

$map->marker = [ 'type' => 'Marker', 'opacity' => 0.5 ]

Apart from Leaflet's own Marker and CircleMarker, Locator sports two other markers:

DotMarker

A simple extension of CircleMarker. It has fixed radius and always has (at least) the class name 'dot-marker'. The default marker of Locator is a DotMarker.

SpriteMarker

A marker with a DivIcon. Use this to display FontAwesome markers like so:

$map->marker = [ 'type' => 'SpriteMarker', 'html' => '<i class="far fa-2x fa-dog"></i>' ]

[news] Yii 1.1.22 is released

$
0
0

We are very pleased to announce that Yii Framework version 1.1.22 is released. You can download it at yiiframework.com/download/.

This release is a release of Yii 1.1 that has reached maintenance mode and will, only receive necessary security fixes and fixes to adjust the code for compatibility with PHP 7 if they do not cause breaking changes. This allows you to keep your servers PHP version up to date in the environments where old Yii 1.1 applications are hosted and stay within the version ranges supported by the PHP team.

Yii 1.1.22 provides additional PHP 7 compatibility fixes and is compatible with PHP 7.4.

We recommend to use Yii 2.0 for new projects as well as introducing Yii 2.0 for developing new features in existing Yii 1.1 apps, as described in the Yii 2 guide. Upgrading a whole app to Yii 2.0 will, in most cases, result in a total rewrite so this option provides a way for upgrading step by step and allows you to keep old applications up to date even with low budget.

For the complete list of changes in this release, please see the change log. For upgrading, always make sure to read the upgrade instructions, however in this release there are no changes that require changes.

We would like to express our gratitude to all contributors who have spent their precious time helping improve Yii and made this release possible.

[news] Gii extension 2.1.4 released

$
0
0

We are very pleased to announce the release of Gii extension version 2.1.4.

This release fixes relational query getter documentation style and adds relation's phpdoc hints with target ActiveQuery class to model generator.

See the CHANGELOG for details.

[news] Debug extension 2.1.13 released

[extension] undefinedor/smart-rest

$
0
0

SmartRest

  1. Purpose
  2. Installation
  3. Usage

Purpose

The controller of `yii\rest\urlRule` must be set. So you have to set this property when you add a controller. This project sloved it.

Installation

The preferred way to install this extension is through Composer . composer require undefinedor/smart-rest

Usage


 'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true,
            'rules' => [
                ['class' => 'SmartRest\UrlRule'],
            ],
        ],

[news] Yii 2.0.32

$
0
0

We are very pleased to announce the release of Yii Framework version 2.0.32. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.

Version 2.0.32 is a minor release of Yii 2.0 that fixes 14 issues and makes two enhancements:

  • Path alias support was added to \yii\web\UploadFile::saveAs()
  • Added support for aria attributes to \yii\helpers\BaseHtml::renderTagAttributes()

Among bug fixes, there is one that changes HTTP response code when content type negotiation fails. Previously it was "415 Unsupported Media Type", now it is "406 Not Acceptable".

Additionally, there are adjustments in application templates. Advanced application template got updated Codeception configuration to match newer version used. Basic application template raised minimum PHP requirement to version 5.6.

Thanks to all Yii community members who contribute to the framework, translators who keep documentation translations up to date and community members who answer questions at forums.

There are many active Yii communities so if you need help or want to share your experience, feel free to join them.

A complete list of changes can be found in the CHANGELOG.

[extension] sjaakp/yii2-wordcount

$
0
0
  1. Yii2-wordcount
  2. Installation
  3. Using WordCount
  4. Totals

Yii2-wordcount

Word count behavior for Yii2

Latest Stable Version Total Downloads License

This is a word counting behavior for ActiveRecords in the Yii 2.0 PHP Framework. It counts the words in one or more designated attributes. The count(s) are exposed through new virtual attributes.

A demonstration of yii2-wordcount is here.

Installation

The preferred way to install yii2-wordcount is through Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-wordcount": "*"

Or run:

composer require sjaakp/yii2-wordcount "*"

You can manually install yii2-wordcount by downloading the source in ZIP-format.

Using WordCount

WordCount is a Behavior for an ActiveRecord. It has one property:

  • $attribute string|array The name of the attribute of wihich we want to count the words. Can also be an array of attribute names. Moreover, it can be an array with '<attrName>' => '<countAttrName>' elements.

If the count attribute name is not explicitly set in the $attribute array, the virtual count attribute is called '<attrName>_count' automatically.

Here is the simplest way to set up an ActiveRecord with WordCount:

namespace app\models;

use yii\db\ActiveRecord;
use sjaakp\wordcount\WordCount;

class Article extends ActiveRecord
{
    public static function tableName()
    {
        return 'article';
    }
    // ...
        
    public function behaviors()
    {
        return [
            [
                'class' => WordCount::class,
                'attribute' => 'bodytext'
            ],
            // ... other behaviors ...
        ];
    }
    // ...
}

Class Article will now have a new virtual attribute with the name 'bodytext_count'. It's value is an integer and it can be queried just like any other attribute:

$wordsCounted = $model->bodytext_count

A slightly more involved way to set up an Activerecord with WordCount would be:

 // ...     
 class Article extends ActiveRecord
 {
     // ...
         
     public function behaviors()
     {
         return [
             [
                 'class' => WordCount::class,
                 'attribute' => [
                    'bodytext' => 'textcount',
                    'title' => 'titlecount'
                 ]
             ],
             // ... other behaviors ...
         ];
     }
     // ...
 }

It gives two new virtual attributes, named 'textcount' and 'titlecount'.

Notice that WordCount uses the PHP function str_word_count(). This is not the most perfect way to count words, so you should consider the results as no more than good approximations.

Totals

Totals is a helper class with one method:

public static function count($query, $attribute)

This static function returns the total of $attribute values in the ActiveRecords found by ActiveQuery $query. If $attribute is a string, the return value will be an integer. If $attribute is an array of attribute names, count() will return an array with '<attr>' => <total> elements.

Usage example:

use sjaakp\wordcount\Totals;

$totals = Totals::count(Article::find(), [ 'titlecount', 'textcount' ]);

Notice that count() also works with non-virtual attributes. However, it would be much wiser to use ActiveQuery::sum() in that case.


[extension] mgrechanik/yii2-categories-and-tags

$
0
0

Active Record hierarchical categories (or tags) for Yii2 framework

  1. Table of contents
  2. Goal
  3. Demo
  4. Installing

Русская версия

Table of contents

Goal

This extension gives you the module with the next functionality:

  1. It connects `Active Recordmodels of one table to a tree according toMaterialized path` algorithm using this extension
  2. You can use your own `ActiveRecord` model with fields you need by inheriting it from base category model of this extension. Details
  3. This module follows approach of universal module
  4. In fact you will have a set of `Active Recordmodels connected into a tree withCRUD` operations with them at backend section

    • This module gives no frontend section since we are not aware of what will be put into category
    • It will also fit to serve for tags system (if they are organized hierarchically)
    • Functionality of `CRUD` pages provides a possibility to set up/change a position of each node in the tree to any valid position
    • The futher work with a category tree is meant by using Materialized path extension ! Example
    • The index page of viewing a categories tree assumes that all category needs to be displayed, without pagination or filtering

Demo

The functionality of backend section will look like: Functionality of category we get

Installing

Installing through composer:

The preferred way to install this extension is through composer.:

Either run composer require --prefer-dist mgrechanik/yii2-categories-and-tags

or add "mgrechanik/yii2-categories-and-tags" : "~1.0.0" to the require section of your composer.json

Migrations

If you do not need additional fields to category `Active Record` model (details) then the table for default category can be created by running:

php yii migrate --migrationPath=@vendor/mgrechanik/yii2-categories-and-tags/src/console/migrations
Setting the module up

As was mentioned before this module follows the approach of universal module, and since it gives you only backend pages when you set it up into your application specify the next `mode:php

'modules' => [
    'category' => [
        'class' => 'mgrechanik\yii2category\Module',
        'mode' => 'backend',
        // Other module settings
    ],
    // ...
],

Done. When you access ```/category``` page you will see all your categories in a form of a tree.

---

## Default AR category model of this extension  <span id="default-ar"></span> 

The **required** fields for category model are ```id, path, level, weight ``` (`id` is the **primary key**), 
they serve to saving tree position. The rest of the fields are ones you need.

If you are satisfied with only one additional text field - ```name``` - then this extension provides
[Category](https://github.com/mgrechanik/yii2-categories-and-tags/blob/master/src/models/Category.php) model which is set as the default category model of the module.

The work precisely with it is shown at [demo](#demo) above.


---

## Using your own AR model  <span id="custom-ar"></span>   

If having one additional ```name``` field [default](#default-ar) category model gives is not enough 
there is a way to use your own model with fields you need which will serve as a category model.

To do this you need to follow the next steps:

#### А) Setting up your AR model <span id="custom-ar-a"></span>

1) Generate the class of your AR model starting from table created by migration similar to [Category model migration](https://github.com/mgrechanik/yii2-categories-and-tags/blob/master/src/console/migrations/m180908_094405_create_category_table.php). The main point here are [required](#default-ar) fields

2) Change the code of your AR model exactly like we did the same with [Category](https://github.com/mgrechanik/yii2-categories-and-tags/blob/master/src/models/Category.php) model: 
* change the table name
* make it to be inherited from ```BaseCategory``` class
* Set up your additional fields in ```rules(), attributeLabels()```

3) Set up your module to use this category model by using it's ```$categoryModelClass``` property

4) If your model does not have ```name``` field you need to set up [```$indentedNameCreatorCallback```](#indented-name) module property

#### B) Setting up your category form model <span id="custom-ar-b"></span>

AR model and form model are separated so the steps similar to **A)** need to be performed to your form model.

1) Create your form model starting from [CategoryForm](https://github.com/mgrechanik/yii2-categories-and-tags/blob/master/src/ui/forms/backend/CategoryForm.php). 
In the default form we added only one field - ```name``` but you need to add your own. Do not forget about inheritance from ```BaseCategoryForm```

2) Set up your module to use this category form model by using it's ```$categoryFormModelClass``` property

#### C) Setting up views <span id="custom-ar-c"></span>

This module has an opportunity to set up [which views to use](#setup-views).

The ones of them with information which vary needs to be copied, changed as needed and set up to module.

#### Ready to use examples of this module variations <span id="custom-ar-examples"></span>

Nowadays there are the next variations of this module:
* [SEO categories](https://github.com/mgrechanik/yii2-seo-categories)

---

## Module settings <span id="settings"></span>

[Setting up](#setup) the module into application we can use it's next properties:

#### ```$categoryModelClass``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Which category AR model class to use

#### ```$categoryFormModelClass``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Which category form model class to use

#### ```$indentedNameCreatorCallback``` <span id="indented-name">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Callback which will create the label of the category at the categories page
considering indent needed to show categories as a tree

#### ```$categoryIndexView```, ```$categoryCreateView```, ```$categoryUpdateView```, ```$categoryFormView```, ```$categoryViewView``` <span id="setup-views"></span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- The corresponding **views** for module to use. 
For it's format look into [documentation](https://www.yiiframework.com/doc/api/2.0/yii-base-view#render()-detail)

#### ```$redirectToIndexAfterCreate``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to redirect to the categories page after new element has been created.  
```True``` by default. With ```false``` the redirect will be to category view page

#### ```$redirectToIndexAfterUpdate``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Similar to the previous property but for updation task

#### ```$validateCategoryModel``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to validate category model before saving.  
Default ```false``` when we consider that the validation form performes is enough

#### ```$creatingSuccessMessage```, ```$updatingSuccessMessage```, ```$deletingSuccessMessage``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- The texts of flash messages.  
If you change them do not forget about their translations in the ```yii2category``` source


---

## Example of displaying a categories tree at frontend <span id="frontend-output"></span>

If you need to output your categories tree into any template just run:
```php
use mgrechanik\yiimaterializedpath\ServiceInterface;
// This is our default category model:
use mgrechanik\yii2category\models\Category;
use mgrechanik\yiimaterializedpath\widgets\TreeToListWidget;

// get the trees managing service
$service = \Yii::createObject(ServiceInterface::class);
// Get the element relevant to who we build the tree.
// In our case it is the Root node
$root = $service->getRoot(Category::class);
// Build the tree from descendants of the Root node
$tree = $service->buildDescendantsTree($root);
// Print at the page
print TreeToListWidget::widget(['tree' => $tree]);

You will see the next tree:

  • Laptops & PC
    • Laptops
    • PC
  • Phones & Accessories
    • Smartphones
      • Android
      • iOS
    • Batteries

[extension] mgrechanik/yii2-seo-categories

$
0
0

Active Record hierarchical SEO categories and tags for Yii2 framework

  1. Table of contents
  2. Goal
  3. or `slug` fields and they will not appear in the web form of creating/editing SEO category
  4. Installing

Русская версия

Table of contents

Goal

This extension gives you a variation of categories module, in which the opportunity to create any your own `Active Record` category models was given.

We suggest that when creating pages at frontend to display associated content of the category (or tag) we would need to manage SEO information of such category page.

Respectively we add next fields to our SEO category `Active Record` model:

  • 
    
  • 
    
  • 
    
  • 
    
  • 
    
  • 
    

With all this in module's settings you may choose not to use `meta_other`

or `slug` fields and they will not appear in the web form of creating/editing SEO category

Installing

Installing through composer:

The preferred way to install this extension is through composer.:

Either run composer require --prefer-dist mgrechanik/yii2-seo-categories

or add "mgrechanik/yii2-seo-categories" : "~1.0.0" to the require section of your composer.json

Migrations

This extension comes with two migrations:

  • the first creates SEO categories table with all indexes needed
  • the second creates unique index for `slug` field

You can run both of them:

php yii migrate --migrationPath=@vendor/mgrechanik/yii2-seo-categories/src/console/migrations

, or when you do not use `slug` field run only the first migration:

php yii migrate 1 --migrationPath=@vendor/mgrechanik/yii2-seo-categories/src/console/migrations
Setting the module up

As was mentioned in the basic categories module, this module follows the approach of universal module, and since it gives you only backend pages when you set it up into your application specify the next `mode:php

'modules' => [
    'seocategory' => [
        'class' => 'mgrechanik\yii2seocategory\Module',
        'mode' => 'backend',
        // Other module settings
    ],
    // ...
],

Done. When you access ```/seocategory``` page you will see all your SEO categories in a form of tree.

---

## Module settings <span id="settings"></span>

[Setting up](#setup) the module into application, along with all properties of the [base categories module](https://github.com/mgrechanik/yii2-categories-and-tags#settings), we can use it's next properties:

#### ```$useMetaOtherField = false``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to use ```other meta tags``` field

#### ```$useSlugField = true``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to use ```slug``` field. It is supposed to be unique

#### ```$slugPattern``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- When we use previous field in this property we set up regular expression of expected symbols 

#### ```$showTitleColumnAtIndexPage = true```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to display ```title``` field in the categories list grid

#### ```$showSlugColumnAtIndexPage = false``` 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Whether to display ```slug``` field in the categories list grid

[news] Twig extension 2.2.2 and 2.3.0 released

$
0
0

We are very pleased to announce two releases of Twig extension.

Version 2.2.2 fixes an issue with non-working HtmlHelperExtension, version 2.3.0 upgrades Twig to 2.7.x.

[extension] sjaakp/yii2-datepager

$
0
0

yii2-datepager

  1. Installation
  2. Using Datepager
  3. Classes
Paging on date values for Yii2

Latest Stable Version Total Downloads License

These classes enable database paging based on date values in the Yii 2.0 PHP Framework.

A demonstration of yii2-datepager is here.

Installation

The preferred way to install yii2-datepager is through Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-datepager": "*"

Or run:

composer require sjaakp/yii2-datepager "*"

You can manually install yii2-datepager by downloading the source in ZIP-format.

Using Datepager

Using Yii2 Datepager is easy. A minimum usage scenario would look like the following. In EventController.php we would have something like:

<?php
use sjaakp\datepager\ActiveDataProvider;

class EventController extends Controller
{
	// ...

	public function actionIndex()    {
        $dataProvider = new ActiveDataProvider([
            'query' => Event::find(),
            'dateAttribute' => 'date'
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

	// ... more actions ...
}

The corresponding view file index.php could look something like:

<?php
use sjaakp\datepager\DatePager;
?>

<?= DatePager::widget([
    'dataProvider' => $dataProvider
]) ?>

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'date',
        'title',
        // ... more columns ...
    ],
]); ?>

Classes

ActiveDataProvider

This is an extension from its Yii-counterpart in yii\data, and can be used in the same way. It is important to set attribute $dateAttribute.

$dateAttribute

string Set this to the name of the attribute which is used to define the pages. Must be set.

$interval

string Defines the interval of the pages. Must be set in a form PHP's DateInterval can understand. Default: 'P1Y' (one year).

$beginDate

string Date of the first Datepager page. If not set (default), Datepager determines this date itself. It can be set to any date within the range of the first page. Format: any PHP date format.

$endDate

string Date of the last Datepager page. If not set (default), Datepager determines this date itself. It can be set to any date within the range of the last page. Format: any PHP date format.

$dateParam

string The Datepager HTML parameter name. Default value: 'date'. Might be changed if there is a conflict with other functionality.

DatePager

This is the widget that renders the actual datepager. The attribute $dataProvider must be set.

$dataProvider

The Datepager ActiveDataProvider that this pager is associated with. Must be set.

$maxButtonCount

int The maximum number of page buttons rendered. Default: 10.

$labelFormat

null|string|callable Defines the format of the page label.

  • If null: DatePager determines the format based on the dataprovider's interval.
  • If string: a date format according to Yii's Fomrmatter::dateformat.
  • If callable: a function($page, $datePager), returning a string, where $page is a PHP DateTimeInterface.
$options

array HTML options for the datepager container tag. Default: [ 'class' => 'pagination' ], compatible with Bootstrap.

$buttonOptions

array HTML options for the datepager buttons. Default: [ 'class' => 'page-item' ], compatible with Bootstrap 4.

$linkOptions

array HTML options for the datepager links. Default: [ 'class' => 'page-link' ], compatible with Bootstrap 4.

$activePageCssClass

string CSS class of the active page. Default: 'active'.

$disabledPageCssClass

string CSS class of a disabled page. Default: 'disabled'.

$prevPageLabel, $nextPageLabel

'string' Text labels for the previous and next buttons, will not be HTML encoded. If false, the button will not be rendered. Defaults: '&laquo;' and '&raquo;'.

$firstPageLabel, $lastPageLabel

'string' Text labels for the first and last buttons, will not be HTML encoded. If false (default), the button will not be rendered.

All properties, except $dataProvider and $labelFormat are direct equivalents of their counterparts in Yii's LinkPager.

[news] Auth Client extension 2.2.7 released

Viewing all 2941 articles
Browse latest View live