How do I solve Unknown database error in Yii2? - php

My Friend Suggested me to use Yii2 Framework And sent me all the files of a project he has worked upon, including the .sql file which he exported from phpmyadmin. I am trying to edit the same project (with his permission). After importing the .sql file i changed the database name username and password in \config\db.php and got this error
Database Exception – yii\db\Exception
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Here is my db.php :
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydb',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
Then I Downloaded basic Yii2 application from official Yii Site (which works working fine), then i replaced \controllers\SiteController.php from the directory of the project that my friend sent me with the one i downloaded. To my Surprise the error was gone but it still looked like same as the one i downloaded (The one my friend sent was a educational school website, so it is supposed to look the same).
Here is SiteController.php of the one that my friend sent me
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\User;
use app\models\ContactForm;
use app\modules\admin\models\AdmissionEnquiryForm;
use app\models\Article;
use app\models\ArticleSearch;
use app\modules\admin\models\SidebarModule;
use app\modules\admin\models\SidebarModuleSearch;
use app\modules\admin\models\Gallery;
use app\modules\admin\models\Activities;
use app\modules\admin\models\Newsletter;
use app\modules\admin\models\VisitorCounter;
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public $enableCsrfValidation = false;
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'change-password'],
//'except' =>['login'],
'rules' => [
[
'actions' => ['logout', 'change-password'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return string
*/
/*
public function actionIndex()
{
$model = Article::find()->where(['id' => 1])->one();
return $this->render('index').
$this->renderPartial('//article/overview', [
'model' => $this->findModel(1),
]);
}
public function actionIndex()
{
$this->layout='articles';
return $this->render('index', [
'model' => $this->findModel(1),
]);
}
*/
public function actionIndex()
{
$this->layout='home';
$sidebar=new SidebarModule;
$newsletter= new Newsletter;
/*$counter=new VisitorCounter;
$counter->counter=+1;
$counter->save();
$visits=VisitorCounter::find()->max('id');
$visits->counter=+1;
$visits->save();
//var_dump($visits);
*/
$visits=VisitorCounter::find()->where(['id'=>1])->One();
$visits->counter=$visits->counter+1;
$visits->save();
$this->view->params['newsletter'] = $newsletter;
// var_dump($_POST);
if ($newsletter->load(Yii::$app->request->post()) && $newsletter->save()) {
//Yii::$app->user->setFlash('success', "you are successfully subscribed to our Newsletter");
Yii::$app->session->setFlash('success', "you are successfully subscribed to our Newsletter");
// $newsletter->email=($_POST['email']);
}
return $this->render('index',['sidebar'=>$sidebar]);
}
/**
* Login action.
*
* #return Response|string
*/
/*
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
*/
public function actionLogin() {
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$this->layout = '#app/themes/backend/login';
$model = new LoginForm(['scenario' => 'login']);
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->redirect(Yii::$app->user->getReturnUrl());
}
return $this->render('login', [
'model' => $model,
]);
}
/**
* Logout action.
*
* #return Response
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return Response|string
*/
public function actionContact()
{
$model = new ContactForm();
$model->subject = "Enquiry from website";
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
//return $this->redirect(Yii::$app->request->referrer);
return $this->render('contact', ['model' => $model]);
}
public function actionAdmissionEnquiryForm()
{
$model = new AdmissionEnquiryForm();
$model->subject = "Enquiry for admission";
if ($model->load(Yii::$app->request->post()) && $model->admission(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('AdmissionEnquiryFormSubmitted');
return $this->refresh();
}
//return $this->redirect(Yii::$app->request->referrer);
return $this->render('AdmissionEnquiryForm', ['model' => $model]);
}
public function actionChangePassword() {
$this->layout = '#app/themes/backend/main';
$userId = Yii::$app->user->identity->id;
$model = User::find()->where(['id' => $userId])->one();
$model->scenario = 'changeP';
if ($model->load(Yii::$app->request->post())) {
$oldpassword = $model->oldpassword;
$password = $model->password;
$hash = $model->password_hash;
$result = Yii::$app->getSecurity()->validatePassword($oldpassword, $hash);
$NewPassword = Yii::$app->getSecurity()->generatePasswordHash($password);
if ($result) {
$model->password_hash = $NewPassword;
$confirm = $model->save();
if ($confirm) {
Yii::$app->session->setFlash('passwordChanged');
$link = Yii::$app->urlManager->createAbsoluteUrl(['site/signin']);
return $this->refresh();
}
} else {
$model->addError('oldpassword', 'Incorrect old password.');
}
}
return $this->render('change-password',
['model' => $model]);
}
/**
* Displays about page.
*
* #return string
*/
public function actionAbout()
{
return $this->render('about');
}
protected function findModel($id)
{
if (($model = Article::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
public function actionGallery($id=null) {
$activities = Activities::find()->where(['status' => 1])->orderBy(['id'=>SORT_DESC])->all();
$model = Activities::find()->where(['id' => $id])->one();
// var_dump($model1);
$latestActivity = Activities::find()->max('id');
if($id==null){
$gallery = Gallery::find()->where(['status' => 'active','activity_name'=>$latestActivity])->all();
}else{
$gallery = Gallery::find()->where(['status' => 'active','activity_name'=>$id])->all();
}
return $this->render('gallery', ['gallery' => $gallery,'activities'=>$activities,'model'=>$model]);
}
}
And here is the SiteController.php of the one i downloaded
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* #return Response|string
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
/**
* Logout action.
*
* #return Response
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return Response|string
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
/**
* Displays about page.
*
* #return string
*/
public function actionAbout()
{
return $this->render('about');
}
}
Note : The Files he sent me are of Sailor theme of Yii2.
How do solve the database not found error? Also please help me understand how replacing config.php from basic yii2 application (which I downloaded) with the one which is already there isn't showing error. Thanks in Advance.

Strictly speaking, the error is because in db.php have you specified the database name mydb, but that database doesn't exist (or, perhaps you don't have permission on it, although that's unlikely since you're using the root user).
Are you certain the database exists on your local database instance? Does your user (root) have the correct permissions to see and access the database?
Most likely this is the problem, either the database is called something else or doesn't exist at all, so you should either create the database on your local system or change the name db.php is looking for.

Related

Multi file upload + textInput - doesn't save in db (yii2)

I am using yii2 basic and wanted to make a gallery, so I made use of multi file upload. All working fine, till I added a text input ('year').
GalleryController.php
public function actionCreate()
{
$model = new MultipleUploadForm();
$year;
if (Yii::$app->request->isPost) {
$model->files = UploadedFile::getInstances($model, 'files');
if ($model->gaUpload()) {
return $this->redirect(['index']);
}
}
return $this->render('create', ['model' => $model]);
}
MultipleUploadForm :
class MultipleUploadForm extends Model
{
/**
* #var UploadedFile[] files uploaded
*/
public $files;
public $year;
public function rules()
{
return [
[['files'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 0],
[['year'], 'string'],
];
}
public function gaUpload()
{
if ($this->validate()) {
foreach ($this->files as $file) {
$model2 = new Gallery();
$model2->img = $file->baseName . '_' . rand(100,999) . '.' . $file->extension;
$model2->save_dir = 'uploads/gallery/';
$model2->year = $this->year;
$file->saveAs($model2->save_dir . $model2->img);
$model2->save();
}
return true;
} else {
return false;
}
}
}
Gallery:
class Gallery extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'cgallery';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['year', 'img', 'save_dir'], 'required'],
[['img', 'save_dir', 'year'], 'string', 'max' => 1024],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'year' => 'Year',
'img' => 'Img',
'save_dir' => 'Save Dir',
];
}
}
_form.php:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], ]); ?>
<?= $form->field($model, 'year')->textInput()?>
<?php
echo '<label class="control-label">Add Pictures</label>';
echo FileInput::widget([
'model' => $model,
'attribute' => 'files[]',
'pluginOptions' => [
'showRemove' => false,
'uploadLabel' => 'Save',
'uploadIcon' => '',
'browseLabel' => '',
'fileExtensions' => 'any',
],
'options' => ['multiple' => true]
]);
?>
<?php ActiveForm::end(); ?>
If I take 'year' out of the process, like : $model2->year = '2010' it work's just fine. I might need to add, that the files get uploaded (into the dir), but it won't get saved to the database.
Has anyone an idea what i did wrong?
EDIT:
Thanks to Wynton Franklin for the help.
The solution was to add the line:
$model->load(\Yii::$app->request->post());
Changed GalleryController.php:
public function actionCreate()
{
$model = new MultipleUploadForm();
$model->load(\Yii::$app->request->post());
if (Yii::$app->request->isPost) {
$model->files = UploadedFile::getInstances($model, 'files');
if ($model->gaUpload()) {
return $this->redirect(['index']);
}
}
return $this->render('create', ['model' => $model]);
}
In your controller year is not begin set. Check that.
if (Yii::$app->request->isPost) {
$model->year = $_POST[][] // or however you do it in yii
$model->files = UploadedFile::getInstances($model, 'files');
if ($model->gaUpload()) {
return $this->redirect(['index']);
}
}

