Relation “migration” already exists error while executing yii migrate

If you use PostgreSQL Database and got error
“Relation “migration” already exists error while executing yii migrate”
Just check your config, it seems that you have a mistake in schema section.
Example:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=yourdb',
            'username' => 'yourdb_user',
            'password' => 'password',
            'charset' => 'utf8',
            'schemaMap' => [
                'pgsql' => [
                    'class' => 'yii\db\pgsql\Schema',
                    'defaultSchema' => 'public'
                ]
            ], // PostgreSQL
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],

Yii requirements.php error after moving to /web folder.

If you get:

Error

The path to yii framework seems to be incorrect.

You need to install Yii framework via composer or adjust the framework path in file requirements.php.

Please refer to the README on how to install Yii.

Warning: require_once({your_site}/web/vendor/yiisoft/yii2/requirements/YiiRequirementChecker.php): failed to open stream: No such file or directory in {your_site}\web\requirements.php on line 23

Fatal error: require_once(): Failed opening required '{your_site}/web/vendor/yiisoft/yii2/requirements/YiiRequirementChecker.php' (include_path='...php\PEAR') in {your_site}\web\requirements.php on line 23

Then just change 14 line on:

$frameworkPath = dirname(__FILE__) . '/../vendor/yiisoft/yii2';

Happy codding.

Fast installing Yii framework

Steps:
0. If you do not already have Composer installed, you may do so by following the instructions at getcomposer.org.
1. Install Yii)

composer global require "fxp/composer-asset-plugin:^1.2.0"

and final

composer create-project --prefer-dist yiisoft/yii2-app-basic my_project_name

That’s all. Happy Codding.
Continue reading Fast installing Yii framework

How to get Swift Mailer Delivery/Failures/Errors Status when you sending emails

Example of send email method with using Swift_Mailer (Swift_SmtpTransport, Swift_Message)
If you want get Delivery/Failures/Errors Status you can use this construction:

 /**
     * Method for sending emails via Swift_Mailer
     * @param $email - object
     * example $email = \new StdClass();
     * $email->login = 'sender@mail.example';
     * $email->password = 'password_of_sender_email';
     * $email->host = 'imap.gmail.com'; //real example for Gmail
     * $email->first_name = 'Test Example Name';
     * $email->to = 'reciepient@mail.example'; //or array ['reciepient1@mail.example','reciepient2@mail.example','reciepient3@mail.example']
     * $email->subject = 'Example of subject';
     * $email->body = 'Example of <br/> email body message';
     * @return boolean
     */
    public static function sendEmail($email)
    {
        $isSent = $failures = false;
        try {
            $transport = \Swift_SmtpTransport::newInstance()->setHost($email->host)->setPort(465)->setUsername($email->login)->setPassword($email->password)->setEncryption('ssl');

            $mailMessage = \Swift_Message::newInstance()->setFrom([$email->login => $email->first_name])->setReturnPath($email->to)->setTo($email->to)->setSubject($email->subject)->setBody($email->body, 'text/html');

            $mailer = \Swift_Mailer::newInstance($transport);

            if ($mailer->send($mailMessage, $failures)) {
                $isSent = true;
                echo ' SUCCESS SENDING!:' . $email->login . ' to ' . $email->to;
            } else {
                echo ' SENDING ERROR TO :' . print_R($failures);
            }
        } catch (\Exception $e) {
            echo 'Catch Error with ' . $email->login . ' : ' . $e->getErrorMessage() . "\n";
        }
        return $isSent;
    }

swift_SmtpTransport / Swift_Message /Swift_Mailer

Yii 2 Response formats: RAW, HTML, JSON, JSONP, XML

If you want that your method return data in specific format in Yii2 then you can use this simple construction:
Example method return in JSON format:

use yii\web\Response;
//......
public function actionJson()
    {
        $something = true; // or you can set for test -> false;
        $return_json = ['status' => 'error'];
        if ($something == true)
        {
            $return_json = ['status' => 'success', 'message' => ' is successfully saved'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $return_json;
    }

/*header results
Connection: Keep-Alive
Content-Length: 55
Content-Type : application/json; charset=UTF-8
*/

Continue reading Yii 2 Response formats: RAW, HTML, JSON, JSONP, XML

How to sort array with objects by object property in Yii 2?

If you want to sort your array with objects by specific property in Yii 2 then you can use beautiful method ArrayHelper::multisort (&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
Example (you have unsorted array ‘history’ with objects):

Array
(
    [0] => stdClass Object
        (
            [sent_date] => 2016-01-28 13:42:10
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [1] => stdClass Object
        (
            [sent_date] => 2016-01-29 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [2] => stdClass Object
        (
            [sent_date] => 2016-01-31 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [3] => stdClass Object
        (
            [sent_date] => 2015-12-01 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

)

Continue reading How to sort array with objects by object property in Yii 2?

Yii 2 database field types

The following abstract column types are supported:

  • pk : an auto-incremental primary key type, will be converted into “int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • bigpk: an auto-incremental primary key type, will be converted into “bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • string: string type, will be converted into “varchar(255)”
  • text: a long string type, will be converted into “text”
  • smallint: a small integer type, will be converted into “smallint(6)”
  • integer: integer type, will be converted into “int(11)”
  • bigint: a big integer type, will be converted into “bigint(20)”
  • boolean: boolean type, will be converted into “tinyint(1)”
  • float: float number type, will be converted into “float”
  • decimal: decimal number type, will be converted into “decimal”
  • datetime: datetime type, will be converted into “datetime”
  • timestamp: timestamp type, will be converted into “timestamp”
  • time: time type, will be converted into “time”
  • date: date type, will be converted into “date”
  • money: money type, will be converted into “decimal(19,4)”
  • binary: binary data type, will be converted into “blob”

 
Continue reading Yii 2 database field types