A major version of yiisoft/auth standalone package was released.
In this version IdentityRepositoryInterface::findIdentityByToken()
was extracted into IdentityWithTokenRepositoryInterface
. Additionally, token type is now configurable.
More description and usage examples are available in readme.
]]>Created a new component for Yii2. The Open Graph component for your website
composer require umanskyi31/opengraph
or add
"umanskyi31/opengraph": "*"
to the require section of your composer.json file.
'components' => [
'opengraph' => [
'class' => 'umanskyi31\opengraph\OpenGraph',
],
// ...
]
You should add component to controller before rendering view.
Example:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
Add basic attributes:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getBasic()
->setUrl('https://umanskyi.com')
->setTitle('My_Article_Title')
->setDescription('My_Article_Description')
->setSiteName('My_Site_Name')
->setLocale('pl_PL')
->setLocalAlternate(['fr_FR', 'en_US'])
->render();
Add image attributes:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getImage()
->setUrl('https://umanskyi.com/logo.png')
->setAttributes([
'secure_url' => 'https://umanskyi.com/logo.png',
'width' => 100,
'height' => 100,
'alt' => "Logo",
])
->render();
If necessary, an array of images also possible to add the next code:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getImage()
->setUrl('https://umanskyi.com/logo.png')
->setAttributes([
'secure_url' => 'https://umanskyi.com/logo.png',
'width' => 100,
'height' => 100,
'alt' => "Logo",
])
->render();
$openGraph->getImage()
->setUrl('https://umanskyi.com/small_logo.png')
->setAttributes([
'secure_url' => 'https://umanskyi.com/small_logo.png',
'width' => 50,
'height' => 50,
'alt' => "small logo",
])
->render();
Add article attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getArticle()
->setAuthor(['http://examples.opengraphprotocol.us/profile.html'])
->setTag(['Test_TAG'])
->setSection('Front page')
->setPublishTime(new \DateTime('2010-10-11'))
->render();
Add audio attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getAudio()
->setAttributes([
'secure_url' => 'https://umanskyi.com/media/audio/250hz.mp3',
'type' => 'audio/mpeg'
])
->setUrl('https://d72cgtgi6hvvl.cloudfront.net/media/audio/250hz.mp3')
->render();
Add book attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getBook()
->setReleaseDate(new \DateTime('2011-10-10'))
->setTag(['Apple', 'New'])
->setAuthor(['http://umanskyi.com/profile.html'])
->setIsbn(1451648537)
->render();
Add music attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getMusic()
->setReleaseDate(new \DateTime('2016-01-16'))
->setDuration(236)
->setAttrAlbum([
'album:track' => 2
])
->setMusician([
'http://open.spotify.com/artist/1dfeR4HaWDbWqFHLkxsg1d',
'http://open.spotify.com/artist/1dfeR4HaWDbWqFirlsag1d'
])
->render();
Add profile attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getProfile()
->setGender('Male')
->setFirstName('Vlad')
->setLastName('Umanskyi')
->setUsername('vlad.umanskyi')
->render();
Add video attribute:
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->getVideo()
->setUrl('https://umanskyi.com/strobe/FlashMediaPlayback.swf')
->setAttributes([
'width' => 450,
'height' => 350,
'secure_url' => 'https://umanskyi.com/strobe/FlashMediaPlayback.swf',
'type' => 'application/x-shockwave-flash'
])
->setAdditionalAttributes([
'tag' => 'train',
'release_date' => '1980-10-02'
])
->render();
The current version also has a configuration Twitter Card
/**
* @var OpenGraph $openGraph
*/
$openGraph = Yii::$app->opengraph;
$openGraph->useTwitterCard()
->setCard('summary')
->setSite('https://umanskyi.com')
->setCreator('Vlad Umanskyi')
->render();
If you want to add own configuration or override some tag, you must implement umanskyi31\opengraph\Configuration and add to Yii container. Some example you can find here umanskyi31\opengraph\OpenGraphConfiguration
If you have any issue please let me know issue
]]>The preferred way to install this extension is through composer.
composer require sovngare/yii2-array-validator
Use class: sovngare\validators\ArrayValidator
Validate true if property "fields" will be array.
`
php
public function rules()
{
return [
['fields', 'required'],
['fields', ArrayValidator::class]
];
}
`
Validate true if status[code] key will be integer in the range 100 and 500.
`
php
public function rules()
{
return [
['fields', ArrayValidator::class, 'key' => 'status.code', 'rules' => [
['integer', 'min' => 100, 'max' => 500]
]]
];
}
`
By default key label is "Attribute". Model errors log:
`
json
{
"fields": [
"Attribute must be no less than 100."
]
}
To change label you must send param label:
php
public function rules()
{
return [
['fields', ArrayValidator::class, 'key' => 'status.code', 'rules' => [
['integer', 'min' => 100, 'max' => 500]
], 'label' => 'status_code']
];
}
Model errors log now:
json
{
"fields": [
"Status Code must be no less than 100."
]
}
`
Data from client:
phone:7087952412
fields[name]:Sovngare
fields[avatar]:(\yii\web\UploadedFile)
Model:
`
php
class TestModel extends Model
{
public $phone;
public $fields;
public function rules()
{
return [
[['phone', 'fields'], 'required'],
['fields', ArrayValidator::class, 'key' => 'name', 'rules' => [
['required'],
['string', 'length' => [4, 16]]
], 'label' => 'name'],
['fields', ArrayValidator::class, 'key' => 'avatar', 'rules' => [
['required'],
['image', 'maxSize' => 1024 * 1024 * 3]
], 'label' => 'avatar'],
];
}
}
Controller
php
public function actionIndex()
{
$model = new TestModel();
$model->attributes = Yii::$app->request->getBodyParams();
if (is_array($model->fields)) {
$model->fields['avatar'] = UploadedFile::getInstanceByName('fields[avatar]');
}
if (!$model->validate()) {
return $model->errors;
}
return $model->attributes;
}
`
Version 1.1.0 of yiisoft/http package was released.
ContentDispositionHeader
was introduced. It helps building Content-Disposition header that complies to RFC-6266 and works in majority of modern browsers:
$name = \Yiisoft\Http\ContentDispositionHeader::name();
$value = \Yiisoft\Http\ContentDispositionHeader::value(
\Yiisoft\Http\ContentDispositionHeader::INLINE,
'avatar.png'
);
$value = \Yiisoft\Http\ContentDispositionHeader::inline('document.pdf');
$value = \Yiisoft\Http\ContentDispositionHeader::attachment('document.pdf');
Also, Method::ANY
is now deprecated in favor of Method::ALL
.
More details could be found in the package README.
]]>Session package implements a session service, PSR-15 session middleware, and a flash message service which helps use one-time messages.
You can access session data through SessionInterface
.
/** @var \Yiisoft\Session\SessionInterface $session */
$myId = $session->get('my_id');
if ($myId === null) {
$session->set('my_id', 42);
}
In case you need some data to remain in session until read, such as in case with displaying a message on the next page,
FlashInteface
is your friend:
/** @var Yiisoft\Session\Flash\FlashInterface $flash */
// request 1
$flash->set('warning', 'Oh no, not again.');
// request 2
$warning = $flash->get('warning');
if ($warning !== null) {
// do something with it
}
]]>Another Yii3 family package is released. This time it is yiisoft/i18n
. The package provides common internationalization utilities and currently includes a Locale
class. It stores locale information created from BCP 47 formatted string. Can parse locale string, modify locale parts, form locale string from parts, and derive fallback locale.
$locale = new \Yiisoft\I18n\Locale('es-CL');
echo $locale->language(); // es
echo $locale->region(); // CL
$locale = $locale->withLanguage('en');
echo $locale->asString(); // en-CL
echo $locale->fallbackLocale()->asString(); // en
The package has 100% code coverage and 100% mutation score.
]]>Yii3 Asset bundle for the Bootstrap Icons
The package could be installed via composer:
composer require yiirocks/yii-bootstrap-icons
use YiiRocks\Yii\Bootstrap\Icons\Assets\BootstrapIconsAsset;
$assetManager->register([
BootstrapIconsAsset::class,
]);
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
]]>inline
/ˈɪnlʌɪn/
adjectiveincluded as part of the main text on a page, rather than in a separate section
This extension provides simple functions for Yii framework 3.0 applications to add Font Awesome Icons inline.
The package could be installed via composer:
composer require yiirocks/svg-inline-fontawesome
The default configuration will enable $svg
in any view.
echo $svg->fai('cookie');
Available options can be found in the documentation.
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
]]>inline
/ˈɪnlʌɪn/
adjectiveincluded as part of the main text on a page, rather than in a separate section
This extension provides simple functions for Yii framework 3.0 applications to add Bootstrap Icons inline.
The package could be installed via composer:
composer require yiirocks/svg-inline-bootstrap
The default configuration will enable $svg
in any view.
echo $svg->bootstrap('award');
Available options can be found in the documentation.
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
]]>inline
/ˈɪnlʌɪn/
adjectiveincluded as part of the main text on a page, rather than in a separate section
This extension provides simple functions for Yii framework 3.0 applications to add SVG Images inline.
The package could be installed via composer:
composer require yiirocks/svg-inline
It can be extended with Bootstrap Icons and/or Font Awesome Icons:
composer require yiirocks/svg-inline-bootstrap
composer require yiirocks/svg-inline-fontawesome
The default configuration will enable $svg
in any view.
echo $svg->file('@assets/image.svg');
Available options can be found in the documentation.
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
]]>First release of test support package was tagged. The package is intended to simplify the process of testing application elements that depend on PSR interfaces and is currently covering:
More interfaces are to be covered in the subsequent releases. Extensive documentation is available.
]]>Patch release of aliases package was tagged. It is fixing a bug with nested aliases and getAll()
.
Update does not require anything special. Just do composer update
.
A pre-release version 0.5.0 of Composer config plugin was tagged. The plugin takes care of assembling configuration from multiple sources as configured in composer.json
. That usually happens on composer update
or composer install
. Assembled configs are then used in the application cutting application bootstrap time significantly.
The plugin is still under development so there still could be configuration syntax changes.
]]>Imagine extension version 2.3.0 was released.
Image::thumbnail()
now accepts ImageInterface::THUMBNAIL_FLAG_UPSCALE
flag to allow thumbnail upscaling. Since this option is only supported in imagine/imagine v1.0.0 or later, support for older version was dropped.
See CHANGELOG for details.
]]>Queue extension version 2.3.1 was released.
This version fixes amqp-interop queue/listen signal handling and adds compatibilty with symfony/process 5.0.
Full changelog is available at GitHub.
]]>We are very pleased to announce the release of MongoDB extension version 2.1.11.
This version adds compatibility with PECL MongoDb 1.9.0 driver.
See the CHANGELOG for details.
]]>We are very pleased to announce the release of HTTP client extension version 2.0.13.
See the CHANGELOG for details.
]]>Debug extension version 2.1.16 was released.
See the CHANGELOG for details.
]]>We are very pleased to announce the release of Yii Framework version 2.0.40. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.
The release is mostly focused on fixing issues found since last release.
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.
]]>An Amazon S3 component for Yii2.
Yii2 AWS S3 uses SemVer.
Version 2.x requires PHP 7. For PHP less 7.0 use 1.x.
This project is a fork from the excellent project yii2-aws-s3 by frostealth and adnsio.
Upon their work, we add support for IAM role attached to the EC2, which you don't need to insert your credentials.
We will also add support for easier integration with your models, by adding a S3MediaTrait.
Run the Composer command to install the latest version:
`
bash
composer require bp-sys/yii2-aws-s3 ~2.0
`
Add the component to config/main.php
`
php
'components' => [
// ...
's3' => [
'class' => 'bpsys\yii2\aws\s3\Service',
'credentials' => [ // Aws\Credentials\CredentialsInterface|array|callable
'key' => 'my-key',
'secret' => 'my-secret',
],
'region' => 'my-region',
'defaultBucket' => 'my-bucket',
'defaultAcl' => 'public-read',
'defaultPresignedExpiration' => '+1 hour',
],
// ...
],
`
Credentials parameter is optional: if you plan to use IAM roles attached to your EC2 instance there is no need for credentials. Just remove this parameter. Just be cautious if you need those credentials, this may cause errors during execution.
/** @var \bpsys\yii2\aws\s3\Service $s3 */
$s3 = Yii::$app->get('s3');
/** @var \Aws\ResultInterface $result */
$result = $s3->commands()->get('filename.ext')->saveAs('/path/to/local/file.ext')->execute();
$result = $s3->commands()->put('filename.ext', 'body')->withContentType('text/plain')->execute();
$result = $s3->commands()->delete('filename.ext')->execute();
$result = $s3->commands()->upload('filename.ext', '/path/to/local/file.ext')->withAcl('private')->execute();
$result = $s3->commands()->restore('filename.ext', $days = 7)->execute();
$result = $s3->commands()->list('path/')->execute();
/** @var bool $exist */
$exist = $s3->commands()->exist('filename.ext')->execute();
/** @var string $url */
$url = $s3->commands()->getUrl('filename.ext')->execute();
/** @var string $signedUrl */
$signedUrl = $s3->commands()->getPresignedUrl('filename.ext', '+2 days')->execute();
/** @var \bpsys\yii2\aws\s3\Service $s3 */
$s3 = Yii::$app->get('s3');
/** @var \Aws\ResultInterface $result */
$result = $s3->get('filename.ext');
$result = $s3->put('filename.ext', 'body');
$result = $s3->delete('filename.ext');
$result = $s3->upload('filename.ext', '/path/to/local/file.ext');
$result = $s3->restore('filename.ext', $days = 7);
$result = $s3->list('path/');
/** @var bool $exist */
$exist = $s3->exist('filename.ext');
/** @var string $url */
$url = $s3->getUrl('filename.ext');
/** @var string $signedUrl */
$signedUrl = $s3->getPresignedUrl('filename.ext', '+2 days'); // Pass only one parameter to get expiration date from component defaults
/** @var \bpsys\yii2\aws\s3\interfaces\Service $s3 */
$s3 = Yii::$app->get('s3');
/** @var \bpsys\yii2\aws\s3\commands\GetCommand $command */
$command = $s3->create(GetCommand::class);
$command->inBucket('my-another-bucket')->byFilename('filename.ext')->saveAs('/path/to/local/file.ext');
/** @var \Aws\ResultInterface $result */
$result = $s3->execute($command);
// or async
/** @var \GuzzleHttp\Promise\PromiseInterface $promise */
$promise = $s3->execute($command->async());
Attach the Trait to the model with some media attribute that will be saved in S3:
class Person extends \yii\db\ActiveRecord
{
use \bpsys\yii2\aws\s3\traits\S3MediaTrait;
// ...
}
$image = \yii\web\UploadedFile::getInstance( $formModel, 'my_file_attribute' );
// Save image as my_image.png on S3 at //my_bucket/images/ path
// $model->image will hold "my_image.png" after this call finish with success
$model->saveUploadedFile( $image, 'image', 'my_image.png' );
// Get the URL to the image on S3
$model->getFileUrl( 'image' );
// Get the presigned URL to the image on S3
// The default duration is "+1 day"
$model->getFilePresignedUrl( 'image' );
// Remove the file with named saved on the image attribute
// Continuing the example, here "//my_bucket/images/my_image.png" will be deleted from S3
$model->removeFile( 'image' );
// Save my_image.* to S3 on //my_bucket/images/ path
// The extension of the file will be determined by the submitted file type
// This allows multiple file types upload (png,jpg,gif,...)
$model->saveUploadedFile( $image, 'image', 'my_image', true );
Yii2 AWS S3 is licensed under the MIT License.
See the LICENSE file for more information.
]]>We are very pleased to announce that Yii Framework version 1.1.23 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 and 8 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.23 adds support for PHP 8 and improves compatibility for PHP 7. It also adds support for PostgreSQL 12.
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 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.
We would like to express our gratitude to all contributors who have spent their precious time helping improve Yii and made this release possible.
]]>First version of cookies package released.
The package helps in working with HTTP cookies in a PSR-7 environment:
Set-Cookie
headers to responseAccording to our quality standards, it has full test coverag, high MSI score and type coverage.
Usage examples are available in package readme.
]]>'components' => [
'yandexXml' => [
'class' => dicr\yandex\xml\YandexXML::class,
'login' => 'ваш_логин',
'apiKey' => 'ваш_ключ_api'
]
];
use dicr\yandex\xml\YandexXML;
/** @var YandexXML $yandexXml получаем компонент */
$yandexXml = Yii::$app->get('yandexXml');
// создаем запрос
$request = $yandexXml->request([
'query' => 'Мой поисковый запрос'
]);
// выводим результаты поиска
foreach ($request->results as $res) {
echo 'Позиция: ' . $res['pos'] . "\n";
echo 'URL: ' . $res['url'] . "\n";
}
use dicr\yandex\xml\YandexXML;
/** @var YandexXML $yandexXml получаем компонент */
$yandexXml = Yii::$app->get('yandexXml');
echo "Расписание лимитов:\n";
foreach ($yandexXml->limitsSchedule as $item) {
echo date('d.m.Y H:i', $item['from']) . ' - ' . date('H:i', $item['to']) . ': ' . $item['count'] . "\n";
}
echo 'Текущий лимит зап./час: ' . $yandexXml->hourLimit . "\n";
echo 'Текущий лимит зап./сек: ' . $yandexXml->rpsLimit . "\n";
echo 'Задержка между запросами, сек: ' . $yandexXml->requestDelay . "\n";
]]>'components' => [
'telegram' => [
'class' => dicr\telegram\TelegramModule::class,
'botToken' => 'ваш токен'
]
];
use dicr\telegram\TelegramModule;
use dicr\telegram\request\SendMessage;
/** @var TelegramModule $module получаем модуль */
$module = Yii::$app->get('telegram');
/** @var SendMessage $request формируем запрос */
$request = $module->createRequest([
'class' => SendMessage::class,
'chatId' => 'XXXXXXXXXXXXX',
'text' => 'Проверка сообщения'
]);
// отправка сообщения
$response = $request->send();
Установить/удалить webhook можно из командной строки.
# установить webHook
/usr/bin/php yii.php telegram/command/webhook-set
# проверить webhook
/usr/bin/php yii.php telegram/command/webhook-info
# удалить webhook
/usr/bin/php yii.php telegram/command/webhook-delete
Для обработки обновлений через webhook нужно настроить функцию-обработчик в конфиге модуля:
use dicr\telegram\entity\Update;
use dicr\telegram\TelegramModule;
'components' => [
'telegram' => [
'class' => dicr\telegram\TelegramModule::class,
'botToken' => 'ваш токен',
'handler' => static function(Update $update, TelegramModule $module) {
// обработка обновлений от webhook
}
]
];
]]>'modules' => [
'sberbank' => [
'class' => dicr\sberbank\SberbankModule::class,
'userName' => 'user-api',
'password' => 'my-password'
]
];
/** @var SberbankModule $module */
$module = Yii::$app->getModule('sberbank');
/** @var RegisterPaymentRequest $request создаем запрос */
$request = $module->registerPaymentRequest([
'orderNumber' => $orderNumber,
//'amount' => 3982, // автовычисление
'returnUrl' => 'https://test.ru',
'orderBundle' => [
'cartItems' => [
'items' => [
[
'positionId' => 1,
'name' => 'Русская водка',
'code' => 'VODKA-777',
'price' => 1203,
'quantity' => ['value' => 1.255, 'measure' => 'л'] // чекушка 1.25 литров
//'amount' => 1509.765 ( 1510 копеек ) автовычисление с округлением
],
[
'positionId' => 2,
'name' => 'Пряная селедка',
'code' => 'СЕЛ-Д',
'price' => 1236, // 12.34 руб
'quantity' => ['value' => 2, 'measure' => 'шт'],
'amount' => 2472
],
]
]
]
]);
/** @var RegisterPaymentResponse $response отправляем запрос */
$response = $request->send();
/** @var string $orderId номер заказа в системе банка */
$orderId = $response->orderId;
// переадресуем посетителя на страницу оплаты
$response->redirect();
/** @var SberbankModule $module */
$module = Yii::$app->getModule('sberbank');
/** @var OrderStatusRequest $req создаем запрос */
$req = $module->orderStatusRequest([
'orderId' => $orderId
]);
/** @var OrderStatusResponse $res отправляем запрос */
$res = $req->send();
/** @var int $orderStatus стутс заказа */
$orderStatus = $res->orderStatus;
]]>Документация:
Клиент реализован в виде модуля, для обработки callback-запросов от банка.
В конфиге приложения настраиваем модуль оплаты частями. Основные настройки - это storeId
и password
.
[
'modules' => [
'payparts' => [
'class' => dicr\payparts\PayPartsModule::class,
'storeId' => '* мой storeId *',
'password' => '* мой password *',
// обработчик состояний платежей (опционально)
'callbackHandler' => static function(dicr\payparts\PayPartsResponse $response) {
Order::setPayed($response->orderId);
}
]
]
];
/** @var PayPartsModule $module получаем модуль оплат */
$module = Yii::$app->getModule('payparts');
// запрос на создание платежа
$request = $module->paymentRequest([
'orderId' => $orderId, // номер заказа в интернет-магазине
'merchantType' => PayParts::MERCHANT_TYPE_PP, // сервис "оплата частями"
'partsCount' => 2, // кол-во частей
'products' => [ // список товаров
['name' => 'Рулон бумаги', 'price' => 0.01, 'count' => 2],
['name' => 'Автомобиль', 'price' => 123, 'count' => 1],
['name' => 'Талоны на Интернет', 'price' => 123.123, 'count' => 3]
]
]);
// отправляем запрос и получаем токен
$response = $request->send();
echo 'Token: ' . $response->token . "\n";
echo 'Redirect URL: ' . $response->paymentUrl . "\n";
// переадресация покупателя на страницу оплаты
$response->redirectCheckout();
Если не установлен обработчик callback-оповещений банка, то состояние платежа можно получить дополнительным запросом:
// запрос состояния платежа
$request = $module->createStateRequest([
'orderId' => $orderId // номер заказа
]);
// проверяем состояние платежа
$response = $request->send();
echo 'PaymentState: ' . $response->paymentState . "\n";
Рабочий пример вызова реализован в тестах (директория tests).
]]>API: https://admin.p1sms.ru/panel/apiinfo
'modules' => [
'p1sms' => [
'class' => dicr\p1sms\P1SMSModule::class,
'apiKey' => 'XXXXXXXXXXX',
]
];
use dicr\p1sms\P1SMSModule;
/** @var P1SMSModule $module получаем модуль */
$module = Yii::$app->getModule('p1sms');
// создание запроса
$req = $module->smsRequest([
'phone' => '+71111111111',
'text' => 'Проверка',
]);
// отправка СМС
$req->send();
]]>API: see doc
'modules' => [
'novapay' => [
'class' => dicr\novapay\NovaPayModule::class,
'merchantId' => 'ваш_merchant_id',
// приватный ключ клиента указывается либо как путь к файлу (через file://, либо PEM-код)
'clientKey' => 'file://' . __DIR__ . '/client.key'
]
];
use dicr\novapay\NovaPayModule;
use dicr\novapay\request\FramesInitRequest;
use dicr\novapay\request\FramesInitResponse;use dicr\novapay\request\GetStatusRequest;
/** @var NovaPayModule $novaPay получаем модуль */
$novaPay = Yii::$app->getModule('novapay');
// запрос на создание платежа
$request = $novaPay->createRequest([
'class' => FramesInitRequest::class,
'amount' => 55.55,
'products' => [
[
'description' => 'Товар1',
'price' => 11.11,
'count' => 1
],
[
'description' => 'Товар2',
'price' => 22.22,
'count' => 2
]
],
'delivery' => [
'volumeWeight' => 0.01,
'weight' => 0.1
]
]);
/** @var FramesInitResponse $ret отправляем запрос */
$ret = $request->send();
echo 'Адрес для переадресации: ' . $ret->url . "\n";
// запрос на проверку состояние платежной сессии
$request = $novaPay->createRequest([
'class' => GetStatusRequest::class,
'sessionId' => $ret->sessionId
]);
$status = $request->send();
echo 'Статус: ' . $status . "\n";
]]>A minor version of strings package was released:
WildcardPattern
now could be turned off by passing a boolean flag.withEnding()
was added to WildcardPattern
. It is allowing to match ending of testing string only ignoring the beginning.More details could be found in the package CHANGELOG.
]]>Debug extension version 2.1.15 was released.
This release fixes a bug introduced in previous release.
See the CHANGELOG for details.
]]>We are very pleased to announce the release of Auth Client extension version 2.2.9.
This release fixes regression introduced in previous release.
See the CHANGELOG for details.
]]>We are very pleased to announce the release of MongoDB extension version 2.1.10.
This version adds compatibility with Yii 2.0.39 session and fixes yii\mongodb\file\Upload::addFile()
when uploading file with readonly permissions.
See the CHANGELOG for details.
]]>We are very pleased to announce the release of Redis extension version 2.0.14.
This version adds compatibility with Yii 2.0.39 session and fixes a bug with Connection::isActive()
returning false
for active connections.
See the CHANGELOG for details.
]]>\yii\mail\BaseMailer::useFileTransport is a great tool. If you activate it, all
emails sent trough this mailer will be saved (by default) on @runtime/mail
instead of being sent, allowing the devs to inspect thre result.
But what happens if we want to actually receive the emails on our inboxes. When
all emails are suppose to go to one account, there is no problem: setup it as
a param and the modify it in the params-local.php
(assuming advaced
application template).
The big issue arises when the app is supposed to send emails to different
accounts and make use of replyTo, cc and bcc fields. It's almost impossible try
to solve it with previous approach and without using a lot of if(YII_DEBUG)
.
Well, next there is a solution:
'useFileTransport' => true,
'fileTransportCallback' => function (\yii\mail\MailerInterface $mailer, \yii\mail\MessageInterface $message) {
$message->attachContent(json_encode([
'to' => $message->getTo(),
'cc' => $message->getCc(),
'bcc' => $message->getBcc(),
'replyTo' => $message->getReplyTo(),
]), ['fileName' => 'metadata.json', 'contentType' => 'application/json'])
->setTo('debug@mydomain.com') // account to receive all the emails
->setCc(null)
->setBcc(null)
->setReplyTo(null);
$mailer->useFileTransport = false;
$mailer->send($message);
$mailer->useFileTransport = true;
return $mailer->generateMessageFileName();
}
How it works? fileTransportCallback
is the callback to specify the filename that should be used to create the saved email on @runtime/mail
. It "intercepts" the send email process, so we can use it for our porpuses.
useFileTransport
useFileTransport
This way we both receive all the emails on the specified account and get them stored
on @runtime/mail
.
Pretty simple helper to review emails on Yii2 applications.
Originally posted on: https://glpzzz.github.io/2020/10/02/yii2-redirect-all-emails.html
]]>After getting lot's of error and don't know how to perform multiple images api in yii2 finally I get it today
This is my question I asked on forum and it works for me https://forum.yiiframework.com/t/multiple-file-uploading-api-in-yii2/130519
Implement this code in model for Multiple File Uploading
public function rules()
{
return [
[['post_id', 'media'], 'required'],
[['post_id'], 'integer'],
[['media'], 'file', 'maxFiles' => 10],//here is my file field
[['created_at'], 'string', 'max' => 25],
[['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['post_id' => 'id']],
];
}
you can add extension or any skiponempty method also
And this is my controller action where I prformed multiple file uploading
public function actionMultiple(){
$model = new Media;
$model->post_id = '2';
if (Yii::$app->request->ispost) {
$model->media = UploadedFile::getInstances($model, 'media');
if ($model->media) {
foreach ($model->media as $value) {
$model = new Media;
$model->post_id = '2';
$BasePath = Yii::$app->basePath.'/../images/post_images';
$filename = time().'-'.$value->baseName.'.'.$value->extension;
$model->media = $filename;
if ($model->save()) {
$value->saveAs($BasePath.$filename);
}
}
return array('status' => true, 'message' => 'Image Saved');
}
}
return array('status' => true, 'data' => $model);
}
If any query or question I will respond
]]>Logging is a very important feature of the application. It let's you know what is happening in every moment. By default, Yii2 basic and advanced application have just a \yii\log\FileTarget target configured.
To receive emails with messages from the app, setup the log component to email (or Telegram, or slack) transport instead (or besides) of file transport:
'components' => [
// ...
'log' => [
'targets' => [
[
'class' => 'yii\log\EmailTarget',
'mailer' => 'mailer',
'levels' => ['error', 'warning'],
'message' => [
'from' => ['log@example.com'],
'to' => ['developer1@example.com', 'developer2@example.com'],
'subject' => 'Log message',
],
],
],
],
// ...
],
The \yii\log\EmailTarget component is another way to log messages, in this case emailing them via the mailer
component of the application as specified on the mailer
attribute of EmailTarget
configuration. Note that you can also specify messages properties and which levels of messages should be the sent trough this target.
If you want to receive messages via other platforms besides email, there are other components that represents log targets:
Or you can implement your own by subclassing \yii\log\Target
]]>https://schema.org is a markup system that allows to embed structured data on their web pages for use by search engines and other applications. Let's see how to add Schema.org to our pages on Yii2 based websites using JSON-LD.
Basically what we need is to embed something like this in our pages:
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "Movie",
"name": "Avatar",
"director":
{
"@type": "Person",
"name": "James Cameron",
"birthDate": "1954-08-16"
},
"genre": "Science fiction",
"trailer": "../movies/avatar-theatrical-trailer.html"
}
</script>
But we don't like to write scripts like this on Yii2, so let's try to do it in other, more PHP, way.
In the layout we can define some general markup for our website, so we add the following snippet at the beginning of the@app/views/layouts/main.php
file:
<?= \yii\helpers\Html::script(isset($this->params['schema'])
? $this->params['schema']
: \yii\helpers\Json::encode([
'@context' => 'https://schema.org',
'@type' => 'WebSite',
'name' => Yii::$app->name,
'image' => $this->image,
'url' => Yi::$app->homeUrl,
'descriptions' => $this->description,
'author' => [
'@type' => 'Organization',
'name' => Yii::$app->name,
'url' => 'https://www.hogarencuba.com',
'telephone' => '+5352381595',
]
]), [
'type' => 'application/ld+json',
]) ?>
Here we are using the Html::script($content, $options) to include the script with the necessary type
option, and Json::encode($value, $options) to generate the JSON. Also we use a page parameter named schema
to allow overrides on the markup from other pages. For example, in @app/views/real-estate/view.php
we are using:
$this->params['schema'] = \yii\helpers\Json::encode([
'@context' => 'https://schema.org',
'@type' => 'Product',
'name' => $model->title,
'description' => $model->description,
'image' => array_map(function ($item) {
return $item->url;
}, $model->images),
'category' => $model->type->description_es,
'productID' => $model->code,
'identifier' => $model->code,
'sku' => $model->code,
'url' => \yii\helpers\Url::current(),
'brand' => [
'@type' => 'Organization',
'name' => Yii::$app->name,
'url' => 'https://www.hogarencuba.com',
'telephone' => '+5352381595',
],
'offers' => [
'@type' => 'Offer',
'availability' => 'InStock',
'url' => \yii\helpers\Url::current(),
'priceCurrency' => 'CUC',
'price' => $model->price,
'priceValidUntil' => date('Y-m-d', strtotime(date("Y-m-d", time()) . " + 365 day")),
'itemCondition' => 'https://schema.org/UsedCondition',
'sku' => $model->code,
'identifier' => $model->code,
'image' => $model->images[0],
'category' => $model->type->description_es,
'offeredBy' => [
'@type' => 'Organization',
'name' => Yii::$app->name,
'url' => 'https://www.hogarencuba.com',
'telephone' => '+5352381595',
]
]
]);
Here we redefine the schema for this page with more complex markup: a product with an offer.
This way all the pages on our website will have a schema.org markup defined: in the layout we have a default and in other pages we can redefine setting the value on $this->params['schema']
.
OpenGraph and Twitter Cards are two metadata sets that allow to describe web pages and make it more understandable for Facebook and Twitter respectively.
There a lot of meta tags to add to a simple webpage, so let's use TaggedView
This component overrides the yii\web\View
adding more attributes to it, allowing to set the values on every view. Usually we setup page title with
$this->title = $model->title;
Now, with TaggedView we are able to set:
$this->title = $model->title;
$this->description = $model->abstract;
$this->image = $model->image;
$this->keywords = ['foo', 'bar'];
And this will generate the proper OpenGraph, Twitter Card and HTML meta description tags for this page.
Also, we can define default values for every tag in the component configuration that will be available for every page and just will be overriden if redefined as in previous example.
'components' => [
//...
'view' => [
'class' => 'daxslab\taggedview\View',
'site_name' => '',
'author' => '',
'locale' => '',
'generator' => '',
'updated_time' => '',
],
//...
]
Some of this properties have default values assigned, like site_name
that gets Yii::$app->name
by default.
Result of usage on a website:
<title>¿Deseas comprar o vender una casa en Cuba? | HogarEnCuba, para comprar y vender casas en Cuba</title>
<meta name="author" content="Daxslab (https://www.daxslab.com)">
<meta name="description" content="Hay 580 casas...">
<meta name="generator" content="Yii2 PHP Framework (http://www.yiiframework.com)">
<meta name="keywords" content="HogarEnCuba, ...">
<meta name="robots" content="follow">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:description" content="Hay 580 casas...">
<meta name="twitter:image" content="https://www.hogarencuba.com/images/main-identifier_es.png">
<meta name="twitter:site" content="HogarEnCuba">
<meta name="twitter:title" content="¿Deseas comprar o vender una casa en Cuba?">
<meta name="twitter:type" content="website">
<meta name="twitter:url" content="https://www.hogarencuba.com/">
<meta property="og:description" content="Hay 580 casas...">
<meta property="og:image" content="https://www.hogarencuba.com/images/main-identifier_es.png">
<meta property="og:locale" content="es">
<meta property="og:site_name" content="HogarEnCuba">
<meta property="og:title" content="¿Deseas comprar o vender una casa en Cuba?">
<meta property="og:type" content="website">
<meta property="og:updated_time" content="10 sept. 2020 9:43:00">
]]>Hi. I had to split my article as max length was reached. Check my previous articles here (mainly the 1st one):
You will need MSSQL drivers in PHP. Programatically you can list them or test their presence like this:
var_dump(\PDO::getAvailableDrivers());
if (in_array('sqlsrv', \PDO::getAvailableDrivers())) {
// ... MsSQL driver is available, do something
}
Based on your system you have to download different driver. The differences are x64 vs x86 and ThreadSafe vs nonThreadSafe. In Windows I always use ThreadSafe. Explanation.
Newest PHP drivers are here.
Older PHP drivers here.
Once drivers are downloaded and extracted, pick one DLL file and place it into folder "php/ext". On Windows it might be for example here: "C:\xampp\php\ext"
Note: In some situations you could also need these OBDC drivers, but I am not sure when:
Now file php.ini must be modified. On Windows it might be placed here: "C:\xampp\php\php.ini". Open it and search for rows starting with word "extension" and paste there cca this:
extension={filename.dll}
// Example:
extension=php_pdo_sqlsrv_74_ts_x64.dll
Now restart Apache and visit phpinfo() web page. You should see section "pdo_sqlsrv". If you are using XAMPP, it might be on this URL: http://localhost/dashboard/phpinfo.php.
Then just add connection to your MSSQL DB in Yii2 config. In my case the database was remote so I needed to create 2nd DB connection. Read next chapter how to do it.
Adding 2nd database is done like this in yii-config:
'db' => $db, // the original DB
'db2'=>[
'class' => 'yii\db\Connection',
'driverName' => 'sqlsrv',
// I was not able to specify database like this:
// 'dsn' => 'sqlsrv:Server={serverName};Database={dbName}',
'dsn' => 'sqlsrv:Server={serverName}',
'username' => '{username}',
'password' => '{pwd}',
'charset' => 'utf8',
],
That's it. Now you can test your DB like this:
$result = Yii::$app->db2->createCommand('SELECT * FROM {tblname}')->queryAll();
var_dump($result);
Note that in MSSQL you can have longer table names. Example: CATEGORY.SCHEMA.TBL_NAME
And your first test-model can look like this (file MyMsModel.php):
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
class MyMsModel extends \yii\db\ActiveRecord
{
public static function getDb()
{
return \Yii::$app->db2; // or Yii::$app->get('db2');
}
public static function tableName()
{
return 'CATEGORY.SCHEMA.TBL_NAME'; // or SCHEMA.TBL_NAME
}
}
Usage:
$result = MyMsModel::find()->limit(2)->all();
var_dump($result);
Once you have added the 2nd database (read above) go to the Model Generator in Gii. Change there the DB connection to whatever you named the connection in yii-config (in the example above it was "db2") and set tablename in format: SCHEMA.TBL_NAME. If MSSQL server has more databases, one of them is set to be the main DB. This will be used I think. I haven't succeeded to change the DB. DB can be set in the DSN string, but it had no effect in my case.
In previous chapters I showed how to use PhpExcel in Yii 1. Now I needed it also in Yii 2 and it was extremely easy.
Note: PhpExcel is deprecated and was replaced with PhpSpreadsheet.
// 1) Command line:
// This downloads everything to folder "vendor"
composer require phpoffice/phpspreadsheet --prefer-source
// --prefer-source ... also documentation and samples are downloaded
// ... adds cca 40MB and 1400 files
// ... only for devel system
// 2) PHP:
// Now you can directly use the package without any configuration:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Uncomment following rows if you want to set col width:
//$sheet->getColumnDimension('A')->setAutoSize(false);
//$sheet->getColumnDimension('A')->setWidth("50");
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
// You can save the file on the server:
// $writer->save('hello_world.xlsx');
// Or you can send the file directly to the browser so user can download it:
// header('Content-Type: application/vnd.ms-excel'); // This is probably for older XLS files.
header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // This is for XLSX files (they are basically zip files).
header('Content-Disposition: attachment;filename="filename.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
Thanks to DbCreator for the idea how to send XLSX to browser. Nevertheless exit() or die() should not be called. Read the link.
Following is my idea which originates from method renderPhpFile() from Yii2:
ob_start();
ob_implicit_flush(false);
$writer->save('php://output');
$file = ob_get_clean();
return \Yii::$app->response->sendContentAsFile($file, 'file.xlsx',[
'mimeType' => 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'inline' => false
]);
This also worked for me:
$tmpFileName = uniqid('file_').'.xlsx';
$writer->save($tmpFileName);
header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename.xlsx"');
header('Cache-Control: max-age=0');
echo file_get_contents($tmpFileName);
unlink($tmpFileName);
exit();
Note: But exit() or die() should not be called. Read the "DbCreator" link above.
See part I of this guide for other PDF creators:
TCPDF was created in 2002 (I think) and these days (year 2020) is being rewritten into a modern PHP application. I will describe both, but lets begin with the older version.
Older version of TCPDF
Download it from GitHub and save it into folder
{projectPath}/_tcpdf
Into web/index.php add this:
require_once('../_tcpdf/tcpdf.php');
Now you can use any Example to test TCPDF. For example: https://tcpdf.org/examples/example_001/
Note: You have to call constructor with backslash:
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
Note: Texts are printed using more methods - see file tcpdf.php for details:
Note: Store your files in UTF8 no BOM format so diacritics is correct in PDF.
Importing new TTF fonts is done like this:
// this command creates filed in folder _tcpdf\fonts. Use the filename as the fontname in other commands.
$fontname = \TCPDF_FONTS::addTTFfont("path to TTF file", 'TrueTypeUnicode', '', 96);
Now you can use it in PHP like this:
$pdf->SetFont($fontname, '', 24, '', true);
Or in HTML:
<font size="9" face="fontName" style="color: rgb(128, 128, 128);">ABC</font>
Rendering is done like this:
$pdf->writeHTML($html);
Note: When printing pageNr and totalPageCount to the footer, writeHTML() was not able to correctly interpret methods getAliasNumPage() and getAliasNbPages() as shown in Example 3. I had to use rendering method Text() and position the numbers correctly like this:
$this->writeHTML($footerHtmlTable);
$this->SetTextColor('128'); // I have gray pageNr
$this->Text(185, 279, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages());
$this->SetTextColor('0'); // returning black color
New version of TCPDF
... to be finished ...
If I generate a PDF-invoice it contains many numbers and it is nice to print them as integers when decimals are not needed. For example number 24 looks better and saves space compared to 24.00. So I created such a formatter. Original inspiration and how-to was found here:
My formatter looks like this:
<?php
namespace app\myHelpers;
class MyFormatter extends \yii\i18n\Formatter {
public function asDecimalOrInteger($value) {
$intStr = (string) (int) $value; // 24.56 => "24" or 24 => "24"
if ($intStr === (string) $value) {
// If input was integer, we are comparing strings "24" and "24"
return $this->asInteger($value);
}
if (( $intStr . '.00' === (string) $value)) {
// If the input was decimal, but decimals were all zeros, it is an integer.
return $this->asInteger($value);
}
// All other situations
$decimal = $this->asDecimal($value);
// Here I trim also the trailing zero.
// Disadvantage is that String is returned, but in PDF it is not important
return rtrim((string)$decimal, "0");
}
}
Usage is simple. Read the link above and give like to karpy47 or see below:
// file config/web.php
'components' => [
'formatter' => [
'class' => 'app\myHelpers\MyFormatter',
],
],
There is only one formatter in the whole of Yii and you can extend it = you can add more methods and the rest of the formatter will remain so you can use all other methods as mentioned in documentation.
... can be easily done by adding a MySQL VIEW into your DB, creating a model for it and using it in the "ParentSearch" model as the base class.
Let's show it on list of invoices and their items. Invoices are in table "invoice" (model Invoice) and their items in "invoice_item" (model InvoiceItem). Now we need to join them and sort and filter them by SUM of prices (amounts). To avoid calculations in PHP, DB can do it for us if we prepare a MySQL VIEW:
CREATE VIEW v_invoice AS
SELECT invoice.*,
SUM(invoice_item.units * invoice_item.price_per_unit) as amount,
COUNT(invoice_item.id) as items
FROM invoice
LEFT JOIN invoice_item
ON (invoice.id = invoice_item.id_invoice)
GROUP BY invoice.id
Note: Here you can read why it is better not to use COUNT(*) in LEFT JOIN:
This will technically clone the original table "invoice" into "v_invoice" and will append 2 calculated columns: "amount" + "items". Now you can easily use this VIEW as a TABLE (for reading only) and display it in a GridView. If you already have a GridView for table "invoice" the change is just tiny. Create this model:
<?php
namespace app\models;
class v_Invoice extends Invoice
{
public static function primaryKey()
{
// here is specified which column(s) create the fictive primary key in the mysql-view
return ['id'];
}
public static function tableName()
{
return 'v_invoice';
}
}
.. and in model InvoiceSearch replace word Invoice with v_Invoice (on 2 places I guess) plus add rules for those new columns. Example:
public function rules()
{
return [
// ...
[['amount'], 'number'], // decimal
[['items'], 'integer'],
];
}
Into method search() add condition if you want to filter by amount or items:
if (trim($this->amount)!=='') {
$query->andFilterWhere([
'amount' => $this->amount
]);
}
In the GridView you can now use the columns "amount" and "items" as native columns. Filtering and sorting will work.
Danger: Read below how to search and sort by related columns. This might stop working if you want to join your MySQL with another table.
I believe this approach is the simplest to reach the goal. The advantage is that the MySQL VIEW is only used when search() method is called - it means in the list of invoices. Other parts of the web are not influenced because they use the original Invoice model. But if you need some special method from the Invoice model, you have it also in v_Invoice. If data is saved or changed, you must always modify the original table "invoice".
Lets say you have table of invoices and table of companies. They have relation and you want to display list of Invoices plus on each row the corresponding company name. You want to filter and sort by this column.
Your GridView:
<?= GridView::widget([
// ...
'columns' => [
// ...
[
'attribute'=>'company_name',
'value'=>'companyRelation.name',
],
Your InvoiceSearch model:
class InvoiceSearch extends Invoice
{
public $company_name;
// ...
public function rules() {
return [
// ...
[['company_name'], 'safe'],
];
}
// ...
public function search($params) {
// ...
// You must use joinWith() in order to have both tables in one JOIN - then you can call WHERE and ORDER BY on the 2nd table.
// Explanation here:
// https://stackoverflow.com/questions/25600048/what-is-the-difference-between-with-and-joinwith-in-yii2-and-when-to-use-them
$query = Invoice::find()->joinWith('companyRelation');
// Appending new sortable column:
$sort = $dataProvider->getSort();
$sort->attributes['company_name'] = [
'asc' => ['table.column' => SORT_ASC],
'desc' => ['table.column' => SORT_DESC],
'label' => 'Some label',
'default' => SORT_ASC
];
// ...
if (trim($this->company_name)!=='') {
$query->andFilterWhere(['like', 'table.column', $this->company_name]);
}
}
In my tutorial for Yii v1 I presented following way how to send headers manually and then call exit(). But calling exit() or die() is not a good idea so I discovered a better way in Yii v2. See chapter Secured (secret) file download
Motivation: Sometimes you receive a PDF file encoded into a string using base64. For example a label with barcodes from FedEx, DPD or other delivery companies and your task is to show the label to users.
For me workes this algorithm:
$pdfBase64 = 'JVBERi0xLjQ ... Y0CiUlRU9GCg==';
// First I create a fictive stream in a temporary file
// Read more about PHP wrappers:
// https://www.php.net/manual/en/wrappers.php.php
$stream = fopen('php://temp','r+');
// Decoded base64 is written into the stream
fwrite($stream, base64_decode($pdfBase64));
// And the stream is rewound back to the start so others can read it
rewind($stream);
// This row sets "Content-Type" header to none. Below I set it manually do application/pdf.
Yii::$app->response->format = Yii::$app->response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'application/pdf');
// This row will download the file. If you do not use the line, the file will be displayed in the browser.
// Details here:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#Downloads
// Yii::$app->response->headers->set('Content-Disposition','attachment; filename="hello.pdf"');
// Here is used the temporary stream
Yii::$app->response->stream = $stream;
// You can call following line, but you don't have to. Method send() is called automatically when current action ends:
// Details here:
// https://www.yiiframework.com/doc/api/2.0/yii-web-response#sendContentAsFile()-detail
// return Yii::$app->response->send();
Note: You can add more headers if you need. Check my previous article (linked above).
]]>Note:Pantahub is the only place where Linux firmware can be shared and deployed for any device, You can signup @pantahub here:http://www.pantahub.com
Click to download: https://pantavisor-ci.s3.amazonaws.com/pv-initial-devices/tags/012-rc2/162943661/rpi3_initial_stable.img.xz
Run $ unxz rpi3_initial_stable.img.xz
Note: pvr is a CLI tool which can be used to interact with your device through pantahub platform.
Note: Using pvr you can share your firmware and projects as simple as with a git tree.
Note: Move the pvr binary to your bin folder after download.
Linux(AMD64): Download
Linux(ARM32v6): Download
Darwin(AMD64): Download
pvr clone; pvr commit; pvr post
Install from github source code:
$ go get gitlab.com/pantacor/pvr
$ go build -o ~/bin/pvr gitlab.com/pantacor/pvr
Note: You need "GOLANG" to be installed in your system for building pvr from github source code.
$ pvr scan
¶
$ pvr claim -c merely-regular-gorilla https://api.pantahub.com:443/devices/5f1b9c44e193a
Watch now on Amazon Prime Video
5000afa9901
$ pvr clone https://pvr.pantahub.com/sirinibin/presently_learning_pelican/0 presently_learning_pelican
Now your device is ready to deploy your Yii2 app
`$ cd presently_learning_pelican`
>sirinibin/yii2-basic-arm32v7:latest
is a Docker
Watch now on Amazon Prime Video
image made for the devices with ARM32 architecture
>> You can customise the docker image for your custom Yii2 app.
$ pvr app add yii2 --from=sirinibin/yii2-basic-arm32v7:latest
$ pvr add .
$ pvr commit
$ pvr post
Status 1:
Status 2:
Status 3:
Status 4:
Access the device IP: http://10.42.0.231/myapp1/web/ in your web browser.
]]>You are done!
Yii2 - Converting from Bootstrap3 to Bootstrap4
This article has been written because while conversion is a largely pain-free process, there are some minor issues. These are not difficult to solve, but it is not immediately obvious where the problem lies.
1 - Install Bootstrap4 My preference is to simply use composer. Change composer.json in the root of your project:
Copy the line, and change the new line:
"yiisoft/yii2-bootstrap" : "~2.0.6", "yiisoft/yii2-bootstrap4" : "^2.0.8",
yii\bootstrap\
and change it to yii\bootstrap4\
. However, be careful - your IDE may require the backslash to be escaped. For example, Eclipse will find all files with the string easily, but the search string must have double-backslashes, while the replacement string must be left as single ones.NavBar::begin
and look at it's class options. In my case they were the original: 'class' => 'navbar-inverse navbar-fixed-top'
At the end of all this, I had the class line changed to something which gave me a navbar very similar to the original:
//Bootstrap3: 'class' => 'navbar-inverse navbar-fixed-top',
//Changed for Bootstrap4:
'class' => 'navbar navbar-expand-md navbar-light bg-dark',
Breadcrumbs
Note - March 2020: This entire section on Breadcrumbs may no longer be an issue. While I've left the section in as a tutorial, before making any changes read what Davide has to say in the user comments.
So, that fixed my navbar. Next, I noticed that the breadcrumbs were not quite right - the slash separating the path elements was no longer there. Preparing for a lot of debugging, I went to the Bootstrap site to look for a little inspiration. I didn't need to look any further - Bootstrap 4 requires each Breadcrumb element to have a class of "breadcrumb-item". After I spent a little time looking at vendors/yiisoft/yii2/widgets/Breadcrumbs.php to get some understanding of the issue, I discovered all that's needed is to change the itemTemplate and activeItemTemplate. Of course, since these are part of the Yii2 framework, you don't want to change that file, otherwise, it will probably get updated at some stage, and all your changes would be lost. Since both of these attributes are public, you can change them from outside the class, and the easiest place to do this is in frontend/views/main.php:
`
html
<div class="container">
<?= Breadcrumbs::widget([
'itemTemplate' => "\n\t<li class=\"breadcrumb-item\"><i>{link}</i></li>\n", // template for all links
'activeItemTemplate' => "\t<li class=\"breadcrumb-item active\">{link}</li>\n", // template for the active link
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>```
Data Grid ActionColumn One of my pages was a data grid generated for me by gii. On each row it has a set of buttons that you can click to view, edit or delete the row. Under Bootstrap 4, the ActionColumn disappeared. Viewing the page source showed me it was there, but I couldn't see it or click on it. Going to the migration guide, it turns out that Bootstrap 3 includes icons, but Bootstrap 4 doesn't. I got a lot of help from a question asked in the Yii2forum.. In the end, my solution was to get a local copy of FontAwesome 5 by including the line "fortawesome/font-awesome": "^5.12.1" in the require section of composer.json, and then choosing the icons that I wanted. I spent a lot of time figuring out how to do this, but when I was done, it seemed almost anti-climactic in it's simplicity. This is what I did in my data form:
['class' => 'yii\grid\ActionColumn',
'buttons' => [
'update' => function($url,$model) {
return Html::a('<i class="fas fa-edit"></i>', $url, [
'title' => Yii::t('app', 'update')
]);
},
'view' => function($url,$model) {
return Html::a('<i class="fas fa-eye"></i>', $url, [
'title' => Yii::t('app', 'view')
]);
},
'delete' => function($url,$model) {
return Html::a('<i class="fas fa-trash"></i>', $url, [
'title' => Yii::t('app', 'delete')
]);
}
]
],
Functional Tests
Not seeing anything more visually, at least nothing that was obvious, I now ran the suite of tests. These were all previously passing, but now several of them failed. One of them was the Contact Form, so I ran that one separately and the tests informed me they were failing because they couldn't see the error message:
1) ContactCest: Check contact submit no data
Test ../frontend/tests/functional/ContactCest.php:checkContactSubmitNoData
Step See "Name cannot be blank",".help-block"
Fail Element located either by name, CSS or XPath element with '.help-block' was not found.
I, on the other hand, could see the error messages on the form, so I used the browser's page source and discovered that the css class was no longer "help-block", it had changed to "invalid-feedback". Easy enough - in frontend/tests/_support/FunctionalTester.php, I changed the expected css class:
public function seeValidationError($message)
{
$this->see($message, '.invalid-feedback');
}
Of course, this little excerpt is just an example. I found the same thing had to be done in several locations, but all were easily found and resolved.
After this, running my tests pointed me to no other problems, but I don't expect that to mean there aren't any other problems. While everything seems to be working so far, I expect there are more issues hiding in the woodwork. Somehow, those problems don't seem quite so insurmountable anymore.
]]>I have a dream ... I am happy to join with you today in what will go down in history as the greatest demonstration of bad design of Active Record.
I have an API. It's built with a RESTful extension over Active Record, and some endpoints provide PUT methods to upload files. By a REST design we create an entity with POST /video
first, and then upload a video file with PUT /video/{id}/data
.
How do we get the {id}
? The essential solutuion is UUID generated by a client. It allows API application to be stateless and scale it, use master-master replication for databases and feel yourself a modern guy.
If you have Postgres — lucky you, feel free to use the built-in UUID data type and close this article.
With MySQL the essential solution is insert into users values(unhex(replace(uuid(),'-',''))...
MySQL team recommends updating our INSERT queries. With Active Record it is not really possible.
For fetching UUIDs it recommends adding a virtual column — this can be used.
If you design the application from ground up, you can use defferent fields for a binary and text representation of UUID, and reference them in different parts of an application, but I am bound to the legacy code.
Adding getId()
/setId()
won't help - data comes from a client in JSON and fills the model object with a setAttributes()
call avoiding generic magic methods.
Here's the hack:
Step 1. Add a private $idText
property
use yii\db\ActiveRecord;
class Video extends ActiveRecord
{
private $idText;
Step 2. Add two validators and a filter
//check if value is a valid UUID
['id','match', 'pattern'=>'/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i'],
// convert UUID from text value to binary and store the text value in a private variable,
// this is a workaround for lack of mapping in active record
['id','filter','skipOnError' => true, 'filter' => function($uuid) {
$this->idText = $uuid;
return pack("H*", str_replace('-', '', $uuid));
}],
//now let's check if ID is taken
['id','unique','filter' => function(\yii\db\Query $q) {
$q->where(['id' => $this->getAttribute('id')]);
}],
First rule is a validator for an input. Second rule is a filter preparing UUID to be written in a binary format and keeping the text form for output. Third one is a validator running a query over the binary value generated by a filter.
Note: I wrote
$this->getAttribute('id')
,$this->id
returns a text form.
We can write a query to validate data, not to save it.
Step 3. Add getters
public function __get($name)
{
return ($name === 'id') ? $this->getId() : parent::__get($name);
}
/**
* Return UUID in a textual representation
*/
public function getId(): string
{
if ($this->idText === NULL && $this->getIsNewRecord()){
//the filter did not convert ID to binary yet, return the data from input
return strtoupper($this->getAttribute('id'));
}
//ID is converted
return strtoupper($this->idText ?? $this->getAttribute('id_text'));
}
When we call the $model->id
property we need the getId()
executed. But Active Record base class overrides Yii compoent default behavior and does not call a getter method of an object if a property is a field in a table. So I override the magic getter.
From the other hand, a regexp valiator I wrote calls $model->id
, triggering the getter before the UUID is saved to the private property. I check if the object is newly created to serve the text value for validator.
Note the strtoupper()
call: client may send UUID in both upper and low cases, but after unpacking from binary we will have a value in upper case. I received different string values before storing data to DB and after fetching it. Convert the textual UUID value to an upper or lower case everywhere to avoid problems.
It looks weird to mutate data in a validator, but I found this is the best way. I belive I shouldn't use beforeSave()
callback to set the binary value for generating SQL, and return the text value back in afterSave()
- supporting this code would be a classic hell like #define true false;
.
Step 4. Define the mapping for output
public function fields()
{
$fields = parent::fields();
$fields['id'] =function(){return $this->getId();};
return $fields;
}
This method is used by RESTful serializers to format data when you access your API with GET /video
requests.
So, now you can go the generic MySQL way
Step 5. add a virtual column
ALTER TABLE t1 ADD id_text varchar(36) generated always as
(insert(
insert(
insert(
insert(hex(id_bin),9,0,'-'),
14,0,'-'),
19,0,'-'),
24,0,'-')
) virtual;
Step 5. Use Object Relation Mapping in Yii 3 when it's available and write mapping instead of these hacks.
P.S. A couple of helper functions.
declare(strict_types=1);
namespace common\helpers;
class UUIDHelper
{
const UUID_REGEXP = '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';
public static function string2bin(string $uuid): string
{
return pack("H*", str_replace('-', '', $uuid));
}
public static function bin2string(string $binary): string
{
return strtolower(join("-", unpack("H8time_low/H4time_mid/H4time_hi/H4clock_seq_hi/H12clock_seq_low", $binary)));
}
public static function isUUID(string $uuid): bool
{
return (bool)preg_match(self::UUID_REGEXP,$uuid);
}
}
]]>Hi all!
This article had to be split as I reached the max length. Second part is here:
This snippet guide works with the basic Yii demo application and enhances it. It continues in my series of simple Yii tutorials. Previous two contain basic info about MVC concept, exporting to Excel and other topics so read them as well, but they are meant for Yii v1. I started with them cca in year 2011:
... and today I am beginning with Yii 2 so I will also gather my snippets and publish them here so we all can quickly setup the yii-basic-demo just by copying and pasting. This is my goal - to show how-to without long descriptions.
If you find any problems in my snippets, let me know, please.
Skip this paragraph if you know how to run your Yii demo project...
I work with Win10 + XAMPP Server so I will expect this configuration. Do not forget to start the server and enable Apache + MySQL in the dialog. Then test that following 2 URLs work for you
You should also download the Yii basic demo application and place it into the htdocs folder. In my case it is here:
And your index.php should be here:
If you set things correctly up, following URL will open your demo application. Now it will probably throw an exception:
The Exception is removed by entering any text into attribute 'cookieValidationKey' in file:
Dont forget to connect Yii to the DB. It is done in file:
... but it should work out-of-the-box if you use DB name "yii2basic" which is also used in examples below ...
.
.
Once you download and run the basic app, I recommend to push it into GitLab. You will probably need a SSH certificate which can be generated like this using PuTTYgen or command "ssh-keygen" in Windows10. When I work with Git I use TortoiseGIT which integrates all git functionalities into the context menu in Windows File Explorer.
First go to GitLab web and create a new project. Then you might need to fight a bit, because the process of connecting your PC to GIT seems to be quite complicated. At least for me.
Note: Here you can add the public SSH key to GitLab. Private key must be named "id_rsa" and stored in Win10 on path C:\Users\{username}\.ssh\id_rsa
Once things work, just create an empty folder, right click it and select Git Clone. Enter your git path, best is this format:
Note: What works for me the best is using the following command to clone my project and system asks me for the password. Other means of connection usually refuse me. Then I can start using TortoiseGIT.
git clone https://{username}@gitlab.com/{username}/{myProjectName}.git
When cloned, copy the content of the "basic" folder into the new empty git-folder and push everything except for folder "vendor". (It contains 75MB and 7000 files so you dont want to have it in GIT)
Then you can start to modify you project, for example based on this "tutorial".
Thanks to .gitignore files only 115 files are uploaded. Te vendor-folder can be recreated using command
composer install
which only needs file composer.json to exist.
I found these two pages where things are explained: link link.
You need to create file .gitlab-ci.yml in the root of your repository with this content. It will fire a Pipeline job on commit using "LFTP client".
variables:
HOST: "ftp url"
USERNAME: "user"
PASSWORD: "password"
TARGETFOLDER: "relative path if needed, or just ./"
deploy:
script:
- apt-get update -qq && apt-get install -y -qq lftp
- lftp -c "set ftp:ssl-allow no; open -u $USERNAME,$PASSWORD $HOST; mirror -Rnev ./ $TARGETFOLDER --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/ --exclude vendor --exclude web/assets --exclude web/index.php --exclude web/index-test.php --exclude .gitlab-ci.yml"
only:
- master
I just added some exclusions (see the code) and will probably add --delete in the future. Read linked webs.
Important info: Your FTP server might block foreign IPs. If this happens, your transfer will fail with error 530. You must findout GitLab's IPs and whitelist them. [This link]( https://docs.gitlab.com/ee/user/gitlab_com/#ip-range) might help.
To create DB with users, use following command. I recommend charset utf8_unicode_ci (or utf8mb4_unicode_ci) as it allows you to use more international characters.
CREATE DATABASE IF NOT EXISTS `yii2basic` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
USE `yii2basic`;
CREATE TABLE IF NOT EXISTS `user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(60) NOT NULL,
`email` VARCHAR(60) NOT NULL,
`authKey` VARCHAR(60),
PRIMARY KEY (`id`))
ENGINE = InnoDB;
INSERT INTO `user` (`id`, `username`, `password`, `email`, `authKey`) VALUES (NULL, 'user01', '0497fe4d674fe37194a6fcb08913e596ef6a307f', 'user01@gmail.com', NULL);
If you must use MyISAM instead of InnoDB, just change the word InnoDB into MYISAM.
Then replace existing model User with following snippet
<?php
namespace app\models;
use Yii;
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
// When user detail is being edited we will only modify attribute password_new
// Why? We dont want to load password-hash from DB and display it to the user
// We only want him to see empty field and if it is filled in, password is changed on background
public $password_new;
public $password_new_repeat;
// Use this scenario in UserController->actionCreate() right after: $model = new User() like this:
// $model->scenario = User::SCENARIO_CREATE;
// This will force the user to enter the password when new user is created
// When user is edited, new password is not needed
const SCENARIO_CREATE = "user-create";
// ----- Default 3 model-methods by GII:
public static function tableName() {
return 'user';
}
public function rules() {
return [
[['username', 'email'], 'required'],
[['password_new_repeat', 'password_new'], 'required', "on" => self::SCENARIO_CREATE],
[['username', 'email'], 'string', 'max' => 45],
['email', 'email'],
[['password', 'authKey'], 'string', 'max' => 60],
[['password', 'password_new_repeat', 'password_new'], 'safe'],
['password_new_repeat', 'compare', 'operator' => '==', 'compareAttribute' => 'password_new'],
['password_new', 'compare', 'operator' => '==', 'compareAttribute' => 'password_new_repeat'],
['password_new_repeat', 'setPasswordWhenChanged'],
];
}
public function attributeLabels() {
return [
'id' => Yii::t('app', 'ID'),
'username' => Yii::t('app', 'Username'),
'password' => Yii::t('app', 'Password'),
'password_new' => Yii::t('app', 'New password'),
'password_new_repeat' => Yii::t('app', 'Repeat new password'),
'authKey' => Yii::t('app', 'Auth Key'),
'email' => Yii::t('app', 'Email'),
];
}
// ----- Password validator
public function setPasswordWhenChanged($attribute_name, $params) {
if (trim($this->password_new_repeat) === "") {
return true;
}
if ($this->password_new_repeat === $this->password_new) {
$this->password = sha1($this->password_new_repeat);
}
return true;
}
// ----- IdentityInterface methods:
public static function findIdentity($id) {
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null) {
return static::findOne(['access_token' => $token]);
}
public function getId() {
return $this->id;
}
public function getAuthKey() {
return $this->authKey;
}
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
// ----- Because of default LoginForm:
public static function findByUsername($username) {
return static::findOne(['username' => $username]);
}
public function validatePassword($password) {
return $this->password === sha1($password);
}
}
Validators vs JavaScript:
Now you can also create CRUD for the User model using GII:
CRUD = Create Read Update Delete = views and controller. On the GII page enter following values:
And then you can edit users on this URL: http://localhost/basic/web/index.php?r=user ... but it is not all. You have to modify the view-files so that correct input fields are displayed!
Open folder views\user and do following:
Plus do not forget to use the new scenario in UserController->actionCreate() like this:
public function actionCreate()
{
$model = new User();
$model->scenario = User::SCENARIO_CREATE; // the new scenario!
// ...
.
.
Translations are fairly simple, but I probably didnt read manuals carefully so it took me some time. Note that now I am only describing translations which are saved in files. I do not use DB translations yet. Maybe later.
1 - Translating short texts and captions
First create following folders and file.
(Note that cs-CZ is for Czech Lanuage. For German you should use de-DE etc. Use any other language if you want.)
The idea behind is that in the code there are used only English texts and if you want to change from English to some other language this file will be used.
Now go to file config/web.php, find section "components" and paste the i18n section:
'components' => [
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@app/messages',
'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php'
],
],
],
], // end of 'i18n'
// ... other configurations
], // end of 'components'
Explanation of the asterisk * can be found in article https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n
You surely saw that in views and models there are translated-texts saved like this:
Yii::t('app', 'New password'),
It means that this text belongs to category "app" and its English version (and also its ID) is "New password". So this ID will be searched in the file you just created. In my case it was the Czech file:
Therefore open the file and paste there following code:
<?php
return [
'New password' => 'Nové heslo',
];
?>
Now you can open the page for adding a new user and you will see than so far nothing changed :-)
We must change the language ... For now let's do it in a primitive and permanent way again in file config/web.php
$config = [
// use your language
// also accessible via Yii::$app->language
'language' => 'cs-CZ',
// This attribute is not necessary.
// en-US is default value
'sourceLanguage' => 'en-US',
// ... other configs
2 - Translating long texts and whole views
If you have a view with long texts and you want to translate it into a 2nd language, it is not good idea to use the previous approach, because it uses the English text as the ID.
It is better to translate the whole view. How? ... Just create a sub-folder next to the view and give it name which will be identical to the target-lang-ID. In my case the 2nd language is Czech so I created following folder and copied my view in it. So now I have 2 identical views with identical names:
Yii will automatically use the Czech version if needed.
.
.
First lets add to file config/params.php attributes with list of supported languages:
<?php
return [
// ...
'allowedLanguages' => [
'en-US' => "English",
'cs-CZ' => "Česky",
],
'langSwitchUrl' => '/site/set-lang',
];
This list can be displayed in the main menu. Edit file:
And above the Nav::widget add few rows:
$listOfLanguages = [];
$langSwitchUrl = Yii::$app->params["langSwitchUrl"];
foreach (Yii::$app->params["allowedLanguages"] as $langId => $langName) {
$listOfLanguages[] = ['label' => Yii::t('app', $langName), 'url' => [$langSwitchUrl, 'langID' => $langId]];
}
and then add one item into Nav::widge
echo Nav::widget([
// ...
'items' => [
// ...
['label' => Yii::t('app', 'Language'),'items' => $listOfLanguages],
// ...
Now in the top-right corner you can see a new drop-down-list with list of 2 languages. If one is selected, action "site/setLang" is called so we have to create it in SiteController.
Note that this approach will always redirect user to the new action and his work will be lost. Nevertheless this approach is very simple so I am using it in small projects. More complex projects may require an ajax call when language is changed and then updating texts using javascript so reload is not needed and user's work is preserved. But I expect that when someone opens the web, he/she sets the language immediately and then there is no need for further changes.
The setLang action looks like this:
public function actionSetLang($langID = "") {
$allowedLanguages = Yii::$app->params["allowedLanguages"];
$langID = trim($langID);
if ($langID !== "" && array_key_exists($langID, $allowedLanguages)) {
Yii::$app->session->set('langID', $langID);
}
return $this->redirect(['site/index']);
}
As you can see when the language is changed, redirection to site/index happens. Also mind that we are not modifying the attribute from config/web.php using Yii::$app->language, but we are saving the value into the session. The reason is that PHP deletes memory after every click, only session is kept.
We then can use the langID-value in other controllers using new method beforeAction:
public function beforeAction($action) {
if (!parent::beforeAction($action)) {
return false;
}
Yii::$app->language = Yii::$app->session->get('langID');
return true;
}
.. or you can create one parent-controller named for example BaseController. All other controllers will extend it.
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class BaseController extends Controller {
public function beforeAction($action) {
if (!parent::beforeAction($action)) {
return false;
}
Yii::$app->language = Yii::$app->session->get('langID');
return true;
}
}
As you can see in the snippet above, other controllers must contain row "use app\controllers\BaseController" + "extends BaseController".
Go to config\web.php and add following values:
$config = [
// ..
'language' => 'cs-CZ',
// \Yii::$app->language:
// https://www.yiiframework.com/doc/api/2.0/yii-base-application#$language-detail
//..
'components' => [
'formatter' => [
//'locale' => 'cs_CZ',
// Only effective when the "PHP intl extension" is installed else "language" above is used:
// https://www.php.net/manual/en/book.intl.php
//'language' => 'cs-CZ',
// If not set, "locale" above will be used:
// https://www.yiiframework.com/doc/api/2.0/yii-i18n-formatter#$language-detail
// Following values might be usefull for your situation:
'booleanFormat' => ['Ne', 'Ano'],
'dateFormat' => 'yyyy-mm-dd', // or 'php:Y-m-d'
'datetimeFormat' => 'yyyy-mm-dd HH:mm:ss', // or 'php:Y-m-d H:i:s'
'decimalSeparator' => ',',
'defaultTimeZone' => 'Europe/Prague',
'thousandSeparator' => ' ',
'timeFormat' => 'php:H:i:s', // or HH:mm:ss
'currencyCode' => 'CZK',
],
In GridView and DetailView you can then use following and your settings from above will be used:
'columns' => [
[
'attribute' => 'colName',
'label' => 'Value',
'format'=>['decimal',2]
],
[
'label' => 'Value',
'value'=> function ($model) { return \Yii::$app->formatter->asDecimal($model->myCol, 2) . ' EUR' ; } ],
]
// ...
]
PS: I do not use currency formatter as it always puts the currency name before the number. For example USD 123. But in my country we use format: 123 CZK.
More links on this topic:
Every controller can allow different users/guests to use different actions. Method behaviors() can be used to do this. If you generate the controller using GII the method will be present and you will just add the "access-part" like this:
// don't forget to add this import:
use yii\filters\AccessControl;
public function behaviors() {
return [
// ...
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'], // logged in users
// 'roles' => ['?'], // guests
// 'matchCallback' => function ($rule, $action) {
// all logged in users are redirected to some other page
// just for demonstration of matchCallback
// return $this->redirect('index.php?r=user/create');
// }
],
],
// All guests are redirected to site/index in current controller:
'denyCallback' => function($rule, $action) {
Yii::$app->response->redirect(['site/index']);
},
],
];
}
.. This is all I needed so far. I will add more complex snippet as soon as I need it ...
Details can be found here https://www.yiiframework.com/doc/guide/2.0/en/security-authorization.
.
.
Just uncomment section "urlManager" in config/web.php .. htaccess file is already included in the basic demo. In case of problems see this link.
My problem was that images were not displayed when I enabled nice URLs. Smilar discussion here.
// Originally I used these img-paths:
<img src="..\web\imgs\myimg01.jpg"/>
/// Then I had to chage them to this:
Html::img(Yii::$app->request->baseUrl . '/imgs/myimg01.jpg')
// The important change is using the "baseUrl"
Note that Yii::$app->request->baseUrl returns "/myProject/web". No trailing slash.
.
.
Note: If you are using the advanced demo app, this link can be interesting for you.
Yii 2 has the speciality that index.php is hidden in the web folder. I didnt find in the official documentation the important info - how to hide the folder, because user is not interested in it ...
Our demo application is placed in folder:
Now you will need 2 files named .htaccess
The first one is mentioned in chapter Nice URLs and looks like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
The second is simpler:
RewriteEngine on
RewriteRule ^(.*)$ web/$1 [L]
... it only adds the word "web" into all URLs. But first we have to remove the word from URLs. Open file config/web.php and find section request. Add attribute baseUrl:
'request' => [
// 'cookieValidationKey' => ...
'baseUrl' => '/basic', // add this line
],
Now things will work for you. But it might be needed to use different value for devel and productive environment. Productive web is usually in the root-folder so baseUrl should be en empty string. I did it like this:
$baseUrlWithoutWebFolder = "";
if (YII_ENV_DEV) {
$baseUrlWithoutWebFolder = '/basic';
}
// ...
'request' => [
// 'cookieValidationKey' => ...
'baseUrl' => $baseUrlWithoutWebFolder,
],
I will test this and if I find problems and solutions I will add them.
.
.
... to be added ...
.
.
.
.
DROP TABLE IF EXISTS `contact` ;
CREATE TABLE IF NOT EXISTS `contact` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`subject` VARCHAR(100) NOT NULL,
`body` TEXT NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
use app\models\Contact;
// ...
public function actionContact() {
$model = new Contact();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// ...
public $verifyCode;
// ...
['verifyCode', 'captcha'],
['email', 'email'],
// and translation for Captcha
'verifyCode' => Yii::t('app', 'Verification'),
<p>
Note that if you turn on the Yii debugger ...
Then some security - filtering users in the new ContactController:
public function beforeAction($action) {
if (!parent::beforeAction($action)) {
return false;
}
$guestAllowedActions = [];
if (Yii::$app->user->isGuest) {
if (!in_array($action->actionMethod, $guestAllowedActions)) {
return $this->redirect(['site/index']);
}
}
return true;
}
.
.
... text ...
.
.
I needed to show user a list of his events in a large calendar so I used library fullcalendar.
Great demo which you can just copy and paste:
/*I added this style to hide vertical scroll-bars*/
.fc-scroller.fc-day-grid-container{
overflow: hidden !important;
}
$this->registerCssFile('@web/css/fullcalendar/fullcalendar.css');
$this->registerCssFile('@web/css/fullcalendar/fullcalendar.print.css', ['media' => 'print']);
$this->registerJsFile('@web/js/fullcalendar/moment.min.js', ['depends' => ['yii\web\JqueryAsset']]);
$this->registerJsFile('@web/js/fullcalendar/fullcalendar.min.js', ['depends' => ['yii\web\JqueryAsset']]);
// details here:
// https://www.yiiframework.com/doc/api/2.0/yii-web-view
... if you want to go pro, use NPM. The NPM way is described here.
API is here: https://fullcalendar.io/docs ... you can then enhace the calendar config from the example above
In order to make things work I had to force jQuery to be loaded before calendar scripts using file config/web.php like this
'components' => [
// ...
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'jsOptions' => [ 'position' => \yii\web\View::POS_HEAD ],
],
],
],
You can customize the calendar in many ways. For example different event-color is shown here. Check the source code.
.
.
I have been using scenarios a lot but today I spent 1 hour on a problem - I had 2 scenarios and one of them was just assigned to the model ...
$model->scenario = "abc";
... but had no rule defined yet. I wanted to implement the rule later, but I didnt know that when you set a scenario to your model it must be used in method rules() or defined in method scenarios(). So take this into consideration. I expected that when the scenario has no rules it will just be skipped or deleted.
.
.
If you want to allow user to enter html-formatted text, you need to use some HTML wysiwyg editor, because ordinary TextArea can only work with plain text. It seems to me that Summernote is the simplest addon available:
// Add following code to file layouts/main.php ..
// But make sure jquery is already loaded !!
// - Read about this topic in chapter "Adding a google-like calendar"
<!-- include summernote css/js -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
// And then in any view you can use this code:
<script>
$(document).ready(function() {
$('#summernote1').summernote();
$('#summernote2').summernote();
});
</script>
<div id="summernote1">Hello Summernote</div>
<form method="post">
<textarea id="summernote2" name="editordata"></textarea>
</form>
On this page I showed how to save Contacts inqueries into database. If you want to use the richtext editor in this section, open view contact/_form.php and just add this JS code:
<script>
$(document).ready(function() {
$('#contact-body').summernote();
});
</script>
It will be saved to DB as HTML code. But this might be also a source of problems, because user can inject some dangerous HTML code. So keep this in mind.
Now you will also have to modify view contact/view.php like this in order to see nice formatted text:
DetailView::widget([
'model' => $model,
'attributes' => [
// ...
'body:html',
],
])
... to discover all possible formatters, check all asXXX() functions on this page:
.
.
This is not really a YII topic but as my article is some kind of a code-library I will paste it here as well. To test your SEO score you can use special webs. For example seotesteronline, but only once per day. It will show some statistics and recommend enhancements so that your web is nicely shown on FB and Twitter or found by Google.
Important are for example OG meta tags or TWITTER meta tags. They are basicly the same. Read more here. You can test them at iframely.com.
Basic tags are following and you should place them to head:
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta property="og:site_name" content="European Travel, Inc.">
<meta property="og:title" content="European Travel Destinations">
<meta property="og:description" content="Offering tour packages for individuals or groups.">
<meta property="og:image" content="http://euro-travel-example.com/thumbnail.jpg">
<meta property="og:url" content="http://euro-travel-example.com/index.htm">
<meta name="twitter:card" content="summary_large_image">
<!-- Non-Essential, But Recommended -->
<meta property="og:site_name" content="European Travel, Inc.">
<meta name="twitter:image:alt" content="Alt text for image">
<!-- Non-Essential, But Required for Analytics -->
<meta property="fb:app_id" content="your_app_id" />
<meta name="twitter:site" content="@website-username">
<!-- seotesteronline.com will also want you to add these: -->
<meta name="description" content="blah blah">
<meta property="og:type" content="website">
<meta name="twitter:title" content="blah blah">
<meta name="twitter:description" content="blah blah">
<meta name="twitter:image" content="http://something.jpg">
Do not forget about file robots.txt and sitemap.xml:
// robots.txt can contain this:
User-agent: *
Allow: /
Sitemap: http://www.example.com/sitemap.xml
// And file sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>http://example.com/someFile.html</loc>
<image:image>
<image:loc>http://example.com/someImg.jpg</image:loc>
</image:image>
</url>
</urlset>
You can also minify here or here all your files. Adding "microdata" can help as well, but I have never used it. On the other hand what I do is that I compress images using these two sites tinyjpg.com and tinypng.com.
.
.
.
.
JQuery and its UI extension provide drag&drop functionalities, but these do not work on Android or generally on mobile devices. You can use one more dependency called touch-punch to fix the problem. It should be loaded after jQuery and UI.
<!-- jQuery + UI -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<!-- http://touchpunch.furf.com/ -->
<!-- Use this file locally -->
<script src="./jquery.ui.touch-punch.min.js"></script>
And then standard code should work:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
<!-- jQuery + UI -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<!-- http://touchpunch.furf.com/ -->
<script src="./jquery.ui.touch-punch.min.js"></script>
<style>
.draggable {
width: 100px;
height: 100px;
border: 1px solid red;
}
.droppable {
width: 300px;
height: 300px;
border: 1px solid blue;
}
.over {
background-color: gold;
}
</style>
</head>
<body>
<div class="draggable my1">draggable my1</div>
<div class="draggable my2">draggable my2</div>
<div class="droppable myA">droppable myA</div>
<div class="droppable myB">droppable myB</div>
</body>
<script>
$( function() {
// All draggables will return to their original position if not dropped to correct droppable
// ... and will always stay in the area of BODY
$(".draggable").draggable({ revert: "invalid", containment: "body" });
// Demonstration of how particular droppables can accept only particular draggables
$( ".droppable.myA" ).droppable({
accept: ".draggable.my1",
drop: function( event, ui ) {
// positioning the dropped box into the target area
var dropped = ui.draggable;
var droppedOn = $(this);
$(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);
$(this).removeClass("over");
},
over: function(event, elem) {
$(this).addClass("over");
console.log("over");
},
out: function(event, elem) {
$(this).removeClass("over");
}
});
// Demonstration of how particular droppables can accept only particular draggables
$( ".droppable.myB" ).droppable({
accept: ".draggable.my2",
drop: function( event, ui ) {
// positioning the dropped box into the target area
var dropped = ui.draggable;
var droppedOn = $(this);
$(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);
$(this).removeClass("over");
},
over: function(event, elem) {
$(this).addClass("over");
console.log("over");
},
out: function(event, elem) {
$(this).removeClass("over");
}
});
});
</script>
</html>
.
.
If you do not like entering long model-paths and controller-paths in CRUD-generator, you can modify text boxes in "\vendor\yiisoft\yii2-gii\src\generators\crud\form.php" and enter default paths and then only manually add the name of the model.
if (!$generator->modelClass) {
echo $form->field($generator, 'modelClass')->textInput(['value' => 'app\\models\\']);
echo $form->field($generator, 'searchModelClass')->textInput(['value' => 'app\\models\\*Search']);
echo $form->field($generator, 'controllerClass')->textInput(['value' => 'app\\controllers\\*Controller']);
} else {
echo $form->field($generator, 'modelClass');
echo $form->field($generator, 'searchModelClass');
echo $form->field($generator, 'controllerClass');
}
.
.
If you need to store you project for example in folder D:\GIT\EmployerNr1\ProjectNr2, you can. Just modify 2 files and restart Apache (I am using XAMPP under Win):
127.0.0.1 myFictiveUrl.local
<VirtualHost *:80>
DocumentRoot "D:\GIT\EmployerNr1\ProjectNr2"
ServerName myFictiveUrl.local
ServerAlias myFictiveUrl.local
<Directory "D:\GIT\EmployerNr1\ProjectNr2">
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
# New directive needed in Apache 2.4.3:
Require all granted
</Directory>
</VirtualHost>
You can then use http://myFictiveUrl.local in your browser
.
.
Let's have a GridView (list of users) with edit-button which will open the edit-form in a modal window. Once user-detail is changed, ajax validation will be executed. If something is wrong, the field will be highlighted. If everything is OK and saved, modal window will be closed and the GridView will be updated.
Let's add the button to the GridView in the view index.php and let's wrap the GridView into the Pjax. Also ID is added to the GridView so it can be refreshed later via JS:
<?php yii\widgets\Pjax::begin();?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'id' => 'user-list-GridView',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'email:email',
['class' => 'yii\grid\ActionColumn',
'buttons' => [
'user_ajax_update_btn' => function ($url, $model, $key) {
return Html::a ( '<span class="glyphicon glyphicon-share"></span> ',
['user/update', 'id' => $model->id],
['class' => 'openInMyModal', 'onclick'=>'return false;', 'data-myModalTitle'=>'']
);
},
],
'template' => '{update} {view} {delete} {user_ajax_update_btn}'
],
],
]); ?>
<?php yii\widgets\Pjax::end();?>
Plus add (to the end of this view) following JS code:
<?php
// This section can be moved to "\views\layouts\main.php"
yii\bootstrap\Modal::begin([
'header' => '<span id="myModalTitle">Title</span>',
'id' => 'myModalDialog',
'size' => 'modal-lg',
'clientOptions' => [
// https://getbootstrap.com/docs/3.3/javascript/#modals-options
'keyboard' => false, // ESC key won't close the modal
'backdrop' => 'static', // clicking outside the modal will not close it
],
]);
echo "<div id='myModalContent'></div>";
yii\bootstrap\Modal::end();
$this->registerJs(
"// If you use $(document).on, it will handle also events on elements rendered by AJAX.
$(document).on('click','a.openInMyModal',function(e){
// And if you use $('a.openInMyModal'), it will work only on standard elements
// $('a.openInMyModal').click(function(e){
// Prevents the browsers default behaviour (such as opening a link)
// ... but does not stop the event from bubbling up the DOM
e.preventDefault();
// Prevents the event from bubbling up the DOM
// ... but does not stop the browsers default behaviour
// e.stopPropagation();
// Prevents other listeners of the same event from being called
// e.stopImmediatePropagation();
// Good idea is to set onclick='return false;' to the link if it is in a modal window
let title = $(this).attr('data-myModalTitle');
if (title==undefined) { title = ''; }
$('#myModalDialog #myModalTitle').text(title);
$('#myModalDialog').find('#myModalContent').html('');
$('#myModalDialog').modal('show')
.find('#myModalContent')
.load($(this).attr('href'));
return false;
});",
yii\web\View::POS_READY,
'myModalHandler'
);
?>
Now we need to modify the updateAction:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Yii::$app->request->isAjax) {
return "<script>"
. "$.pjax.reload({container:'#user-list-GridView'});"
. "$('#myModalDialog').modal('hide');"
. "</script>";
}
return $this->redirect(['view', 'id' => $model->id]);
}
if (Yii::$app->request->isAjax) {
return $this->renderAjax('update', [
'model' => $model,
]);
}
return $this->render('update', [
'model' => $model,
]);
}
And file _form.php:
<?php yii\widgets\Pjax::begin([
'id' => 'user-detail-Pjax',
'enablePushState' => false,
'enableReplaceState' => false
]); ?>
<?php $form = ActiveForm::begin([
'id'=>'user-detail-ActiveForm',
'options' => ['data-pjax' => 1 ]
]); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'authKey')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
There is this page bootswatch.com which provides simple bootstrap themes. It is enough to replace one CSS file - you can do it in file "views/layouts/main.php" just by adding following row before < /head > tag:
<link href="https://bootswatch.com/3/united/bootstrap.min.css" rel="stylesheet">
</head>
Note that currently Yii2 is using Bootstrap3 so when searching for themes, dont forget to switch to section Bootstrap 3.
Important: Yii2 is using navbar with classes "navbar-inverse navbar-fixed-top". If you are using themes from Bootswatch, change the navbar class to "navbar navbar-default navbar-fixed-top" otherwise the top menu-bar will have weird color. This is also done in file "views/layouts/main.php" like this:
NavBar::begin([
// ...
'options' => [
'class' => 'navbar navbar-default navbar-fixed-top',
],
]);
Note: If you want to download the theme, you should link it like this:
<link href="<?=Yii::$app->getUrlManager()->getBaseUrl()?>/css/bootstrap-bootswatch-united.min.css" rel="stylesheet">
Now you technically do not need the original bootstrap.css file so you can remove it in "basic/config/web.php" by adding the assetManager section to "components":
'components' => [
// https://stackoverflow.com/questions/26734385/yii2-disable-bootstrap-js-jquery-and-css
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
Once composer is installed, you might want to use it to download Yii, but following command might not work:
php composer.phar create-project yiisoft/yii2-app-basic basic
Change it to:
composer create-project yiisoft/yii2-app-basic basic
.. and run it. If you are in the desired folder right now, you can use . (dot) instead of the last "word":
composer create-project yiisoft/yii2-app-basic .
Using DatePicker
Run this command:
composer require --prefer-dist yiisoft/yii2-jui
and then use this code in your view:
<?= $form->field($model, 'date_deadline')->widget(\yii\jui\DatePicker::classname(), [
//'language' => 'en',
'dateFormat' => 'yyyy-MM-dd',
'options' => ['class' => 'form-control']
]) ?>
Read more at the official documentation and on GIT
Favicon is already included, but it nos used in the basic project. Just type this into views/layouts/main.php:
<link rel="icon" type="image/png" sizes="16x16" href="favicon.ico">
Or you can use the official yii-favicon:
<link rel="apple-touch-icon" sizes="180x180" href="https://www.yiiframework.com/favico/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://www.yiiframework.com/favico/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://www.yiiframework.com/favico/favicon-16x16.png">
If you are using DatePicker as described above, you can use it also in GridView as a filter, but it will not work properly. Current filter-value will not be visible and resetting the filter wont be possible. Use following in views/xxx/index.php to solve the issue:
function getDatepickerFilter($searchModel, $attribute) {
$name = basename(get_class($searchModel)) . "[$attribute]";
$result = \yii\jui\DatePicker::widget(['language' => 'en', 'dateFormat' => 'php:Y-m-d', 'name'=>$name, 'value'=>$searchModel->$attribute, 'options' => ['class' => 'form-control'] ]);
if (trim($searchModel->$attribute)!=='') {
$result = '<div style="display:flex;flex-direction:column">' . $result
. '<div class="btn btn-danger btn-xs glyphicon glyphicon-remove" onclick="$(this).prev(\'input\').val(\'\').trigger(\'change\')"></div></div>';
}
return $result;
}
// ...
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ...
[
'attribute' => 'myDateCol',
'value' => 'myDateCol',
'label'=>'My date label',
'filter' => getDatepickerFilter($searchModel,'myDateCol'),
'format' => 'html'
],
// ...
Do you need to specify for example currency using a predefined list, but your view contains only a simple text-input where you must manually enter currency_id from table Currency?
Read how to enhance it.
use yii\helpers\ArrayHelper;
use app\models\Currency; // My example uses Currency model
$currencies = Currency::find()->asArray()->all();
// 'id' = the primary key column
// 'name' = the column with text to be dispalyed to user
// https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
$currencies = ArrayHelper::map($currencies, 'id', 'name');
<?= $form->field($model, 'id_currency')->dropDownList($currencies) ?>
Note: In other views you will need models with predefined relations to reach the correct value. Relations can be created using GII (when they are defined in DB) or manually.
GridView cannot display DropDownList which could be used by the user to change the number of rows per page. You have to add it manually like this:
When you are creating a new model using Gii, you can select if you want to create the SearchModel as well. Do it, it is usefull for example in this situation. Then add following rows to the model:
// file models/InvoiceSearch.php
use yii\helpers\Html; // add this row
class InvoiceSearch extends Invoice
{
public $pageSize = null // add this row
// ...
// This method already exists:
public function rules()
{
return [ // ...
['pageSize', 'safe'], // add this row
// ...
// Add this function:
public function getPageSizeDropDown($htmlOptions = [], $prefixHtml = '', $suffixHtml = '', $labelPrefix = '') {
return $prefixHtml . Html::activeDropDownList($this, 'pageSize',
[
10 => $labelPrefix.'10',
20 => $labelPrefix.'20',
50 => $labelPrefix.'50',
100 => $labelPrefix.'100',
150 => $labelPrefix.'150',
200 => $labelPrefix.'200',
300 => $labelPrefix.'300',
500 => $labelPrefix.'500',
1000 => $labelPrefix.'1000'
],$htmlOptions ) . $suffixHtml;
}
// Add this function:
public function getPageSizeDropDownID($prefix = '#') {
return $prefix . Html::getInputId($this, 'pageSize');
}
// This method already exists:
public function search($params)
{
// Remember to call load() first and then you can work with pageSize
$this->load($params);
// Add following rows:
if (!isset($this->pageSize)) {
// Here we make sure that the dropDownLst will have correct value preselected
$this->pageSize = $dataProvider->pagination->defaultPageSize;
}
$dataProvider->pagination->pageSize = (int)$this->pageSize;
And then in your views/xxx/index.php use following:
$pageSizeDropDown = $searchModel->getPageSizeDropDown(['class' => 'form-control', 'style'=>'width: 20rem'],'','','Rows per page: ');
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>'{summary}<br>{items}<br><div style="display:flex; background-color: #f9f9f9; padding: 0px 3rem;"><div style="flex-grow: 2;">{pager}</div><div style="align-self:center;">'.$pageSizeDropDown.'</div></div>',
'pager' => [ 'maxButtonCount' => 20 ],
'filterSelector' => $searchModel->getPageSizeDropDownID(),
// filterSelector is the core solution of this problem. It refreshes the grid.
Sometimes you need a static class that will do things for you. This is what helpers do.
I work with the Basic example so I do things like this:
<?php
namespace myHelpers;
class MyClassName { /* ... */ }
require __DIR__ . '/../myHelpers/MyClassName.php';
use myHelpers\MyClassName;
// ...
echo MyClassName::myMethod(123);
If you want your form to be rendered in a grid, you can use your custom new helper to help you. How to create helpers is mentioned right above. The helper then looks like this:
<?php
namespace myHelpers;
class GridFormRenderer {
// https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp
// Bootstrap works with 12-column layouts so max span is 12.
public static function renderGridForm($gridForm, $colSize = 'md', $nullReplacement = ' ', $maxBoootstrapColSpan = 12) {
$result = '';
foreach ($gridForm as $row) {
if (is_null($row)) {
$colSpan = $maxBoootstrapColSpan;
$result .= '<div class="row">' . '<div class="col-' . $colSize . '-' . $colSpan . '">' . $nullReplacement . '</div></div>';
continue;
}
$colSpan = floor($maxBoootstrapColSpan / count($row));
$result .= '<div class="row">';
foreach ($row as $col) {
if (is_null($col)) {
$col = $nullReplacement;
}
$result .= '<div class="col-' . $colSize . '-' . $colSpan . '">' . $col . '</div>';
}
$result .= '</div>';
}
return $result;
}
}
And is used like this in any view:
use myHelpers\GridFormRenderer;
// ...
$form = ActiveForm::begin();
$username = $form->field($model, 'username')->textInput(['maxlength' => true]);
$password_new = $form->field($model, 'password_new')->passwordInput(['maxlength' => true]);
$password_new_repeat = $form->field($model, 'password_new_repeat')->passwordInput(['maxlength' => true]);
$email = $form->field($model, 'email')->textInput(['maxlength' => true]);
$gridForm = [
[$username, null, $email], // null = empty cell
null, // null = empty row
[$password_new, $password_new_repeat],
];
echo GridFormRenderer::renderGridForm($gridForm);
ActiveForm::end();
// ...
The result is that your form has 3 rows, the middle one is empty. In the first row there are 3 cells (username, nothing, email) and in the last row there is 2x password.
You do not have to write any HTML, you only arrange inputs into any number of rows and columns (using the array $gridForm) and things just happen automagically.
Note: I am using Windows 10 + XAMPP
I had to follow 2 manuals:
The result in C:\xampp\php\php.ini was:
[XDebug]
zend_extension = c:\xampp\php\ext\php_xdebug.dll
xdebug.remote_enable = on
xdebug.idekey = netbeans-xdebug
xdebug.remote_host = localhost
xdebug.remote_port = 9000
xdebug.remote_autostart=on
xdebug.var_display_max_depth=5
The last row changes behaviour of var_dump() when xdebug is installed. It does not output whole arrays, but max 3 levels. Read here or here.
Quotes were not important. I didnt even need to download current version of xdebug, it was already in folder C:\xampp\php\ext.
Important also is to righ-click your project, select Properties, then menu "Run configurations" and set correct path to your index.php. Best is to use the button "Browse"
Then you just add a breakpoint, click the debug-play button in NetBeans and refresh your browser. Netbeans will stop the code for you.
For creating PDFs can be used FPDF library. It is extremely simple to make it run. Just download it and then use it as a helper - I described how this is done above. Do not forget to add namespace to FPDF.php.
You will only need FPDF.php and folder font. Then in your controller just do this:
use myHelpers\FPDF;
// ...
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output('D', 'hello.pdf');
Note: I renamed original file fpdf.php to FPDF.php
The only disadvantage is that UTF cannot be used and conversion to older encodings is required. For Czech Republic all texts must be converted like this:
private function convertUtf8ToWin1250($value) {
$value = trim($value);
if (strlen($value)==0) {
// Warning:
// Method strlen() returns number of bytes, not necessiraly number of characters.
// Usually it is the same, but not always.
// see also mb_strlen()
return '';
}
return iconv("UTF-8", "WINDOWS-1250//IGNORE", $value );
}
A discussion is available here.
When you need non-English characters, tFPDF should be used. It is the same as FPDF so FPDF documentation and manual can be used. It only modifies character-handling.
Just download it and then use it as a helper - I described how this is done above.
Summary:
tFPDF example:
$pdf = new tFPDF();
$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
$pdf->AddFont('DejaVu','B','DejaVuSansCondensed-Bold.ttf',true);
$pdf->SetFont('DejaVu','',10);
$pageWidth = 210;
$pageMargin = 10;
$maxContentW = $pageWidth - 2*$pageMargin; // = max width of an element
$pdf->SetAutoPageBreak(true, 0);
$pdf->SetMargins($pageMargin, $pageMargin, $pageMargin);
$pdf->SetAutoPageBreak(true, $pageMargin);
// Settings for tables:
$pdf->SetLineWidth(0.2);
$pdf->SetDrawColor(0, 0, 0);
$pdf->AddPage();
/ $pdf->SetFontSize(8);
$displayBorders = 1;
$valueAlign = "L";
$labelAlign = "L";
$usedHeight = 0;
// Logo on the 1st line
$pdf->SetY($pageMargin);
$pdf->SetX($pageMargin);
$logoPath = '../tesla.png';
$imgWidth = 10;
$headerHeight = 10;
$pdf->Image($logoPath, null, null, $imgWidth, $headerHeight);
$pdf->SetY($pageMargin);
$pdf->SetX($pageMargin+$imgWidth);
$pdf->Cell($maxContentW-$imgWidth, $headerHeight, 'Non English chars: ěščřžýáíéúů', $displayBorders, 0, 'C', false);
$usedHeight+= $headerHeight;
$usedHeight+=10;
$pdf->SetY($pageMargin);
$pdf->SetX($pageMargin+$imgWidth);
$pdf->Cell($maxContentW-$imgWidth, 10, 'Non English chars: ěščřžýáíéúů', $displayBorders, 0, 'C', false);
$pdf->SetY($pageMargin + $usedHeight);
$pdf->SetX($pageMargin);
$pdf->Cell(30, 10, 'Customer number:', $displayBorders, 0, 'R', false);
$pdf->SetFont('DejaVu','B',14);
$pdf->SetY($pageMargin + $usedHeight);
$pdf->SetX($pageMargin + 30);
$pdf->Cell(20, 10, 'ABC123', $displayBorders, 0, 'L', false);
$pdf->Output('D', 'hello.pdf');
Note to tFPFD: Once you use it, it creates a few PHP and DAT files in folder unifont. Delete them before uploading to the internet. They will contain hardcoded paths to fonts and must be recreated.
See part II of this guide:
I will describe how to easily export GridView into CSV so that filers and sorting is kept. I do not use any extentions which are so famous today. Note that GridView is not needed, I just want to show the most complicated situation.
Let's say you have page on URL user/index and it contains GridView where you can list and filter users.
Note: In class yii\data\Sort, in method getAttributeOrders(), is the sorting parameter taken from Yii::$app->getRequest() so the name of the sorted column must be in the URL you are using at the moment. This is why sorting might not work if you want to run UserSearch->search() manually without any GET parameters available in Yii::$app->request->queryParams.
The basic method for exporting DataProvider is here:
public function exportDataProviderToCsv($dataProvider) {
// Setting infinite number of rows per page to receive all pages at once
$dataProvider->pagination->pageSize = -1;
// All text-rows will be placed in this array.
// We will later use implode() to insert separators and join everything into 1 large string
$rows = [];
// UTF-8 header = chr(0xEF) . chr(0xBB) . chr(0xBF)
// Plus column names in format:
// ID;Username;Email etc based on your column names
$rows [] = chr(0xEF) . chr(0xBB) . chr(0xBF) . User::getCsvHeader();
foreach ($dataProvider->models as $m) {
// Method getCsvRow() returns CSV row with values. Example:
// 1;petergreen;peter.green@gmail.com ...
$row = trim($m->getCsvRow());
if ($row!='') {
$rows[] = $row;
}
}
// Here we use implode("\n",$rows) to create large string with rows separated by new lines.
// Double quotes must be used around \n !
$csv = implode("\n", $rows);
$currentDate = date('Y-m-d_H-i-s');
return \Yii::$app->response->sendContentAsFile($csv, 'users_' . $currentDate . '.csv', [
'mimeType' => 'application/csv',
'inline' => false
]);
}
If you want to use it to export data from your GridView, modify your action like this:
public function actionIndex($exportToCsv=false) {
// These 2 rows already existed
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams)
if ($exportToCsv) {
$this->exportDataProviderToCsv($dataProvider);
return;
}
// ...
}
And right above your GridView place this link:
<?php
// Pjax::begin(); // If you are using Pjax for GridView, it must start before following buttons.
?>
<div style="display:flex;flex-direction:row;">
<?= Html::a('+ Create new record', ['create'], ['class' => 'btn btn-success']) ?>
<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Export to CSV <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><?php
echo Html::a('Ignore filters and sorting', ['index', 'exportToCsv' => 1], ['target' => '_blank', 'class' => 'text-left', 'data-pjax'=>'0']);
// 'data-pjax'=>'0' is necessaary to avoid PJAX.
// Now we need to open the link in a new tab, not to resolve it as an ajax request.
?></li>
<li><?php
$csvUrl = \yii\helpers\Url::current(['exportToCsv' => 1]);
echo Html::a('Preserve filters and sorting', $csvUrl, ['target' => '_blank', 'class' => 'text-left', 'data-pjax'=>'0']);
// 'data-pjax'=>'0' is necessaary to avoid PJAX.
// Now we need to open the link in a new tab, not to resolve it as an ajax request.
?></li>
</ul>
</div>
</div>
<php
// Here goes the rest ...
// echo GridView::widget([
// ...
?>
In my code above there were used 2 methods in the model which export things to the CSV format. My implementatino is here:
public static function getCsvHeader() {
$result = [];
$result[] = "ID";
$result[] = "Username";
$result[] = "Email";
// ...
return implode(";", $result);
}
public function getCsvRow() {
$result = [];
$result[] = $this->id;
$result[] = $this->username;
$result[] = $this->email;
// ...
return implode(";", $result);
}
See:
]]>Default date format in Oracle is DD-MON-RR (25-JAN-18). With that output, we can't using date formatting.
Too solve this issue, we must change date format oracle like date commonly using
ALTER SESSION SET NLS_DATE_FORMAT = ...
Add this script inside your database connection file
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'oci:host=127.0.0.1:1521/XE',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
'on afterOpen' => function($event) {
// $event->sender refers to the DB connection
$event->sender->createCommand("ALTER SESSION SET NLS_DATE_FORMAT='DD-MM-YYYY hh24:mi:ss'")->execute();
}
];
]]>Yii 3 and many Yii 2 package sources are contained within src
directory which is convenient since you have less directories to check.
/config
/runtime
/src
/assets
/commands
/controllers
/mail
/models
/views
/widgets
/tests
/vendor
/web
yii
Let's start with the basic applicaiton template.
src
directory.config/web.php
:$config = [
// ...
'basePath' => dirname(__DIR__) . '/src',
'runtimePath' => dirname(__DIR__) . '/runtime',
'vendorPath' => dirname(__DIR__) . '/vendor',
// ...
];
And config/console.php
:
$config = [
// ...
'basePath' => dirname(__DIR__) . '/src',
'runtimePath' => dirname(__DIR__) . '/runtime',
'vendorPath' => dirname(__DIR__) . '/vendor',
// ...
];
That's it now you have both console and web application source code in src
.
The nested set behaviour is an approach to store hierarchical data in relational databases. For example, if we have many categories for our product or items. One category can be a "parent" for other categories, means that one category consists of more than one category. The model can be drawn using a "tree" model. There are other approaches available but what we will learn in this article is specifically the NestedSetsBehavior made by Alexander Kochetov, which utilizing the Modified Preorder Tree Traversal algorithm.
Requirements :
It is always recommended to use Composer to install any kind of package or extension for our Yii2-powered project.
$ composer require creocoder/yii2-nested-sets
In this article, we will use Category
for our model/table name. So we would like to generate the table using our beloved migration tool.
$ ./yii migrate/create create_category_table
We need to modify the table so it contains our desired fields. We also generate three additional fields named position
, created_at
, and updated_at
.
<?php
use yii\db\Migration;
/**
* Handles the creation for table `category`.
*/
class m160611_114633_create_category extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('category', [
'id' => $this->primaryKey(),
'name' => $this->string()->notNull(),
'tree' => $this->integer()->notNull(),
'lft' => $this->integer()->notNull(),
'rgt' => $this->integer()->notNull(),
'depth' => $this->integer()->notNull(),
'position' => $this->integer()->notNull()->defaultValue(0),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
]);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('category');
}
}
Then, generate the table using the migration tool.
$ ./yii migrate
If everything is okay, then you could see that a new table named category
already exists.
To initiate a model, we need to use Gii tool from Yii2. Call the tool from your localhost:8080/gii/model
, and fill in the Table Name field with our existing table: category
. Fill other fields with appropriate values, and don't forget to give a check to "Generate ActiveQuery" checklist item. This will generate another file that needs to be modified later.
Continue to generate the CRUD for our model with CRUD Generator Tool. Fill in each field with our existing model. After all files are generated, you can see that we already have models, controllers, and views but our work is far from done because we need to modify each file.
The first file we should modify is the model file: Category
.
<?php
namespace common\models;
use Yii;
use creocoder\nestedsets\NestedSetsBehavior;
/**
* This is the model class for table "category".
*
* @property integer $id
* @property string $name
* @property integer $tree
* @property integer $lft
* @property integer $rgt
* @property integer $depth
* @property integer $position
* @property integer $created_at
* @property integer $updated_at
*/
class Category extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'category';
}
public function behaviors() {
return [
\yii\behaviors\TimeStampBehavior::className(),
'tree' => [
'class' => NestedSetsBehavior::className(),
'treeAttribute' => 'tree',
// 'leftAttribute' => 'lft',
// 'rightAttribute' => 'rgt',
// 'depthAttribute' => 'depth',
],
];
}
public function transactions()
{
return [
self::SCENARIO_DEFAULT => self::OP_ALL,
];
}
public static function find()
{
return new CategoryQuery(get_called_class());
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['position'], 'default', 'value' => 0],
[['tree', 'lft', 'rgt', 'depth', 'position', 'created_at', 'updated_at'], 'integer'],
[['name'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'tree' => Yii::t('app', 'Tree'),
'lft' => Yii::t('app', 'Lft'),
'rgt' => Yii::t('app', 'Rgt'),
'depth' => Yii::t('app', 'Depth'),
'position' => Yii::t('app', 'Position'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
/**
* Get parent's ID
* @return \yii\db\ActiveQuery
*/
public function getParentId()
{
$parent = $this->parent;
return $parent ? $parent->id : null;
}
/**
* Get parent's node
* @return \yii\db\ActiveQuery
*/
public function getParent()
{
return $this->parents(1)->one();
}
/**
* Get a full tree as a list, except the node and its children
* @param integer $node_id node's ID
* @return array array of node
*/
public static function getTree($node_id = 0)
{
// don't include children and the node
$children = [];
if ( ! empty($node_id))
$children = array_merge(
self::findOne($node_id)->children()->column(),
[$node_id]
);
$rows = self::find()->
select('id, name, depth')->
where(['NOT IN', 'id', $children])->
orderBy('tree, lft, position')->
all();
$return = [];
foreach ($rows as $row)
$return[$row->id] = str_repeat('-', $row->depth) . ' ' . $row->name;
return $return;
}
}
As you can see, we import the extension using the keyword use:
use creocoder\nestedsets\NestedSetsBehavior;
and I also add the TimeStampBehavior
for our additional fields, created_at
and updated_at
\yii\behaviors\TimeStampBehavior::className(),
Next : Our modification to CategoryController
file is at update
, create
, and delete
function.
<?php
namespace backend\controllers;
use Yii;
use common\models\Category;
use common\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CategoryController implements the CRUD actions for Category model.
*/
class CategoryController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Category models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new CategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Category model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Category model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Category();
if ( ! empty(Yii::$app->request->post('Category')))
{
$post = Yii::$app->request->post('Category');
$model->name = $post['name'];
$model->position = $post['position'];
$parent_id = $post['parentId'];
if (empty($parent_id))
$model->makeRoot();
else
{
$parent = Category::findOne($parent_id);
$model->appendTo($parent);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Category model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ( ! empty(Yii::$app->request->post('Category')))
{
$post = Yii::$app->request->post('Category');
$model->name = $post['name'];
$model->position = $post['position'];
$parent_id = $post['parentId'];
if ($model->save())
{
if (empty($parent_id))
{
if ( ! $model->isRoot())
$model->makeRoot();
}
else // move node to other root
{
if ($model->id != $parent_id)
{
$parent = Category::findOne($parent_id);
$model->appendTo($parent);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Category model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
if ($model->isRoot())
$model->deleteWithChildren();
else
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the Category model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Category the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Category::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
As for our views files, we need to remove unnecessary fields from our form, such as the lft
, rgt
, etc, and add the sophisticated parent field to be a dropdown list. This requires a lot of effort, as you can see on the getTree
function on our model.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\models\Category;
/* @var $this yii\web\View */
/* @var $model common\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="category-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<div class='form-group field-attribute-parentId'>
<?= Html::label('Parent', 'parent', ['class' => 'control-label']);?>
<?= Html::dropdownList(
'Category[parentId]',
$model->parentId,
Category::getTree($model->id),
['prompt' => 'No Parent (saved as root)', 'class' => 'form-control']
);?>
</div>
<?= $form->field($model, 'position')->textInput(['type' => 'number']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Complete files can be found at my GitHub page: https://github.com/prabowomurti/learn-nested-set
The screencast (subtitled English) here : https://www.youtube.com/watch?v=MjJEjF1arHs
]]>Register an event handler at Object-Level
e.g inside the init method of a Model
// this should be inside your model class. For example User.php
public function init(){
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);
// first parameter is the name of the event and second is the handler.
// For handlers I use methods sendMail and notification
// from $this class.
parent::init(); // DON'T Forget to call the parent method.
}
from https://stackoverflow.com/questions/28575636/how-to-use-events-in-yii2
Register an event handler at Class-Level
To register event handlers at Class-Level a good place can be inside the bootstrap process.
So, you can put the registration code as
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::debug(get_class($event->sender) . ' is inserted');
});
in a php file like the bootstrap.php
used in Advanced-Template or through configuration, with your custom component for example
see docs
(https://www.yiiframework.com/doc/guide/2.0/en/structure-applications#bootstrap or https://www.yiiframework.com/doc/guide/2.0/en/structure-extensions#bootstrapping-classes)
]]>Note: The information here is outdated. You can check yii-demo for current Yii 3 features.
Since this Wiki page is getting bigger and bigger, I decided to document things in a Yii 3 project instead.
Project source can be found at https://github.com/machour/yii3-kitchen-sink Live web site: https://yii3.idk.tn/
Follow the repo/website to get fresher informations, or better yet, pull the project and run it by yourself to get acquainted with Yii3
This document is intended for an audience already familiar with Yii2. It's meant to bring together all information related to Yii 3 in one place to make it easier to get on track.
Yii 3 is the second major rewrite of the Yii framework.
Originally started in the 2.1 branch, it was later decided to switch to the 3.X series because of all the backward compatibility breakage. Starting with 3.0, Yii will follow the Sementic Versionning.
This rewrite addresses a lot of issues Yii 2 suffered from, like the framework being too coupled with jQuery, bower, bootstrap. [TODO: add more grieffs about Yii2]
Here are the main changes in Yii 3. You can check the complete CHANGELOG for an exhaustive list.
The framework source code have been split into several packages, and at its core level, Yii no longer makes assumptions about your development stack, or the features you will be using.
This enable you to cherry pick the packages you need to compose your application.
This re-organisation is also a great news for maintainance, as these packages will be released separately, thus allowing more frequent updates.
The custom PHP class autoloader have been removed in favor of Composer's PSR-4 implementation.
This means that in order for Yii to see your classes, you will have to explicitly register your namespace in composer.json
. We will see an example later.
Yii 3 takes some positive steps following the PHP-FIG recommendations, by implementing the following PSRs:
If you've ever installed an extension using Yii 2, you may/certainly have found yourself on the extension README file, looking for the chunk of configuration to copy/paste in your own config/main.php
file.
This can often lead to:
Yii 3 takes another approach. Every package bundle its own configuration, and will probably work out of the box. And you may override them, if you need to, from your configuration file.
This is all done by leveraging the hiqdev/composer-config-plugin composer plugin, which takes care of scanning & merging all the configurations when you run composer dump-autoload
(also know as composer du
).
You can read Yii2 projects alternative organization for an in-depth explanation of the motivation behind hiqdev/composer-config-plugin
.
Packages authors will have the responsibility to avoid introducing BC breaks, by adopting a strict sementical versionning.
[TODO]
Here are the new packages introduced in Yii 3, which can be found in this official list.
Let's introduce them briefly:
This is the new kernel of Yii. It defines the base framework and its core features like behaviors, i18n, mail, validation..
You will rarely want to directly install yiisoft/yii-core
. Instead, you will install one or more of the following:
This three packages, considered as Extensions, are responsible for implementing the basic functionnalities of each "channel" they refer to:
yii-console
implements all that you need to build a console application (the base Controller for commands, the Command helper, ..)yii-web
implements all that you need to build a web application (Assets management, Sessions, Request handling ..)yii-rest
implements all that you need to build a REST interface (ActiveController, ..)In Yii 3, libraries do not depend on Yii and are meant to be usable outside the framework.
Their package name is yiisoft/something
without yii-prefix.
The various drivers for DB have also been separated into packages:
Extensions depends (at least) on yii-core. Aside from the 3 extensions already encountered above (yii-console, yii-web, yii-api), these packages are available
This is a very basic Yii project template, that you can use to start your development.
You will probably want to pick one or more of these three starters to install in your project next:
Let's try running the web base template in the next section.
Let's try running a web application using Yii 3, and the provided project template.
composer create-project --prefer-dist --stability=dev yiisoft/yii-project-template myapp
cd myapp
Here's the created structure:
.
├── LICENSE
├── README.md
├── composer.json
├── composer.lock
├── config
│ ├── common.php
│ └── params.php
├── docker-compose.yml
├── hidev.yml
├── public
│ ├── assets
│ ├── favicon.ico
│ ├── index.php
│ └── robots.txt
├── runtime
└── vendor
You won't be able to start the web server right away using ./vendor/bin/yii serve
, as it will complain about not knowing the "app" class.
In fact, this project template only introduce the bare minimum in your application: Caching, Dependencies injection, and Logging. The template doesn't make an assumption about the kind of application you're building (web, cli, api).
You could start from scratch using this bare template, select the extensions & packages you want to use and start developing, or you can pick one of the three starters provided.
web
starter ¶Since we're doing a web application, we will need an asset manager. We can pick either one of those:
Let's go with foxy (personal taste since composer is so slow from Tunisia):
composer require "foxy/foxy:^1.0.0"
We can now install the yii-base-web
starter and run our application:
composer require yiisoft/yii-base-web
vendor/bin/yii serve
By visiting http://localhost:8080/, you should now see something like this:
Checking back our project structure, nothing really changed, aside from the creation of these three entries:
So where do what we see in the browser comes from ?
If you explore the folder in vendor/yiisoft/yii-base-web
, you will see that the template is in fact a project itself, with this structure:
.
├── LICENSE.md
├── README.md
├── composer.json
├── config
│ ├── common.php
│ ├── console.php
│ ├── env.php
│ ├── messages.php
│ ├── params.php
│ └── web.php
├── phpunit.xml.dist
├── public
│ └── css
│ └── site.css
├── requirements.php
├── runtime
└── src
├── assets
│ └── AppAsset.php
├── commands
│ └── HelloController.php
├── controllers
│ └── SiteController.php
├── forms
│ ├── ContactForm.php
│ └── LoginForm.php
├── mail
│ └── layouts
├── messages
│ ├── et
│ ├── pt-BR
│ ├── ru
│ └── uk
├── models
│ └── User.php
├── views
│ ├── layouts
│ └── site
└── widgets
└── Alert.php
The folders and files should make sense to you if you already developed applications using Yii2 and the basic template.
]]>The scenario in which this wiki can be useful is when you have to send an (huge) array of model ids and perform a time consuming computation with it like linking every model to other models. The idea is to split the array into smaller arrays and perform sequential ajax requests, showing the calculation progress using a Bootstrap Progress bar.
I have created a Country model and generated the CRUD operations using Gii. The model class look like this:
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "country".
*
* @property string $code
* @property string $name
* @property int $population
*
*/
class Country extends \yii\db\ActiveRecord {
/**
* {@inheritdoc}
*/
public static function tableName() {
return 'country';
}
/**
* {@inheritdoc}
*/
public function rules() {
return [
[['code', 'name'], 'required'],
[['population'], 'integer'],
[['code'], 'string', 'max' => 3],
[['name'], 'string', 'max' => 52],
[['code'], 'unique'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels() {
return [
'code' => 'Code',
'name' => 'Name',
'population' => 'Population',
];
}
/**
*
* @return array
*/
public static function getCodes(){
return array_keys(ArrayHelper::map(Country::find()->select('code')->asArray()->all(), 'code', 'code'));
}
}
I have also created another model that will take care to validate the ids and perform the time consuming calculation through the process()
function. (in this example I just use a sleep(1)
that will wait for one second for each element of the $codes
array). I also want to keep track of the processed models, incrementing the $processed
class attribute.
<?php
namespace app\models;
use app\models\Country;
/**
* Description of BatchProcessForm
*
* @author toaster
*/
class BatchProcessForm extends \yii\base\Model {
/**
* The codes to process
* @var string
*/
public $codes;
/**
* The number of codes processed
* @var integer
*/
public $processed = 0;
/**
* @return array the validation rules.
*/
public function rules() {
return [
['codes', 'required'],
['codes', 'validateCodes'],
];
}
/**
* Check whether codes exists in the database
* @param type $attribute
* @param type $params
* @param type $validator
*/
public function validateCodes($attribute, $params, $validator) {
$input_codes = json_decode($this->$attribute);
if (null == $input_codes || !is_array($input_codes)) {
$this->addError($attribute, 'Wrong data format');
return;
}
$codes = Country::getCodes();
if (!array_intersect($input_codes, $codes) == $input_codes) {
$this->addError($attribute, 'Some codes selected are not recognized');
}
}
/**
* Process the codes
* @return boolean true if everything goes well
*/
public function process() {
if ($this->validate()) {
$input_codes = json_decode($this->codes);
foreach ($input_codes as $code) {
sleep(1);
$this->processed++;
}
return true;
}
return false;
}
}
The code for the controller action is the following:
/**
* Process an array of codes
* @return mixed
* @throws BadRequestHttpException if the request is not ajax
*/
public function actionProcess(){
if(Yii::$app->request->isAjax){
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new BatchProcessForm();
if($model->load(Yii::$app->request->post()) && $model->process()){
return ['result' => true, 'processed' => $model->processed];
}
return ['result' => false, 'error' => $model->getFirstError('codes')];
}
throw new \yii\web\BadRequestHttpException;
}
In my index.php
view I have added a CheckboxColumn as first column of the Gridview that allows, out of the box, to collect the ids of the models selected via Javascript (in this case the values of the code
attribute). I have also added a button-like hyperlink tag to submit the collected data (with id batch_process
) and a Bootstrap Progress bar inside a Modal Window. The code of my view is the following:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
/* @var $this yii\web\View */
/* @var $searchModel app\models\CountrySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Countries';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="country-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Country', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Batch Process', ['process'], ['class' => 'btn btn-info', 'id' => 'batch_process']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'options' => [
'id' => 'country-index'
],
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'code',
'name',
'population',
['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
<?php Modal::begin(['header' => '<h5 id="progress">0% Complete</h5>', 'id' => 'progress-modal', 'closeButton' => false]); ?>
<?=
yii\bootstrap\Progress::widget([
'percent' => 0,
'options' => ['class' => 'progress-success active progress-striped']
]);
?>
<?php Modal::end(); ?>
<?php $this->registerJsFile('@web/js/main.js', ['depends' => [\app\assets\AppAsset::class]]); ?>
The Javascript file that split in chunks the array and send each chunk sequentially is main.js
. Although I have registered the Javascript file using registerJsFile()
method I highly recommend to better handle and organize js files using Asset Bundles.
Here is the code:
function updateProgressBar(percentage) {
var perc_string = percentage + '% Complete';
$('.progress-bar').attr('aria-valuenow', percentage);
$('.progress-bar').css('width', percentage + '%');
$('#pb-small').text(perc_string);
$('#progress').text(perc_string);
}
function disposeProgressBar(message) {
alert(message);
$('#progress-modal').modal('hide');
}
function showProgressBar() {
var perc = 0;
var perc_string = perc + '% Complete';
$('.progress-bar').attr('aria-valuenow', perc);
$('.progress-bar').css('width', perc + '%');
$('#pb-small').text(perc_string);
$('#progress').text(perc_string);
$('#progress-modal').modal('show');
}
function batchSend(set, iter, take, processed) {
var group = iter + take < set.length ? iter + take : set.length;
var progress = Math.round((group / set.length) * 100);
var dataObj = [];
for (var i = iter; i < group; i++) {
dataObj.push(set[i]);
}
iter += take;
$.ajax({
url: '/country/process', ///?r=country/process
type: 'post',
data: {'BatchProcessForm[codes]': JSON.stringify(dataObj)},
success: function (data) {
if (data.result) {
updateProgressBar(progress);
processed += data.processed;
if (progress < 100) {
batchSend(set, iter, take, processed);
} else {
var plural = processed == 1 ? 'country' : 'countries';
disposeProgressBar(processed + ' ' + plural + ' correctly processed');
}
return true;
}
disposeProgressBar(data.error);
return false;
},
error: function () {
disposeProgressBar('Server error, please try again later');
return false;
}
});
}
$('#batch_process').on('click', function (e) {
e.preventDefault();
var keys = $('#country-index').yiiGridView('getSelectedRows');
if (keys.length <= 0) {
alert('Select at least one country');
return false;
}
var plural = keys.length == 1 ? 'country' : 'countries';
if (confirm(keys.length + ' ' + plural + ' selected.. continue?')) {
showProgressBar();
batchSend(keys, 0, 5, 0);
}
});
The first three functions take care to show, update and hide the progress bar inside the modal window, while the batchSend
function perform the array split and, using recursion, send the data through post ajax request, encoding the array as JSON string and calling itself until there is no more chunks to send. The last lines of code bind the click event of the #batch_process
button checking if at least one row of Gridview has been selected. The number of elements on each array chunk can be set as the third argument of the batchSend
function (in my case 5), you can adjust it accordingly. The first parameter is the whole array obtained by the yiiGridView('getSelectedRows')
function.
The final result is something like this:
...looks cool, isn't it?
]]>Let's assume we have two models: Customer and Supplier and we want both to log in. Yii is quite flexible when it comes to authentication and authorization so it's possible.
First of all, Yii assumes that there's a single type of user component used at once. Still, we're able to create a universal Identity
that works with both customers and suppliers.
So we create models/Identity.php
:
final class Identity implements IdentityInterface
{
const TYPE_CUSTOMER = 'customer';
const TYPE_SUPPLIER = 'supplier';
const ALLOWED_TYPES = [self::TYPE_CUSTOMER, self::TYPE_SUPPLIER];
private $_id;
private $_authkey;
private $_passwordHash;
public static function findIdentity($id)
{
$parts = explode('-', $id);
if (\count($parts) !== 2) {
throw new InvalidCallException('id should be in form of Type-number');
}
[$type, $number] = $parts;
if (!\in_array($type, self::ALLOWED_TYPES, true)) {
throw new InvalidCallException('Unsupported identity type');
}
$model = null;
switch ($type) {
case self::TYPE_CUSTOMER:
$model = Customer::find()->where(['id' => $number])->one();
break;
case self::TYPE_SUPPLIER:
$model = Supplier::find()->where(['id' => $number])->one();
break;
}
if ($model === null) {
return false;
}
$identity = new Identity();
$identity->_id = $id;
$identity->_authkey = $model->authkey;
$identity->_passwordHash = $model->password_hash;
return $identity;
}
public static function findIdentityByAccessToken($token, $type = null)
{
$model = Customer::find()->where(['token' => $token])->one();
if (!$model) {
$model = Supplier::find()->where(['token' => $token])->one();
}
if (!$model) {
return false;
}
if ($model instanceof Customer) {
$type = self::TYPE_CUSTOMER;
} else {
$type = self::TYPE_SUPPLIER;
}
$identity = new Identity();
$identity->_id = $type . '-' . $model->id;
$identity->_authkey = $model->authkey;
$identity->_passwordHash = $model->password_hash;
return $identity;
}
public function validatePassword($password)
{
return password_verify($password, $this->_passwordHash);
}
public static function findIdentityByEmail($email)
{
$model = Customer::find()->where(['email' => $email])->one();
if (!$model) {
$model = Supplier::find()->where(['email' => $email])->one();
}
if (!$model) {
return false;
}
if ($model instanceof Customer) {
$type = self::TYPE_CUSTOMER;
} else {
$type = self::TYPE_SUPPLIER;
}
$identity = new Identity();
$identity->_id = $type . '-' . $model->id;
$identity->_authkey = $model->authkey;
$identity->_passwordHash = $model->password_hash;
return $identity;
}
public function getId()
{
return $this->_id;
}
public function getAuthKey()
{
return $this->_authkey;
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
}
In the above we assume that our ids are like customer-23
or supplier-34
. When we need to get identity instance we split the id by -
and getting both type and integer id for the model corresponding to that type.
Having identity we can tell Yii to use it via config/main.php
:
[
// ...
'components' => [
// ...
'user' => [
'identityClass' => 'app\models\Identity',
'enableAutoLogin' => true,
],
],
],
The only thing left is to adjust models\LoginForm.php
:
class LoginForm extends Model
{
// ...
public function getUser()
{
if ($this->_user === false) {
$this->_user = Identity::findIdentityByEmail($this->username);
}
return $this->_user;
}
}
That's it. Now you can log in using both models.
]]>The definition of breadcrumbs according to its documentation is as follow: Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
We can define the breadcrumbs easily by adding these lines.
$this->title = $model->formNo;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Supplier receiving'), 'url' => ['index', 'type' => $model->type]];
$this->params['breadcrumbs'][] = ['label' => $this->title, 'url' => ['view', 'id' => $model->id]];
Reading the documentation, I encountered the template keyword. I was excited about the possibility to add buttons into breadcrumbs. Add these lines and you would have buttons on the right side of the breadcrumb.
$this->title = $model->formNo;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Supplier receiving'), 'url' => ['index', 'type' => $model->type]];
$this->params['breadcrumbs'][] = ['label' => $this->title, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Delete'), 'template' =>
Html::tag('span', Html::a(Html::icon('glyphicon glyphicon-trash white') . ' ' . Yii::t('app', 'Delete'), Url::to(['delete', 'id' => $model->id]), [
'class' => 'btn btn-xs btn-danger',
'title' => Yii::t('app', 'Delete'),
'data-pjax' => '0',
'data-method' => 'POST',
'data-confirm' => Yii::t('app', 'Are you sure you want to delete this supplier receiving?'),
]
), ['class' => 'pull-right'])];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Update'), 'template' => Html::tag('span', Html::a(
Html::icon('glyphicon glyphicon-pencil') . ' ' . Yii::t('app', 'Update'), Url::to(['update', 'id' => $model->id, 'inview' => 1]), [
'class' => 'btn btn-xs btn-warning',
'title' => Yii::t('app', 'Update'),
'role' => 'modal-remote',
'data-toggle' => 'tooltip',
]
), ['class' => 'pull-right', 'style' => 'margin-right: 5px;'])];
Actually you can use this line to define the template, but $links means the full link. A suggestion to the developer is to make the $url and $label variables to be available like $links, so that we can make the template more flexible and meaningful than above codes.
FYI,
A simple tip to make the view layout efficient.
]]>When to use Active Record is a common question among developers, Yii and overall.
I have about 500K records in my DB tables and each query there are 2 or 3 joins. I was getting data via AR, about a hundred records a time and noticed that using
createCommand
consumes less memory and CPU. I think with DAO instead of AR it will be faster.
It is true that Active Record consumes memory for storing objects and CPU cycles for instantiate these objects.
Is AR bad? Is it for small projects only? We have lots of inserts, about 5000 records an hour and we're using AR for that. Should we re-write?
AR is a pleasure to use when you're managing not that many records at the same time. CRUD is very easy with it. Yii 2 dirty attribute support (only what was modified is saved) off-loads database and mitigates many parallel editing conflicts. If you don't have complex logic in your app and you don't need entity abstractions, AR is an ideal choice.
AR is OK for queries not too complicated when they return no more than a hundred objects. Yes, it is faster and less memory consuming to use query builder or asArray()
but working with arrays is significantly less convenient.
For complex queries, such as aggregates or reports, AR isn't recommended. These are easier to express with query builder or SQL. Same goes for import and export routines.
]]>Yii 2.0 comes with a formatter component to format dates, numbers, and other values for international users according to their locale. This is very useful for displaying data. When working with incoming data or when using enhanced input methods like the MaskedInput widget you sometimes need to access the symbols used by the formatter to generate a pattern or parse the input.
The Yii formatter does not have methods to access this data, it relies on the PHP intl extension for formatting. If you want to access the formatting symbols you need to work with intl directly.
$locale = 'de_DE';
$formatter = new \NumberFormatter($locale,\NumberFormatter::DECIMAL);
$decimalSeparator = $formatter->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
$thousandSeparator = $formatter->getSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
There are more symbols than shown above, for the full list of symbols see the list of NumberFormatter constants in the php manual.
Getting the currency symbol is a bit more complicated if you do not want the symbol of the default currency of a locale, but another currency:
$locale = 'de_DE'; // get the currency symbol of Germanys default currency EUR = "€"
$locale = 'de_DE@currency=USD'; // get the currency symbol of USD in German locale = "$"
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$currencySymbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
Note, that the NumberFormatter
is instantiated with the CURRENCY
constant instead of DECIMAL
here.
Since Yii 2.0.14 Yii has this method built-in in the Locale class.
]]>