yii2 Search model sometimes not found

I am using yii2 basic app. On local host, my site was running perfect, when I turned to another computer there is a problem with the site, where after login to the admin panel, the user is redirected to ..../breaking-news/index.
The problem is that on one computer (local host) it is running perfect, on the other computer (local host or on the internet) it worked perfect for a while then while trying to test after some hours, it gives me the following error after login:
Error
Class 'app\controllers\app\models\appModels\BreakingNewsSearch' not
found
my controller is:
<?php
namespace app\controllers;
use app\models\appmodels\AppBreakingNews;
use app\models\appModels\BreakingNewsSearch;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\Response;
/**
* BreakingNewsController implements the CRUD actions for AppBreakingNews model.
*/
class BreakingNewsController extends BEController {
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete', 'find-model'],
'rules' => [
[
'allow' => TRUE,
'actions' => [ 'index', 'view', 'create', 'update', 'delete', 'find-model'],
'roles' => ['#'],
],
[
'allow' => FALSE,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'find-model'],
'roles' => ['?'],
],
],
'denyCallback' => function ($rule, $action) {
return $this->redirect(Url::toRoute(['site/index']));
}
],
];
}
public function actionGetMainNews() {
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$news = AppBreakingNews::find()->all();
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'data' => $news,
];
}
}
/**
* Lists all AppBreakingNews models.
* #return mixed
*/
public function actionIndex() {
`// $searchMod`el = new BreakingNewsSearch();
$searchModel = new app\models\appModels\BreakingNewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single AppBreakingNews model.
* #param integer $id
* #return mixed
*/
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new AppBreakingNews model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing AppBreakingNews 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 ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing AppBreakingNews model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id) {
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the AppBreakingNews model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return AppBreakingNews the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = AppBreakingNews::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
The search model is here: ...\mywebsite\models\appmodels\BreakingNewsSearch.php
And the error is : class app\models\appModels\BreakingNewsSearch not found
assuming your use statement is correct, ie
use app\models\appModels\BreakingNewsSearch;
would include your BreakingNewsSearch, then you can create a new instance without the qualified name.
/**
* Lists all AppBreakingNews models.
* #return mixed
*/
public function actionIndex() {
$searchModel = new BreakingNewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
If yii still can't autoload the BreakingNewsSearch class then your path is wrong; try
use app\models\appModels\BreakingNewsSearch;
to match
use app\models\appmodels\AppBreakingNews;
As the others said, it was a problem in models/appModels/...
The correct file path is models/appmodels/...
The error was not observable on windows, but on ubuntu it resulted in the mentioned issue.
Thanks for all of you...

Integrity constraint violation – yii\db\IntegrityException Yii2

When I signup and input data username, email and password. Field username is null, i don't know why. And then when I input again data username, email and password the result is error. The description error can see in the picture.
Code for models/User.php :
<?php
namespace app\models;
use Yii;
use yii\web\IdentityInterface;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public static function tableName()
{
return '{{%user}}';
}
public function behaviors()
{
return
[
TimestampBehavior::className(),
];
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function rules()
{
return
[
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
]; */
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
}
Code for models/SignupForm.php :
<?php
namespace app\models;
use app\models\User;
use yii\base\Model;
use Yii;
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public function rules()
{
return
[
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This username has already been
taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already
been taken'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
public function signup()
{
if ($this->validate())
{
$user = new user();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save())
{
return $user;
}
}
return null;
}
}
Code controllers/siteController.php :
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\components\AuthHandler;
use app\models\UserSocialMedia;
use app\models\User;
use app\helpers\Url;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV ? 'testme' : null,
],
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'successCallback'],
],
];
}
public function successCallback($client)
{
// call safeAttributes method for properly format data
$attributes = $this->safeAttributes($client);
}
public function safeAttributes($client)
{
// get user data from client
$attributes = $client->getUserAttributes();
// set default value
$safe_attributes = [
'social_media' => '',
'id' => '',
'username' => '',
'name' => '',
'email' => '',
];
// get value from user attributes base on social media
if ($client instanceof \yii\autclient\client\Facebook)
{
$safe_attributes = [
'social_media' => 'facebook',
'id' => $attributes['id'],
'username' => $attributes['email'],
'name' => $attributes['name'],
'email' => $attributes['email'],
];
}
else if ($client instanceof \yii\autclient\client\Google)
{
$safe_attributes = [
'social_media' => 'google',
'id' => $attributes['id'],
'username' => $attributes['emails'] ['0'] ['value'],
'name' => $attributes['displayName'],
'email' => $attributes['emails'] ['0'] ['value'],
];
}
else if ($client instanceof \yii\autclient\client\Twitter)
{
$safe_attributes = [
'social_media' => 'twitter',
'id' => $attributes['id'],
'username' => $attributes['screen_name'],
'name' => $attributes['name'],
'email' => '-',
];
}
else if ($client instanceof \yii\autclient\client\Github)
{
$safe_attributes = [
'social_media' => 'github',
'id' => $attributes['id'],
'username' => $attributes['login'],
'name' => $attributes['name'],
'email' => $attributes['email'],
];
}
return $safe_attributes;
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
public function actionAbout()
{
return $this->render('about');
}
public function actionCommentary()
{
$model = new \app\models\Commentary();
// return $this->render('commentary',['model' => $model,]);
// Jika form di sumbit dengan method POST
if (Yii::$app->request->post())
{
$model->load(Yii::$app->request->post());
if($model->validate()){
Yii::$app->session->setFlash('success','Thank You');
}
else {
Yii::$app->session->setFlash('error','Sorry, something wrong');
}
return $this->render('result_commentary',['model'=>$model,]);
}
else{
return $this->render('commentary',['model'=>$model,]);
}
}
public function actionQuery()
{
$db = Yii::$app->db;
$command = $db->createCommand('SELECT * FROM employee');
$employees = $command->queryAll();
// Ekstrak data
foreach ($employees as $employee)
{
echo "<br>";
echo $employee['id']." ";
echo $employee['name']." ";
echo $employee['age']." ";
}
}
public function actionQuery2()
{
$db= Yii::$app->db;
// return a single row
$employee = $db->createCommand('SELECT * FROM employee where id=1')
->queryOne();
echo $employee['id']." ";
echo $employee['name']." ";
echo "(".$employee['age'].")";
echo "<hr>";
// return a single column (the first column)
$names = $db->createCommand('SELECT name FROM employee')->
queryColumn();
print_r($names);
echo "<hr>";
// Binding Parameter
$employee = $db->createCommand('SELECT * FROM employee WHERE id=:id'
,['id'=>2])->queryOne();
// INSERT (table name, column values)
//$db->createCommand()->insert('employee',['name'=>'Nur','age'=>'99',
// ])->execute();
// UPDATE (table name, column values, condition)
//$db->createCommand()->update('employee',['age'=>'30'], 'id = 7')
//->execute();
// DELETE (table name, condition)
//$db->createCommand()->delete('employee', 'id = 7')
//->execute();
// table name, column name, column values
$db->createCommand()->batchInsert('employee',
['name', 'age'],
[
['Nur', 25],
['Dani', 32],
['Nurul', 40],
])->execute();
}
public function actionActiveRecord()
{
$employees = \app\models\Employee::find()->all();
foreach($employees as $employee)
{
echo "<br>";
echo $employee->id." ";
echo $employee->name." ";
echo "(".$employee->age.") ";
}
}
public function actionSignup()
{
$model = new \app\models\SignupForm();
// use session
$session = Yii::$app->session;
$attributes = $session['attributes'];
if ($model->load(Yii::$app->request->post()))
{
if ($user = $model->signup())
{
if ($session->has('attributes'))
{
// add data user_social_media
$user_social_media = new UserSocialMedia([
'social_media' => $attributes['social_media'],
'id' => (string)$attributes['id'],
'username' => $attributes['username'],
'user_id' => $user->id,
]);
$user_social_media->save();
}
if (Yii::$app->getUser()->login($user))
{
return $this->goHome();
}
}
}
if ($session->has('attributes'))
{
// set form field with data from social media
$model->username = $attributes['username'];
$model->email = $attributes['email'];
}
return $this->render('signup', ['model' => $model,
]);
}
}
Remove User model attributes' declarations that are present in your database table:
public $id;
public $username;
These will be handled by ActiveRecord and by adding it manually you are preventing this process.

