Posts Tagged with yii

Displaying 11-20 of 113 results.
Wiki: Yii2 beforeSave() and afterSave()wiki
posted by admin on February 22, 2017
Wonderful methods beforeSave () and afterSave () in Yii2 help us to solve various problems, for example, you want before saving the database to change the date format, or save the log action. But not everyone knows how to inherit them.

Let's start with a simple afterSave():

public function afterSave($insert, $changedAttributes){
parent::afterSave($insert, $changedAttributes);
//... to do
}

There is nothing complicated, we simply pass to the parent method all the same settings and run it, and then do everything we needed.

Now beforeSave():

public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
//... to do
return true;
}
return false;
}

All the practical as well as with afterSave() method, except that we need to return the result of the parent method, otherwise we when calling $model->save() will get false, and our model will not be saved, nor do we we will receive no errors. Remember this moment.

Yii1 The principle is the same, only the parameters are not transferred there.Read more
Resolved: Yii2 Class 'app\models\TimestampBehavior' not found
posted by admin on February 21, 2017
I have User model and have behavior in model

<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use app\helpers\Table;
use app\helpers\App;
/**
* This is the model class for table "tbl_user".
*
* @property integer $id
* @property string $username
* @property string $password
* @property string $email
* @property integer $role_id
* @property integer $user_id
* @property integer $status_id
* @property integer $created_dt
* @property integer $updated_dt
* @property integer $timezone_id
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
public $authKey;
public $accessToken;

/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%'.Table::$user.'}}';
}

public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'creation_time',
ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
],
'value' => function() { return App::datetime_now_unix(); },
],
];
}
. . .
}

Error

Class 'app\models\TimestampBehavior' not found
Read more
Resolved: Yii2 required rule not show red star(asterisk) symbol
posted by admin on February 21, 2017
I have form and I have required fields
In output not showing red asterisk(star).
How to resolve it?Read more
Resolved: Yii2 NavBar check isGuest leave empty or fill with multiple items
posted by admin on February 21, 2017

<?php
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use app\helpers\App;
use yii\helpers\Html;

NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => App::t('Home'), 'url' => ['/site/index']],
Yii::$app->user->isGuest ? (
['label' => App::t('Login'), 'url' => ['/site/login']]
) : (
'<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
App::t('Logout').' (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']
)
. Html::endForm()
. '</li>'
),
],
]);
NavBar::end();
?>

I want to add functionality like these:
1. I want to leave else empty
example

Yii::$app->user->isGuest ? (
['label' => App::t('Sign up', 'app2'), 'url' => ['/site/registration']]
) : (
[]//want to leave empty
),

2. I want multiple array
example

Yii::$app->user->isGuest ? (
['label' => App::t('Sign up0', 'app2'), 'url' => ['/site/zczczcxz']],
['label' => App::t('Sign up1', 'app2'), 'url' => ['/site/qweqweqe']],
['label' => App::t('Sign up2', 'app2'), 'url' => ['/site/asdasd']]
) : (
['label' => App::t('Sign up4', 'app2'), 'url' => ['/site/oipoiopi']],
['label' => App::t('Sign up4', 'app2'), 'url' => ['/site/oipoiopi']]
),

Both example not working and throwing errors, I think there is one decision for both situation with errorsRead more
Resolved: Yii2 The 'label' option is required NavBar
posted by admin on February 21, 2017

<?php
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use app\helpers\App;
use yii\helpers\Html;

NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => App::t('Home'), 'url' => ['/site/index']],
//['label' => 'About', 'url' => ['/site/about']],
//['label' => 'Contact', 'url' => ['/site/contact']],
Yii::$app->user->isGuest ? (
['label' => App::t('Sign up', 'app2'), 'url' => ['/site/registration']]
) : (
[]
),
Yii::$app->user->isGuest ? (
['label' => App::t('Login'), 'url' => ['/site/login']]
) : (
'<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
App::t('Logout').' (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']
)
. Html::endForm()
. '</li>'
),

],
]);
NavBar::end();
?>
Read more
Resolved: Yii PHP DateTime UNIX TimeStamp NOW
posted by admin on February 20, 2017

$date = new DateTime();
return $date->format('U');

Error:

Class 'namespace\DateTime' not found
Read more
Resolved: Yii2 Migration multiple insert
posted by admin on February 20, 2017
I want to insert multiple rows in migration

$this->insert //insert once

I want multipleRead more
Resolved: Yii2 Gii not generating models. Exception problem. Ubuntu 16.04
posted by admin on February 16, 2017
In Gii I have error:

There was something wrong when generating the code. Please check the following messages.

How to resolve itRead more
Resolved: Yii2 Migration execution Exception: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
posted by admin on February 15, 2017
I run my Migration in Yii2 from console and get rsult with errors

> create table {{%user}} ... done (time: 0.126s)
> create index index_user_user_id on {{%user}} (user_id) ... done (time: 0.027s)
> create index index_user_role_id on {{%user}} (role_id) ... done (time: 0.026s)
> create index index_user_status_id on {{%user}} (status_id) ... done (time: 0.027s)
> create table {{%status}} ... done (time: 0.033s)
> create table {{%role}} ... done (time: 0.029s)
> add foreign key fk_user_user_id: {{%user}} (user_id) references {{%user}} (id) ...Exception: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
The SQL being executed was: ALTER TABLE `tbl_user` ADD CONSTRAINT `fk_user_user_id` FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
... some notes here
#15 {main}
*** failed to apply m170213_124818_init (time: 0.313s)


0 from 2 migrations were applied.

Migration failed. The rest of the migrations are canceled.

My migration

class m170213_124818_init extends Migration
{
public function safeUp()
{
/** User Create*/
$this->createTable('{{%'.helpers\Table::$user.'}}', [
'id' => $this->primaryKey(10)->notNull()->unsigned(),
. . .
'user_id' => $this->integer(10),
. . .
], 'ENGINE=InnoDB');
# User Create

