[extension] maslosoft/hedron
[extension] maslosoft/manganel
[extension] maslosoft/embedi
[wiki] Pjax GridView: refresh page after delete
Normally, after clicking the delete button in gridview, the record will be deleted and the page will refresh, but the page number in query string is lost. This is not always the case we expect.
How to refresh current page with pjax after deleting the record? It seems there is no very simple solution.
Controller file
public function actionDelete($id) { $this->findModel($id)->delete(); if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['success' => true]; } return $this->redirect(['index']); }
index.php (view file)
<?php $this->registerJs(" $(document).on('ready pjax:success', function() { $('.pjax-delete-link').on('click', function(e) { e.preventDefault(); var deleteUrl = $(this).attr('delete-url'); var pjaxContainer = $(this).attr('pjax-container'); var result = confirm('Delete this item, are you sure?'); if(result) { $.ajax({ url: deleteUrl, type: 'post', error: function(xhr, status, error) { alert('There was an error with your request.' + xhr.responseText); } }).done(function(data) { $.pjax.reload('#' + $.trim(pjaxContainer), {timeout: 3000}); }); } }); }); "); ?> <?php Pjax::begin(['id' => 'my_pjax']); ?> <div class="shop-index"> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ 'id', [ 'class' => 'yii\grid\ActionColumn', 'buttons' => [ 'update' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [ 'class' => 'pjax-update-link', 'title' => Yii::t('yii', 'Update'), ]); }, 'delete' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-trash"></span>', false, [ 'class' => 'pjax-delete-link', 'delete-url' => $url, 'pjax-container' => 'my_pjax', 'title' => Yii::t('yii', 'Delete') ]); } ], ], ], ]); ?> </div> <?php Pjax::end(); ?>
[wiki] How to organize Design "things" in YII2 (themes and layout)
Hello,
after working with YII2 for serveral Years and doing creating systems sharing Information over the web. I'm not a designer, so my look and feel is more functional :).
Sometimes the App needs a nicer look & feel, so its necessary to organize the assets for this and yii can help a lot to make it easy.
Here my tipps for special purposes for handling multiple "Designs".
I use these three features, AssetBundle, Layouts, Themes.
What do you need for desingning your website:
- CSS files,
- JS files and
- some Images or other medias. lets call it "DesignAssets"
What Yii needs:
- one or more Layout files
- the view files
- AssetBundle set in the layout-file lets call it "DesignTemplates"
So how to bundle and where is the best place to put which item?
in your yii app directory
method "theming"
- myYiiApp
- ...
- designs
- myDesign1
- put here all your "DesignTemplates" (AssetBundle,layout, and view folder/files, when using themes)
- myDesign1
OR method "using layouts"
- myYiiApp
- ...
- views
- layouts
- myDesign1.php (layout file)
- ...
- layouts
and for both
myYiiApp
- ...
web
- designs
- myDesign1
- put here all your "DesignAssets" (css, js, img, etc.)
- myDesign1
- designs
...
So you can work with the default security file-rights for the correct purpose.
UseCase one: Write an App and distribute it to some Customer. Here can it be necessary that every customer wants a personal design.
Solution: Using themes
you config in your web.php or main.php (advanced template) whats documented here
if you need special "DesignAssets"
put your "DesignAssets" und the web directory myYiiApp/web/designs/myDesign1/css and js and img folders
customize your myYiiApp/designs/myDesign1/assets/MyDesignAsset.php
and your layout file myYiiApp/designs/myDesign1/layout/main.php
thats it.
UseCase two: you need several designs for e.g. controllers. so my remmmendation is using layouts, because easy switching in controller action.
Solution with layouts
there is no need to configure anything in the config files
if you need special "DesignAssets"
put your "DesignAssets" und the web directory myYiiApp/web/designs/myDesign1/css and js and img folders
create and customize your myYiiApp/assets/MyDesignAsset.php
and your layout file myYiiApp/views/layout/mydesign1.php
in your controller action set your layout.
public function actionIndex() {
$this->layout = 'mydesign1';
}
may it helps your start with designing yii.
[extension] tuyakhov/yii2-json-api
Implementation of JSON API specification for the Yii framework ¶
- Installation
- Data Serializing and Content Negotiation:
- Controlling JSON API output
- Links
- Enabling JSON API Input
- Examples
Installation ¶
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist tuyakhov/yii2-json-api "*"
or add
"tuyakhov/yii2-json-api": "*"
to the require section of your composer.json
file.
Data Serializing and Content Negotiation: ¶
Controller:
`
php
class Controller extends \yii\rest\Controller
{
public $serializer = 'tuyakhov\jsonapi\Serializer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/vnd.api+json' => Response::FORMAT_JSON,
],
]
]);
}
}
By default, the value of `type` is automatically pluralized.
You can change this behavior by setting `tuyakhov\jsonapi\Serializer::$pluralize` property:
php
class Controller extends \yii\rest\Controller
{
public $serializer = [
'class' => 'tuyakhov\jsonapi\Serializer',
'pluralize' => false, // makes {"type": "user"}, instead of {"type": "users"}
];
}
Defining models:
1) Let's define `User` model and declare an `articles` relation
php
use tuyakhov\jsonapi\ResourceTrait;
use tuyakhov\jsonapi\ResourceInterface;
class User extends ActiveRecord implements ResourceInterface {
use ResourceTrait;
public function getArticles()
{
return $this->hasMany(Article::className(), ['author_id' => 'id']);
}
}
2) Now we need to define `Article` model
php
use tuyakhov\jsonapi\ResourceTrait;
use tuyakhov\jsonapi\ResourceInterface;
class Article extends ActiveRecord implements ResourceInterface {
use ResourceTrait;
}
3) As the result `User` model will be serialized into the proper json api resource object:
javascript
{
"data": {
"type": "users",
"id": "1",
"attributes": {
// ... this user's attributes
},
"relationships": {
"articles": {
// ... this user's articles
}
}
}
}
`
Controlling JSON API output ¶
The JSON response is generated by the tuyakhov\jsonapi\JsonApiResponseFormatter
class which will
use the yii\helpers\Json
helper internally. This formatter can be configured with different options like
for example the $prettyPrint
option, which is useful on development for
better readable responses, or $encodeOptions
to control the output
of the JSON encoding.
The formatter can be configured in the yii\web\Response::formatters
property of the response
application
component in the application configuration like the following:
'response' => [
// ...
'formatters' => [
\yii\web\Response::FORMAT_JSON => [
'class' => 'tuyakhov\jsonapi\JsonApiResponseFormatter',
'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
],
],
],
Links ¶
Your resource classes may support HATEOAS by implementing the LinksInterface
.
The interface contains getLinks()
method which should return a list of links.
Typically, you should return at least the self
link representing the URL to the resource object itself.
In order to appear the links in relationships getLinks()
method should return self
link.
Based on this link each relationship will generate self
and related
links.
By default it happens by appending a relationship name at the end of the self
link of the primary model,
you can simply change that behavior by overwriting getRelationshipLinks()
method.
For example,
`
php
class User extends ActiveRecord implements ResourceInterface, LinksInterface
{
use ResourceTrait;
public function getLinks()
{
return [
Link::REL_SELF => Url::to(['user/view', 'id' => $this->id], true),
];
}
}
As the result:
javascript
{
"data": {
"type": "users",
"id": "1",
// ... this user's attributes
"relationships": {
"articles": {
// ... article's data
"links": {
"self": {"href": "http://yourdomain.com/users/1/relationships/articles"},
"related": {"href": "http://yourdomain.com/users/1/articles"}
}
}
}
"links": {
"self": {"href": "http://yourdomain.com/users/1"}
}
}
}
`
Enabling JSON API Input ¶
To let the API accept input data in JSON API format, configure the parsers property of the request application component to use the tuyakhov\jsonapi\JsonApiParser for JSON input
`
php
'request' => [
'parsers' => [
'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser',
]
]
By default it parses a HTTP request body so that you can populate model attributes with user inputs.
For example the request body:
javascript
{
"data": {
"type": "users",
"id": "1",
"attributes": {
"first-name": "Bob",
"last-name": "Homster"
}
}
}
Will be resolved into the following array:
php
// var_dump($_POST);
[
"User" => [
"first_name" => "Bob",
"last_name" => "Homster"
]
]
So you can access request body by calling `\Yii::$app->request->post()` and simply populate the model with input data:
php
$model = new User();
$model->load(\Yii::$app->request->post());
`
By default type users
will be converted into User
(singular, camelCase) which corresponds to the model's formName()
method (which you may override).
You can override the JsonApiParser::formNameCallback
property which refers to a callback that converts 'type' member to form name.
Also you could change the default behavior for conversion of member names to variable names ('first-name' converts into 'first_name') by setting JsonApiParser::memberNameCallback
property.
Examples ¶
Controller:
`
php
class UserController extends \yii\rest\Controller
{
public $serializer = 'tuyakhov\jsonapi\Serializer';
/**
* @inheritdoc
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/vnd.api+json' => Response::FORMAT_JSON,
],
]
]);
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'create' => [
'class' => 'tuyakhov\jsonapi\actions\CreateAction',
'modelClass' => ExampleModel::className()
],
'update' => [
'class' => 'tuyakhov\jsonapi\actions\UpdateAction',
'modelClass' => ExampleModel::className()
],
'view' => [
'class' => 'tuyakhov\jsonapi\actions\ViewAction',
'modelClass' => ExampleModel::className(),
],
'delete' => [
'class' => 'tuyakhov\jsonapi\actions\DeleteAction',
'modelClass' => ExampleModel::className(),
],
'view-related' => [
'class' => 'tuyakhov\jsonapi\actions\ViewRelatedAction',
'modelClass' => ExampleModel::className()
],
'update-relationship' => [
'class' => 'tuyakhov\jsonapi\actions\UpdateRelationshipAction',
'modelClass' => ExampleModel::className()
],
'delete-relationship' => [
'class' => 'tuyakhov\jsonapi\actions\DeleteRelationshipAction',
'modelClass' => ExampleModel::className()
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
}
Model:
```php
class User extends ActiveRecord implements LinksInterface, ResourceInterface
{
use ResourceTrait;
public function getLinks()
{
$reflect = new \ReflectionClass($this);
$controller = Inflector::camel2id($reflect->getShortName());
return [
Link::REL_SELF => Url::to(["$controller/view", 'id' => $this->getId()], true)
];
}
}
Configuration file config/main.php
:
`
php
return [
// ...
'components' => [
'request' => [
'parsers' => [
'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser',
]
],
'response' => [
'format' => \yii\web\Response::FORMAT_JSON,
'formatters' => [
\yii\web\Response::FORMAT_JSON => 'tuyakhov\jsonapi\JsonApiResponseFormatter'
]
],
'urlManager' => [
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'extraPatterns' => [
'GET {id}/<name:\w+>' => 'view-related',
'PATCH {id}/relationships/<name:\w+>' => 'update-relationship',
'DELETE {id}/relationships/<name:\w+>' => 'delete-relationship',
'{id}/<name:\w+>' => 'options'
],
'except' => ['index'],
],
]
]
// ...
]
// ...
]
`
[extension] tuyakhov/yii2-notifications
Notifications for Yii2 ¶
This Yii2 extension provides support for sending notifications across a variety of delivery channels, including mail, SMS, Slack etc. Notifications may also be stored in a database so they may be displayed in your web interface.
Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an "Invoice Paid" notification to your users via the email and SMS channels.
Installation ¶
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist tuyakhov/yii2-notifications "*"
or add
"tuyakhov/yii2-notifications": "*"
to the require section of your composer.json
file.
Usage ¶
The following example shows how to create a Notifier instance and send your first notification:
$notifier = new \tuyakhov\notifications\Notifier([
'channels' => [...],
]);
$notifier->send($recipients, $notifications);
Notifier is often used as an application component and configured in the application configuration like the following:
[
'components' => [
'notifier' => [
'class' => '\tuyakhov\notifications\Notifier',
'channels' => [
'mail' => [
'class' => '\tuyakhov\notifications\channels\MailChannel',
'from' => 'no-reply@example.com'
],
'sms' => [
'class' => '\tuyakhov\notifications\channels\TwilioChannel,
'accountSid' => '...',
'authToken' => '...',
'from' => '+1234567890'
],
'database' => [
'class' => '\tuyakhov\notifications\channels\ActiveRecordChannel'
]
],
],
],
]
Each notification class should implement NotificationInterface and contains a via method and a variable number of message building methods (such as exportForMail
) that convert the notification to a message optimized for that particular channel.
Example of notification that covers the case when an invoice has been paid:
use tuyakhov\notifications\NotificationInterface;
use tuyakhov\notifications\NotificationTrait;
class InvoicePaid implements NotificationInterface
{
use NotificationTrait;
private $invoice;
public function __construct($invoice)
{
$this->invoice = $invoice;
}
public function exportForMail() {
return Yii::createObject([
'class' => '\tuyakhov\notifications\messages\MailMessage',
'view' => ['html' => 'invoice-paid'],
'viewData' => [
'invoiceNumber' => $this->invoice->id,
'amount' => $this->invoice->amount
]
])
}
public function exportForSms()
{
return \Yii::createObject([
'class' => '\tuyakhov\notifications\messages\SmsMessage',
'text' => "Your invoice #{$this->invoice->id} has been paid"
]);
}
}
You may use the NotifiableInterface and NotifiableTrait on any of your models:
`
php
use yii\db\ActiveRecord;
use tuyakhov\notifications\NotifiableTrait;
use tuyakhov\notifications\NotifiableInterface;
class User extends ActiveRecord implements NotifiableInterface {
use NotifiableTrait;
public function routeNotificationForMail()
{
return $this->email;
}
}
`
Database notifications ¶
The database
notification channel stores the notification information in a database table.
You can query the table to display the notifications in your application's user interface. But, before you can do that, you will need to create a database table to hold your notifications. To do this, you can use the migration that comes with this extension:
yii migrate --migrationPath=@vendor/tuyakhov/yii2-notifications/src/migrations
Accessing The Notifications
Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The NotifiableTrait
, which comes with this extension, includes a notifications relationship that returns the notifications for the entity.
To fetch notifications, you may access this method like any other ActiveRecord
relationship.
`
php
$model = User::findOne(1);
foreach($model->notifications as $notification) {
echo $notification->subject;
}
If you want to retrieve only the "unread" notifications, you may use the `unreadNotifications` relationship.
php
$model = User::findOne(1);
foreach($model->unreadNotifications as $notification) {
echo $notification->subject;
}
**Marking Notifications As Read**
Typically, you will want to mark a notification as "read" when a user views it. The `ReadableBehavior` in `Notification` model provides a `markAsRead` method, which updates the read_at column on the notification's database record:
php
$model = User::findOne(1);
foreach($model->unreadNotifications as $notification) {
$notification->markAsRead();
// the following methods are also available
$notification->markAsUnread();
$notification->isUnread();
$notification->isRead();
}
`
[extension] tuyakhov/yii2-youtube
Yii2 youtube extension ¶
Yii2 youtube extension
Installation ¶
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist tuyakhov/yii2-youtube "*"
or add
"tuyakhov/yii2-youtube": "*"
to the require section of your composer.json
file.
Usage ¶
Once the extension is installed, simply use it in your code by :
Widget
\tuyakhov\youtube\EmbedWidget::widget([
'code' => 'vs5ZF9fRDzA',
'playerParameters' => [
'controls' => 2
],
'iframeOptions' => [
'width' => '600',
'height' => '450'
]
]);
Validator
public function rules()
{
return [
['youtube_code', CodeValidator::className()],
];
}
[extension] razonyang/yii-log
Enhanced DB Target for Yii2 Log Component ¶
I wrote this extension for resolving the following problems:
- The logs are chaotic, I cannot distinguish which logs are came from the same requests. It is hard to debug in concurrent scenarios.
- The
yii\log\DbTarget
does not provide rotate feature.
Installation ¶
composer require --prefer-dist razonyang/yii-log
Usage ¶
The usage is similar to yii\log\DbTarget
.
Configuration ¶
[
...
'components' => [
...
'log' => [
'targets' => [
[
'class' => \razonyang\yii\log\DbTarget::class,
'levels' => ['error', 'warning'],
'logTable' => '{{%log}}',
// rotate settings
'rotateInterval' => 100000,
// rotate mutex settings
'rotateMutex' => 'mutex',
'rotateMutexKey' => 'log_rotate',
'rotateMutexAcquireTimeout' => 0,
],
],
],
// mutex is required by log rotate.
'mutex' => [
'class' => \yii\mutex\FileMutex::class,
],
...
],
...
// migrate and rotate settings for console application.
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
...
'@vendor/razonyang/yii-log/src/migrations',
...
],
],
'log' => [
'class' => \razonyang\yii\log\LogController::class,
]
],
...
]
Migrate ¶
./yii migrate
Rotate ¶
./yii log/rotate
[wiki] What SQL-Statement creates yii?
The usual way to find out what Yii has created for an SQL query is to mutilate the SQL in the sourcecode and call the program again so that the SQL statement with errors is displayed. Or you can use the SQL logger, which must be switched on and off each time and logs all SQL statements, which leads to an enormous slowdown in program execution and decelerates your workflow.
These all is not necessary if you use XDebug and place a breakpoint after the function "getCommandBuilder" in the CActiveRecord.php and take a closer look at the return value in $command.
This database access is created in yii:
This code is called by the yii framework
getCommandBuilder returns this data structure with the generated SQL statement:
[extension] johnsnook/yii2-parsel
Yii2 Parsel ¶
Allows developers to provide a boolean search query interface, similar to Google or Sphinx search or other full-text search (FTS) engines.
Turns a user query like 'georgia -(atlanta or decatur)
' into 'georgia AND NOT (atlanta or decatur)
' which is then turn into the follow SQL:
SELECT
"ip", /* ip address */
"visits", /* how many requests they've made */
"city",
"region"
FROM
/* A table similar to apaches access log. See my extension yii2-ipFilter */
"visitor"
WHERE
(
("visitor"."ip" ILIKE '%georgia%')
OR ("visitor"."city" ILIKE '%georgia%')
OR ("visitor"."region" ILIKE '%georgia%')
)
AND ( /** marvel as we efortlessly generate a subquery */
"ip" NOT IN (
SELECT
"ip"
FROM
"visitor"
WHERE
(
("visitor"."ip" ILIKE '%atlanta%')
OR ("visitor"."city" ILIKE '%atlanta%')
OR ("visitor"."region" ILIKE '%atlanta%')
)
OR (
("visitor"."ip" ILIKE '%decatur%')
OR ("visitor"."city" ILIKE '%decatur%')
OR ("visitor"."region" ILIKE '%decatur%')
)
)
)
Example results:
Ip | Visits | City | Region |
---|---|---|---|
107.77.232.216 | 16 | Georgia | |
107.77.235.199 | 3 | Georgia | |
174.218.142.27 | 1 | Lawrenceville | Georgia |
107.77.233.225 | 18 | Georgia | |
205.201.132.14 | 42 | Woodstock | Georgia |
192.3.160.15 | 4 | Douglas | Georgia |
Installation ¶
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist johnsnook/yii2-parsel "*"
or add
"johnsnook/yii2-parsel": "*"
to the require section of your composer.json
file.
Usage ¶
"Look, I didn't know I could speak Parseltongue! What else don't I know about myself? Look. Maybe you can do something, even something horrible and not know you did it."
Once the extension is installed, simply use it in your code by :
$userQuery = 'good AND plenty -licorice';
$parsel = new ParselQuery([
'userQuery' => $this->userQuery,
'dbQuery' => Script::find()
]);
$parsel->dbQuery->all();
Tokens/behavior: ¶
Fields to be search must be either text, varchar or char currently. Future versions may expand to number, dates and maybe even JSON. All search terms, except where specified bye the full match operator are wrapped in your databases wildcard of choice. Searching for "smart" is equivalent to the SQL expression '%smart%'
. Search is case insensitive as long as your database's LIKE
operator is. PostgreSQL will use ILIKE
.
Conjunctives: ¶
'AND' is the default behavior. "smart pretty" is the same as "smart AND pretty."
'OR' allows more results in your query: "smart OR pretty."
Operators: ¶
Operator | Type | Description |
---|---|---|
- | Negation | The user query "smart pretty -judgmental" parses to "smart AND pretty AND NOT judgmental" |
() | Sub-query | Allows grouping of terms . The user query "-crazy (smart AND pretty)" parses to "NOT crazy AND (smart AND pretty)" |
| Wildcard | Fuzzy matches. "butt\" matches butt, buttery, buttered etc. | ||
| Character wildcard | Matches one character. "boo\" matches boot, book, bool, boon, etc. | ||
= | Full match | Entire fields must be equal to the term. "=georgia" only matches where one or more fields is exactly equal to the search term. The search term will NOT be bracketed with %, but wildcards can still be used. |
"" | Double quotes | Phrase. '"Super fun"' searches for the full phrase, space include. Wild cards, negation and exact match operators all work within the phrase. |
'' | Single quotes | Phrase, no wildcards. The term will not be evaluated for or , but will be wrapped in wildcards. If a % or is in the term, it will be escaped. 'P%on' becomes '%P\%on*%'. |
: | Field | Specify the field to search. 'name:jo' will search the name field for 'jo\.' If no field name matches, all fields will be searched for 'name:jo*' |
Examples ¶
See files in /examples. If it's still up, you might also be able to play with an example here
Additional Reading ¶
PostgreSQL
Faster PostgreSQL Searches with Trigrams
Optimizing databases for fuzzy searching
MySQL
Performance analysis of MySQL's FULLTEXT indexes and LIKE queries for full text search
Acknowledgements ¶
This project was built by heavily modifying the excellent "Search Query Parser" project. I de-abstracted the token structure and modified the parser class to better fit my needs. Their licsence file should be found at the root of this project.
Both projects are made possible by the amazing and lightning quick lexer library by Nikita Popov of Berlin. It's work reading his article on the subject.
[extension] kl83/yii2-baron-scrollbar
Yii2 baron scrollbar widget ¶
Baron — a small, fast and crossbrowser custom scrollbar with native system scroll mechanic.
Installation ¶
The preferred way to install this extension is through composer.
Either run
`
php
php composer.phar require kl83/yii2-baron-scrollbar
or add
php
"kl83/yii2-baron-scrollbar": ""
`
to the require section of your composer.json file.
Usage ¶
<?php \kl83\widgets\Scrollbar::begin([
'theme' => \kl83\widgets\Scrollbar::THEME_MACOSX,
'options' => [
'style' => 'height: 30vh',
],
'baronOptions' => [
'cssGuru' => false,
],
]); ?>
<p>Some scrollable content...</p>
<p>Height of parent DOM element must be set.</p>
<?php \kl83\widgets\Scrollbar::end(); ?>
License ¶
MIT License
[extension] kartik-v/yii2-validators
yii2-validators ¶
This extension adds new model validator components for Yii2 frameworkor and/or enhances existing Yii2 model validators.
The EmailValidator
extends the yii\validators\EmailValidator
component to support multiple email inputs for Yii2 framework. In addition this validator allows setting the multiple
property and
setting the min
and max
number of email addresses allowed. This is useful for adding validation rules to your attributes
in the model and also adds enhanced client validation support for ActiveForm inputs at runtime via Javascript.
The PhoneValidator
extends the yii\validators\Validator component
using libphonenumber-for-php based on Google's
libphonenumber library.
The CardValidator
extends the yii\validators\Validator component.
It validates standard debit and credit card number inputs using Luhn's checksum validation. It also helps auto detect the card types and
additionally validating the card holder name, expiry date and CVV entered.
Demo ¶
You can see detailed documentation and demos on usage of this extension.
Installation ¶
The preferred way to install this extension is through composer.
Note: Check the composer.json for this extension's requirements and dependencies. Read this web tip /wiki on setting the
minimum-stability
settings for your application's composer.json.
Either run
$ php composer.phar require kartik-v/yii2-validators "@dev"
or add
"kartik-v/yii2-validators": "@dev"
to the `
require`
section of your composer.json
file.
Usage ¶
EmailValidator ¶
This class extends the yii\validators\EmailValidator
class to offer multiple email validation support. The EmailValidator
class
can be easily used via the alias k-email
in your model validation rules. For example in your model you can use this as shown below:
use yii\db\ActiveRecord;
class EmailModel extends ActiveRecord {
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['to', 'cc', 'bcc'], 'k-email', 'allowName' => true, 'enableIDN' => true, 'max' => 5],
];
}
}
In your view where you render the model inputs with ActiveForm - you may set enableClientValidation
to control whether you need client side validation.
// views/email/send.php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['enableClientValidation' => true]);
echo $form->field($model, 'to')->textInput();
echo $form->field($model, 'cc')->textInput();
echo $form->field($model, 'bcc')->textInput();
// other fields
ActiveForm::end();
PhoneValidator ¶
This class extends the yii\validators\Validator
class to validate phone numbers using
libphonenumber-for-php based on Google's
libphonenumber library. The PhoneValidator
class
can be easily used via the alias k-phone
in your model validation rules. For example in your
model you can use this as shown below:
use yii\db\ActiveRecord;
class ContactModel extends ActiveRecord {
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['phone1'], 'k-phone', 'countryValue' => 'US'],
[['phone2'], 'k-phone', 'countryAttribute' => 'country', 'applyFormat' => false],
];
}
}
CardValidator ¶
The CardValidator
extends the yii\validators\Validator component.
It validates standard debit and credit card number inputs using Luhn's checksum validation. It also helps auto detect the card types and
additionally validating the card holder name, expiry date and CVV entered. The CardValidator
class
can be easily used via the alias k-card
in your model validation rules. For example in your
model you can use this as shown below:
use yii\db\ActiveRecord;
class PaymentModel extends ActiveRecord {
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[
['card_number'],
'k-card',
'typeAttribute' => 'card_type',
'holderAttribute' => 'holderName',
'expiryYearAttribute' => 'expiryYear',
'expiryMonthAttribute' => 'expiryMonth',
'cvvAttribute' => 'cvv',
],
];
}
}
License ¶
yii2-validators is released under the BSD 3-Clause License. See the bundled LICENSE.md
for details.
[extension] kartik-v/yii2-number
yii2-number ¶
Note ¶
This extension replaces the yii2-money extension since Jan 2018. The yii2-money extension will not be enhanced further or supported.
A number control input for Yii2 Framework that uses the jQuery input mask plugin (available also via yii/widgets/MaskedInputAsset
) to render number input masks. This extension is similar to the DateControl extension for dates, and allows one to control the display and save formats for numbers. The extension thus allows one to setup a number format display mask, use currency prefixes if needed, and modify the decimals and thousand separators. It lastly allow the display fields to be auto calculated as numbers when stored into the database.
Refer detailed documentation and demos.
Latest Release ¶
The latest version of the module is v1.0.3. Refer the CHANGE LOG for details.
Install ¶
Either run
$ php composer.phar require kartik-v/yii2-number "@dev"
or add
"kartik-v/yii2-number": "@dev"
to the `
require`
section of your composer.json
file.
Usage ¶
use kartik\number\NumberControl;
// Normal decimal
echo NumberControl::widget([
'name' => 'normal-decimal',
'value' => 43829.39,
]);
// Integer only
echo NumberControl::widget([
'name' => 'integer-only',
'value' => 32892,
'maskedInputOptions' => ['digits' => 0],
]);
// Currency style with prefix and suffix
echo NumberControl::widget([
'name' => 'currency-num',
'value' => 2018032.22,
'maskedInputOptions' => ['prefix' => '$ ', 'suffix' => ' c'],
]);
// Usage with model
$model->currency = 1298132.23;
echo NumberControl::widget([
'model' => $model,
'attribute' => 'currency',
'maskedInputOptions' => ['prefix' => '$ ', 'suffix' => ' c'],
]);
License ¶
yii2-number is released under the BSD-3-Clause License. See the bundled LICENSE.md
for details.
[extension] ayrozjlc/yii2-material-ripple
Yii2 Material Ripple ¶
***
AssetBundle for material-ripple
Installation ¶
Composer ¶
composer require --prefer-dist "ayrozjlc/yii2-material-ripple:*"
or add
"ayrozjlc/yii2-material-ripple": "dev-master"
to the `
require`
section of your composer.json
file.
Usage ¶
in view (for example: `
@app/views/layouts/main.php`
)
// ...
use ayrozjlc\ripple\RippleAsset;
// ...
RippleAsset::register($this);
or add to your `
assets/AppAsset.php`
public $depends = [
// ...
'ayrozjlc\ripple\RippleAsset',
];
[extension] ayrozjlc/yii2-blockui
Yii2 BlockUI ¶
***
AssetBundle for jQuery BlockUI Plugin http://jquery.malsup.com/block/
Installation ¶
Composer ¶
composer require --prefer-dist "ayrozjlc/yii2-blockui:*"
or add
"ayrozjlc/yii2-blockui": "dev-master"
to the `
require`
section of your composer.json
file.
Usage ¶
in view (for example: `
@app/views/layouts/main.php`
)
// ...
use ayrozjlc\blockui\BlockUiAsset;
// ...
BlockUiAsset::register($this);
or add to your `
assets/AppAsset.php`
public $depends = [
// ...
'\ayrozjlc\blockui\BlockUiAsset',
];
[extension] newerton/api-correios
Biblioteca do Correios ¶
Está biblioteca está configurada para o funcionamento correto no Yii Framework.
Exemplo:
`
php
$correio = new Correios;
$address["cep_origem"] = $cep_origem;
if (Yii::app()->user->isGuest) {
$address["cep_destino"] = $cep;
} else {
$address["cep_destino"] = Yii::app()->user->cep;
}
try {
$rows = $correio->getQuote($address);
$this->renderPartial("index", array("rows" => $rows));
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
`
O funcionamento de buscar os produtos do carrinho:
`
php
class Shop {
public static function getCartContent() {
if (is_string(Yii::app()->user->getState("carrinho")))
return json_decode(Yii::app()->user->getState("carrinho"), true);
else
return Yii::app()->user->getState("carrinho");
}
public static function setCartContent($cart) {
return Yii::app()->user->setState("carrinho", json_encode($cart));
}
}
`
Controller que adiciona os produtos a sessão:
`
php
class CarrinhoController extends Controller {
public function actionAdd($id) {
$new = true;
$cart = Shop::getCartContent();
if (!is_null($cart)) {
foreach ($cart as $key => $value) {
if (($value["id"] == $id)) {
$new = false;
$cart[$key]["quant"] += 1;
}
}
}
if ($new)
$cart[] = array("id" => $id, "quant" => 1);
Shop::setCartcontent($cart);
$this->redirect(Yii::app()->createAbsoluteUrl("cart"));
}
}
`
[extension] newerton/yii2-fancybox
yii2-fancybox ¶
fancyBox is a tool that offers a nice and elegant way to add zooming functionality for images, html content and multi-media on your webpages. http://fancyapps.com/fancybox/
Installation ¶
The preferred way to install this extension is through composer.
Either run
php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"
php composer.phar require --prefer-dist newerton/yii2-fancybox "dev-master"
or add
"newerton/yii2-fancybox": "dev-master"
to the require section of your composer.json
file.
Usage ¶
Once the extension is installed, simply use it in your code by :
<?php
echo newerton\fancybox\FancyBox::widget([
'target' => 'a[rel=fancybox]',
'helpers' => true,
'mouse' => true,
'config' => [
'maxWidth' => '90%',
'maxHeight' => '90%',
'playSpeed' => 7000,
'padding' => 0,
'fitToView' => false,
'width' => '70%',
'height' => '70%',
'autoSize' => false,
'closeClick' => false,
'openEffect' => 'elastic',
'closeEffect' => 'elastic',
'prevEffect' => 'elastic',
'nextEffect' => 'elastic',
'closeBtn' => false,
'openOpacity' => true,
'helpers' => [
'title' => ['type' => 'float'],
'buttons' => [],
'thumbs' => ['width' => 68, 'height' => 50],
'overlay' => [
'css' => [
'background' => 'rgba(0, 0, 0, 0.8)'
]
]
],
]
]);
echo Html::a(Html::img('/folder/thumb.jpg'), '/folder/imagem.jpg', ['rel' => 'fancybox']);
?>
Hint: Do not forget to declare the Html class at the top of the file.
use yii\helpers\Html;
[extension] newerton/yii2-fancybox-3
yii2-fancybox-3 ¶
jQuery lightbox script for displaying images, videos and more. Touch enabled, responsive and fully customizable. http://fancyapps.com/fancybox/3/
Installation ¶
- The minimum required PHP version is PHP 5.6 (Concatenation).
- It works best with PHP 7.
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist newerton/yii2-fancybox-3 "*"
or add
"newerton/yii2-fancybox-3": "*"
to the require section of your composer.json
file.
Usage ¶
Once the extension is installed, simply use it in your code by :
<?php
echo newerton\fancybox3\FancyBox::widget();
Options ¶
<?php
echo newerton\fancybox3\FancyBox::widget([
'target' => '[data-fancybox]',
'config' => [
// Enable infinite gallery navigation
'loop' => true,
// Space around image, ignored if zoomed-in or viewport smaller than 800px
'margin' => [44,0],
// Horizontal space between slides
'gutter' => 30,
// Enable keyboard navigation
'keyboard' => true,
// Should display navigation arrows at the screen edges
'arrows' => true,
// Should display infobar (counter and arrows at the top)
'infobar' => true,
// Should display toolbar (buttons at the top)
'toolbar' => true,
// What buttons should appear in the top right corner.
// Buttons will be created using templates from `btnTpl` option
// and they will be placed into toolbar (class="fancybox-toolbar"` element)
'buttons' => [
'slideShow',
'fullScreen',
'thumbs',
'close'
],
// Detect "idle" time in seconds
'idleTime' => 4,
// Should display buttons at top right corner of the content
// If 'auto' - they will be created for content having type 'html', 'inline' or 'ajax'
// Use template from `btnTpl.smallBtn` for customization
'smallBtn' => 'auto',
// Disable right-click and use simple image protection for images
'protect' => false,
// Shortcut to make content "modal" - disable keyboard navigtion, hide buttons, etc
'modal' => false,
'image' => [
// Wait for images to load before displaying
// Requires predefined image dimensions
// If 'auto' - will zoom in thumbnail if 'width' and 'height' attributes are found
'preload' => "auto",
],
'ajax' => [
// Object containing settings for ajax request
'settings' => [
// This helps to indicate that request comes from the modal
// Feel free to change naming
'data' => [
'fancybox' => true
]
]
],
'iframe' => [
// Iframe template
'tpl' => '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen allowtransparency="true" src=""></iframe>',
// Preload iframe before displaying it
// This allows to calculate iframe content width and height
// (note: Due to "Same Origin Policy", you can't get cross domain data). 'preload' => true,
// Custom CSS styling for iframe wrapping element
'css' => [],
// Iframe tag attributes
'attr' => [
'scrolling' => 'auto'
]
],
// Open/close animation type
// Possible values:
// false - disable
// "zoom" - zoom images from/to thumbnail
// "fade"
// "zoom-in-out"
//
'animationEffect' => "zoom",
// Duration in ms for open/close animation
'animationDuration' => 366,
// Should image change opacity while zooming
// If opacity is 'auto', then opacity will be changed if image and thumbnail have different aspect ratios
'zoomOpacity' => 'auto',
// Transition effect between slides
//
// Possible values:
// false - disable
// "fade'
// "slide'
// "circular'
// "tube'
// "zoom-in-out'
// "rotate'
//
'transitionEffect' => "fade",
// Duration in ms for transition animation
'transitionDuration' => 366,
// Custom CSS class for slide element
'slideClass' => '',
// Custom CSS class for layout
'baseClass' => '',
// Base template for layout
'baseTpl' => '<div class="fancybox-container" role="dialog" tabindex="-1">' .
'<div class="fancybox-bg"></div>' .
'<div class="fancybox-controls">' .
'<div class="fancybox-infobar">' .
'<button data-fancybox-previous class="fancybox-button fancybox-button--left" title="Previous"></button>' .
'<div class="fancybox-infobar__body">' .
'<span class="js-fancybox-index"></span> / <span class="js-fancybox-count"></span>' .
'</div>' .
'<button data-fancybox-next class="fancybox-button fancybox-button--right" title="Next"></button>' .
'</div>' .
'<div class="fancybox-buttons">' .
'<button data-fancybox-close class="fancybox-button fancybox-button--close" title="Close (Esc)"></button>' .
'</div>' .
'</div>' .
'<div class="fancybox-slider-wrap">' .
'<div class="fancybox-slider"></div>' .
'</div>' .
'<div class="fancybox-caption-wrap"><div class="fancybox-caption"></div></div>' .
'</div>',
// Loading indicator template
'spinnerTpl' => '<div class="fancybox-loading"></div>',
// Error message template
'errorTpl' => '<div class="fancybox-error"><p>The requested content cannot be loaded. <br /> Please try again later.<p></div>',
'btnTpl' => [
'slideShow' => '<button data-fancybox-play class="fancybox-button fancybox-button--play" title="{{PLAY_START}}"></button>',
'fullScreen' => '<button data-fancybox-fullscreen class="fancybox-button fancybox-button--fullscreen" title="{{FULL_SCREEN}}"></button>',
'thumbs' => '<button data-fancybox-thumbs class="fancybox-button fancybox-button--thumbs" title="{{THUMBS}}"></button>',
'close' => '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="{{CLOSE}}"></button>',
// This small close button will be appended to your html/inline/ajax content by default,
// if "smallBtn" option is not set to false
'smallBtn' => '<button data-fancybox-close class="fancybox-close-small" title="{{CLOSE}}"></button>'
],
// Container is injected into this element
'parentEl' => 'body',
// Focus handling
// ==============
// Try to focus on the first focusable element after opening
'autoFocus' => true,
// Put focus back to active element after closing
'backFocus' => true,
// Do not let user to focus on element outside modal content
'trapFocus' => true,
// Module specific options
// =======================
'fullScreen' => [
'autoStart' => false,
],
'touch' => [
'vertical' => true, // Allow to drag content vertically
'momentum' => true // Continue movement after releasing mouse/touch when panning
],
// Hash value when initializing manually,
// set `false` to disable hash change
'hash' => null,
// Customize or add new media types
// Example:
//
// media' => {
// youtube' => {
// params' => {
// autoplay' => 0
// }
// }
// }
'media' => [],
'slideShow' => [
'autoStart' => false,
'speed' => 4000
],
'thumbs' => [
'autoStart' => false, // Display thumbnails on opening
'hideOnClose' => true // Hide thumbnail grid when closing animation starts
],
// Callbacks
//==========
// See Documentation/API/Events for more information
// Example:
//
// afterShow: function( instance, current ) {
// console.info( 'Clicked element:' );
// console.info( current.opts.$orig );
// }
'onInit' => new \yii\web\JsExpression('function(){ console.log("onInit"); }'),
'beforeLoad' => new \yii\web\JsExpression('function(){ console.log("beforeLoad"); }'),
'afterLoad' => new \yii\web\JsExpression('function(){ console.log("afterLoad"); }'),
'beforeShow' => new \yii\web\JsExpression('function(){ console.log("beforeShow"); }'),
'afterShow' => new \yii\web\JsExpression('function(){ console.log("afterShow"); }'),
'beforeClose' => new \yii\web\JsExpression('function(){ console.log("beforeClose"); }'),
'afterClose' => new \yii\web\JsExpression('function(){ console.log("afterClose"); }'),
'onActivate' => new \yii\web\JsExpression('function(){ console.log("onActivate"); }'),
'onDeactivate' => new \yii\web\JsExpression('function(){ console.log("onDeactivate"); }'),
// Interaction
// ===========
// Use options below to customize taken action when user clicks or double clicks on the fancyBox area,
// each option can be string or method that returns value.
//
// Possible values:
// "close" - close instance
// "next" - move to next gallery item
// "nextOrClose" - move to next gallery item or close if gallery has only one item
// "toggleControls" - show/hide controls
// "zoom" - zoom image (if loaded)
// false - do nothing
// Clicked on the content
'clickContent' => new \yii\web\JsExpression('function( current, event ) {
return current.type === "image" ? "zoom" : false;
}'),
// Clicked on the slide
'clickSlide' => 'close',
// Clicked on the background (backdrop) element
'clickOutside' => 'close',
// Same as previous two, but for double click
'dblclickContent' => false,
'dblclickSlide' => false,
'dblclickOutside' => false,
// Custom options when mobile device is detected
// =============================================
'mobile' => [
'clickContent' => new \yii\web\JsExpression('function( current, event ) {
return current.type === "image" ? "toggleControls" : false;
}'),
'clickSlide' => new \yii\web\JsExpression('function( current, event ) {
return current.type === "image" ? "toggleControls" : "close";
}'),
'dblclickContent' => new \yii\web\JsExpression('function( current, event ) {
return current.type === "image" ? "zoom" : "close";
}'),
'dblclickSlide' => new \yii\web\JsExpression('function( current, event ) {
return current.type === "image" ? "zoom" : "close";
}'),
],
// Internationalization
// ============
'lang' => 'en',
'i18n' => [
'en' => [
'CLOSE' => 'Close',
'NEXT' => 'Next',
'PREV' => 'Previous',
'ERROR' => 'The requested content cannot be loaded. <br/> Please try again later.',
'PLAY_START' => 'Start slideshow',
'PLAY_STOP' => 'Pause slideshow',
'FULL_SCREEN' => 'Full screen',
'THUMBS' => 'Thumbnails'
],
'de' => [
'CLOSE' => 'Schliessen',
'NEXT' => 'Weiter',
'PREV' => 'Zurück',
'ERROR' => 'Die angeforderten Daten konnten nicht geladen werden. <br/> Bitte versuchen Sie es später nochmal.',
'PLAY_START' => 'Diaschau starten',
'PLAY_STOP' => 'Diaschau beenden',
'FULL_SCREEN' => 'Vollbild',
'THUMBS' => 'Vorschaubilder'
]
]
]
]);
echo yii\helpers\Html::a(yii\helpers\Html::img('/folder/thumb.jpg'), '/folder/imagem.jpg', ['data-fancybox' => true]);
?>
[extension] newerton/yii2-boleto-remessa
Yii2 Boleto, Remessa e Retorno ¶
Pacote para gerar boletos, remessas e leitura de retorno.
Requerimentos ¶
Links ¶
Bancos suportados ¶
Banco | Boleto | Remessa 400 | Remessa 240 | Retorno 400 | Retorno 240 |
---|---|---|---|---|---|
Banco do Brasil | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Bancoob (Sicoob) | :eight_pointed_black_star: | :white_check_mark: | :eight_pointed_black_star: | :eight_pointed_black_star: | |
Banrisul | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Bradesco | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Caixa | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Hsbc | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Itau | :white_check_mark: | :white_check_mark: | :white_check_mark: | ||
Santander | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Sicredi | :white_check_mark: | :white_check_mark: | :eight_pointed_black_star: | ||
Banco do Nordeste | :eight_pointed_black_star: | :eight_pointed_black_star: |
:eight_pointed_black_star: necessita de homologação
Instalação ¶
Via composer:
composer require newerton/yii2-boleto-remessa
Ou adicione manualmente ao seu composer.json:
"newerton/yii2-boleto-remessa": "dev-master"
Gerar boleto ¶
Criando o beneficiário ou pagador ¶
$beneficiario = new \Newerton\Yii2Boleto\Pessoa([
'nome' => 'ACME',
'endereco' => 'Rua um, 123',
'cep' => '99999-999',
'uf' => 'UF',
'cidade' => 'CIDADE',
'documento' => '99.999.999/9999-99',
]);
$pagador = new \Newerton\Yii2Boleto\Pessoa([
'nome' => 'Cliente',
'endereco' => 'Rua um, 123',
'bairro' => 'Bairro',
'cep' => '99999-999',
'uf' => 'UF',
'cidade' => 'CIDADE',
'documento' => '999.999.999-99',
]);
Criando o objeto boleto ¶
Campos númericos e suas funções ¶
- numero: campo numérico utilizado para a criação do nosso numero. (identificação do título no banco)*
- numeroControle: campo de livre utilização. até 25 caracteres. (identificação do título na empresa)
- numeroDocumento: campo utilizado para informar ao que o documento se referente (duplicata, nf, np, ns, etc...)
$boletoArray = [
'logo' => 'path/para/o/logo', // Logo da empresa
'dataVencimento' => new \Carbon\Carbon('1790-01-01'),
'valor' => 100.00,
'multa' => 10.00, // porcento
'juros' => 2.00, // porcento ao mes
'juros_apos' => 1, // juros e multa após
'diasProtesto' => false, // protestar após, se for necessário
'numero' => 1,
'numeroDocumento' => 1,
'pagador' => $pagador, // Objeto PessoaContract
'beneficiario' => $beneficiario, // Objeto PessoaContract
'agencia' => 9999, // BB, Bradesco, CEF, HSBC, Itáu
'agenciaDv' => 9, // se possuir
'conta' => 99999, // BB, Bradesco, CEF, HSBC, Itáu, Santander
'contaDv' => 9, // Bradesco, HSBC, Itáu
'carteira' => 99, // BB, Bradesco, CEF, HSBC, Itáu, Santander
'convenio' => 9999999, // BB
'variacaoCarteira' => 99, // BB
'range' => 99999, // HSBC
'codigoCliente' => 99999, // Bradesco, CEF, Santander
'ios' => 0, // Santander
'descricaoDemonstrativo' => ['msg1', 'msg2', 'msg3'], // máximo de 5
'instrucoes' => ['inst1', 'inst2'], // máximo de 5
'aceite' => 1,
'especieDoc' => 'DM',
];
$boleto = new \Newerton\Yii2Boleto\Boleto\Banco\Bb($boletoArray);
Gerando o boleto ¶
Gerando o boleto a partir da instância do objeto (somente um boleto)
$boleto->renderPDF();
// ou
$boleto->renderHTML();
// Os dois métodos aceitam como parâmetro dois booleanos.
// 1º Se True, após renderizado, irá mostrar a janela de impressão. O Valor default é false.
// 2º Se False, irá esconder as instruções de impressão. O valor default é true.
$boleto->renderPDF(true, false); // mostra a janela de impressão e esconde as instruções de impressão
/*
* O comportamento padrão para os métodos renderPDF() e renderHTML() é retornar uma string pura.
* Para gerar um retorno no controller do yii2, utilize da seguinte forma:
*/
// PDF
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/pdf');
$headers->add('Content-Disposition', 'nline; boleto.pdf');
return $boleto->renderPDF();
// HTML
return $boleto->renderHTML();
Gerando boleto a partir da instância do render
// Gerar em PDF
$pdf = new \Newerton\Yii2Boleto\Boleto\Render\Pdf();
$pdf->addBoleto($boleto);
// Ou, para adicionar um array de boletos
$pdf->addBoletos($boletos);
// Quando não informado parâmetros ele se comportará como Pdf::OUTPUT_STANDARD, enviando o buffer do pdf com os headers apropriados.
$pdf->gerarBoleto();
// Para mostrar a janela de impressão no load do PDF
$pdf->showPrint();
// Para remover as intruções de impressão
$pdf->hideInstrucoes();
// O método gerarBoleto() da classe PDF aceita como parâmetro:
// 1º destino: constante com os destinos disponíveis. Ex: Pdf::OUTPUT_SAVE.
// 2º path: caminho absoluto para salvar o pdf quando o destino for Pdf::OUTPUT_SAVE.
//Ex:
$pdf->gerarBoleto(Pdf::OUTPUT_SAVE, Yii::getAlias('@webroot/boletos/meu_boleto.pdf')); // salva o boleto na pasta.
$pdf_inline = $pdf->gerarBoleto(Pdf::OUTPUT_STRING); // retorna o boleto em formato string.
$pdf->gerarBoleto(Pdf::OUTPUT_DOWNLOAD); // força o download pelo navegador.
// Gerar em HTML
$html = new \Newerton\Yii2Boleto\Boleto\Render\Html();
$html->addBoleto($boleto);
// Ou para adicionar um array de boletos
$html->addBoletos($boletos);
// Para mostrar a janela de impressão no load da página
$html->showPrint();
// Para remover as intruções de impressão
$html->hideInstrucoes();
$html->gerarBoleto();
Gerar remessa ¶
$remessaArray = [
'agencia' => 9999,
'agenciaDv' => 9, // se possuir
'conta' => 99999,
'contaDv' => 9, // se possuir
'carteira' => 99,
'convenio' => 9999999, // se possuir
'range' => 99999, // se possuir
'codigoCliente' => 99999, // se possuir
'variacaoCarteira' => 99, // se possuir
'beneficiario' => $beneficiario,
];
$remessa = new \Newerton\Yii2Boleto\Cnab\Remessa\Cnab400\Banco\Bb($remessaArray);
// Adicionar um boleto
$remessa->addBoleto($boleto);
// Ou para adicionar um array de boletos
$boletos = [];
$boletos[] = $boleto1;
$boletos[] = $boleto2;
$boletos[] = $boleto3;
$remessa->addBoletos($boletos);
echo $remessa->gerar();
Tratar retorno ¶
$retorno = \Newerton\Yii2Boleto\Cnab\Retorno\Factory::make('full_path_arquivo_retorno');
$retorno->processar();
echo $retorno->getBancoNome();
// Retorno implementa \SeekableIterator, sendo assim, podemos utilizar o foreach da seguinte forma:
foreach($retorno as $registro) {
var_dump($registro->toArray());
}
// Ou também podemos:
$detalheCollection = $retorno->getDetalhes();
foreach($detalheCollection as $detalhe) {
var_dump($detalhe->toArray());
}
// Ou até mesmo do jeito laravel
$detalheCollection->each(function ($detalhe, $index) {
var_dump($detalhe->toArray())
});
Métodos disponíveis:
$retorno->getDetalhes();
$retorno->getHeader();
$retorno->getTrailer();