Yii2 AccessControl

I am new in Yii2 and I try to make AccessControl and success
but the problem is after I success for login and redirect to other page
my Identity _attributes always are null.So if I check with Yii::$app->user->isGuest the return value is always true
this is my LoginHandler.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginHandler extends Model
{
public $user_name;
public $user_password;
public $rememberMe = true;
private $_user;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_name', 'user_password'], 'required'],
[['user_name', 'user_password'], 'string', 'max' => 100],
['user_password','authenticate'],
];
}
public function authenticate($attribute, $params){
// return true;
}
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->user_name);
}
return $this->_user;
}
}
LoginController
<?php
namespace backend\controllers;
use Yii;
use app\models\user;
use app\models\LoginHandler;
class LoginController extends \yii\web\Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionSignin(){
$user = User::findByUsername('admin');
$model = new LoginHandler();
if(Yii::$app->request->post()){
$data = Yii::$app->request->post();
$model->attributes = $data;
if ($model->login()) {
return $this->redirect(['/user/test']);
}else{
die('test');
}
}
return $this->render('login');
}
}
My User.php as model
namespace app\models;
use Yii;
/**
* This is the model class for table "user".
*
* #property integer $user_id
* #property string $user_name
* #property string $user_password
*/
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface{
public $id;
public $authKey;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_name', 'user_password'], 'required'],
[['user_name', 'user_password'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => 'User ID',
'user_name' => 'User Name',
'user_password' => 'User Password',
];
}
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;
}
public static function findByUsername($username){
return static::findOne(['user_name' => $username]);
}
}
and the last is my configuration main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'backend\models\User',
'loginUrl' => ['login/signin'],
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
Thanks in advance.
You mentioned AccessControl in your question. In Yii2 AccessControl is the special behavior class to manage access rules inside controller:
http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html
and I don't see AccessControl in you code.
Anyway.
Most probably the problem is in your implementation of User class.
Looking at your code I can imagine that the table structure is: user_id (PK), user_name, user_password.
If so, then the method getId() returns variable
($this->id) which is never initialized. But this method is used by Yii to store current user in session. In your case it should return $this->user_id.
And if you wish to make remember me working, you should implement correctly getAuthKey and validateAuthKey too.
Here is details:
http://www.yiiframework.com/doc-2.0/guide-security-authentication.html
If this not helps, then show your table structure and code of view which pass authentication data to LoginController
It looks you should check for
Yii::$app->user->identity