/** User Indexes*/
$this->createIndex("index_user_user_id", '{{%'.helpers\Table::$user.'}}', 'user_id');
# User Indexes

/** User FK */
$this->addForeignKey('fk_user_user_id','{{%'.helpers\Table::$user.'}}', 'user_id', '{{%'.helpers\Table::$user.'}}', 'id', 'CASCADE', 'CASCADE');
# User FK

}

public function safeDown()
{
// to do
}
}

How to resolve Exception

Exception: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
The SQL being executed was: ALTER TABLE `tbl_user` ADD CONSTRAINT `fk_user_user_id` FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
Read more
Resolved: Yii2 Error Exception: Class 'Custom class' not found
posted by admin on February 15, 2017
I use in migration classes custom helper class Table, and in migration up process got an error like
Command:

./yii migrate

Result until error

Yii Migration Tool (based on Yii v2.0.11.2)

Total 2 new migrations to be applied:
m170213_124818_init
m170214_092410_domain

Apply the above migrations? (yes|no) [no]:yes
*** applying m170213_124818_init


Error Message:

Exception: Class 'yii\helpers\Table' not found (/var/www/html/basic/migrations/m170213_124818_init.php:10)


My class is in root directory in helpers directory

<?php
namespace yii\helpers;
class Table
{
public static $user = 'user';
public static $role = 'role';
public static $status = 'status';
public static $domain = 'domain';
}


In migration class

<?php
use yii\db\Migration;
use yii\helpers;

class m170213_124818_init extends Migration
{
public function safeUp()
{
/** User Create*/
$this->createTable('{{%'.helpers\Table::$user.'}}', [
'id' => $this->primaryKey(10)->notNull()->unsigned(),
. . .
], 'ENGINE=InnoDB');
}
}


How to resolve itRead more