Update `create_at` model attribute only if it is null or blank

I am using YII2 advanced application template with yii2-user.
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
This will set the current timestamp value in my user model. But I want to add this only if it's null; it should not be overwritten if I set the value in my controller.
You can create your TimestampBehavior with custom logic:
<?php
namespace app\behaviors;
use yii\db\ActiveRecord;
use yii\base\Behavior;
use yii\db\Expression;
class ARTimestampBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
];
}
public function beforeInsert($event)
{
$model = $event->sender;
if ($model->hasAttribute('created_at') && is_null($model->created_at)) {
$model->created_at = new Expression('NOW()');
}
if ($model->hasAttribute('updated_at')) {
$model->updated_at = new Expression('NOW()');
}
}
public function beforeUpdate($event)
{
$model = $event->sender;
if ($model->hasAttribute('updated_at')) {
$model->updated_at = new Expression('NOW()');
}
}
}
And then use it in your model:
public function behaviors()
{
return [
ARTimestampBehavior::className(),
];
}
I don't think there is an easy way to do this. The closest one can get without much coding it to specify a custom value to be set.
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'value' => function($event) {
return (/* some condition */)
? your_custom_function_returning_the_time()
: time();
],
];
}
That being said, I see this as a potential misuse of TimestampBehavior. One might be better off defining a new column for your custom creation timestamp.
If you are set on using the current column, then ditch TimestampBehavior and overwrite the beforeSave method of your model:
public function beforeSave($insert)
{
if (! parent::beforeSave($insert)) {
return false;
}
if ($insert && this->create_at === null) {
$this->create_at = time();
}
$this->update_at = time();
return true;
}
Just use default TimestampBehavior like this:
/**
* #inheritdoc
* #return array mixed
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => false,
'value' => function($event) {return $event->sender->created_at ?? new \yii\db\Expression('NOW()');},
],
];
}
Yii does have built-in support for preserving already filled values from v2.0.13:
public function behaviors()
{
return [
'timestamp' => [
'class' => \yii\behaviors\TimestampBehavior::class,
'preserveNonEmptyValues' => true,
],
];
}

Categories