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...
Related
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.
I am trying to implement tagged articles for my new small CMS written with yii2.
This is what i have tried https://forum.yiiframework.com/t/how-to-create-tags-for-posts-in-yii2/123890
Everything is working the tagging machanism is fetching data from the tag table but it is not saving data to the table tag_assign.
This is my form.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
//Using for Wysiwig editor
use dosamigos\ckeditor\CKEditor;
//Using for Tagging
use dosamigos\selectize\SelectizeTextInput;
/* #var $this yii\web\View */
/* #var $model common\models\Articles */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="articles-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'content')->widget(CKEditor::className(), [
'options' => ['height' => 800],
'preset' => 'basic',
'clientOptions' => ['height' => 400]
]) ?>
<?= $form->field($model, 'tags')->widget(SelectizeTextInput::className(), [
// calls an action that returns a JSON object with matched
// tags
'loadUrl' => ['tag/list'],
'options' => ['class' => 'form-control'],
'clientOptions' => [
'plugins' => ['remove_button'],
'valueField' => 'name',
'labelField' => 'name',
'searchField' => ['name'],
'create' => true,
],
])->hint('Use commas to separate tags') ?>
<?= $form->field($model, 'date')->textInput() ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
And this is my tag model
<?php
namespace common\models;
use Yii;
use dosamigos\taggable\Taggable;
/**
* This is the model class for table "tags".
*
* #property int $id
* #property string $frequency
* #property string $name
*/
class Tag extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'tags';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['frequency', 'name'], 'required'],
[['frequency'], 'string', 'max' => 500],
[['name'], 'string', 'max' => 250],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'frequency' => 'Frequency',
'name' => 'Name',
];
}
//For Tagging
public function behaviors() {
return [
[
'class' => Taggable::className(),
],
];
}
public function findAllByName($name)
{
return Tag::find()->where('name LIKE :query')
->addParams([':query'=>"%$name%"])
->all();
}
}
Tag controller.
<?php
namespace backend\controllers;
use Yii;
use common\models\Tag;
use common\models\searchTag;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
/**
* TagController implements the CRUD actions for Tag model.
*/
class TagController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Tag models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new searchTag();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Tag model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Tag model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Tag();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
public function actionList($query)
{
$models = Tag::findAllByName($query);
$items = [];
foreach ($models as $model) {
$items[] = ['name' => $model->name];
}
// We know we can use ContentNegotiator filter
// this way is easier to show you here :)
Yii::$app->response->format = Response::FORMAT_JSON;
return $items;
}
/**
* Updates an existing Tag model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Tag model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Tag model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Tag the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Tag::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
And the articles
<?php
namespace common\models;
use Yii;
//For Taggable
use dosamigos\taggable\Taggable;
/**
* This is the model class for table "articles".
*
* #property int $id
* #property string $title
* #property string $content
* #property string $tags
* #property string $date
*/
class Articles extends \yii\db\ActiveRecord
{
//For taggable
public function behaviors() {
return [
[
'class' => Taggable::className(),
],
];
}
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'articles';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['title', 'content', 'tags', 'date'], 'required'],
[['content'], 'string'],
[['date'], 'safe'],
[['title', 'tags'], 'string', 'max' => 250],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'content' => 'Content',
'tags' => 'Tags',
'date' => 'Date',
];
}
public function getTags()
{
return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('tag_assign', ['article_id' => 'id']);
}
}
What I am missing? How can I trouble shoot at least what is going wrong?
in yii2 advanced template site Controller is working fine. When calling a function in new controller it is navigating to 404 error page.
I created model using model generator and create a crude for the model.
This is my controller
namespace backend\Controllers;
use Yii;
use common\models\PackageTable;
use common\models\PackageTableSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PackageTableController implements the CRUD actions for PackageTable model.
*/
class PackageTableController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all PackageTable models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PackageTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single PackageTable model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new PackageTable model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new PackageTable();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->package_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing PackageTable 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->package_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing PackageTable 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 PackageTable model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return PackageTable the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = PackageTable::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
This is my model
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "package_table".
*
* #property integer $package_id
* #property string $package_name
* #property string $description
* #property integer $amount
* #property integer $status
* #property string $created_on
* #property string $updated_on
*/
class PackageTable extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'package_table';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_name', 'description', 'amount', 'status'], 'required'],
[['description'], 'string'],
[['amount', 'status'], 'integer'],
[['created_on', 'updated_on'], 'safe'],
[['package_name'], 'string', 'max' => 250],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'package_id' => 'Package ID',
'package_name' => 'Package Name',
'description' => 'Description',
'amount' => 'Amount',
'status' => 'Status',
'created_on' => 'Created On',
'updated_on' => 'Updated On',
];
}
}
This is my model search
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PackageTable;
/**
* PackageTableSearch represents the model behind the search form about `common\models\PackageTable`.
*/
class PackageTableSearch extends PackageTable
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_id', 'amount', 'status'], 'integer'],
[['package_name', 'description', 'created_on', 'updated_on'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = PackageTable::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'package_id' => $this->package_id,
'amount' => $this->amount,
'status' => $this->status,
'created_on' => $this->created_on,
'updated_on' => $this->updated_on,
]);
$query->andFilterWhere(['like', 'package_name', $this->package_name])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
}
}
Although php namespaces are case-insensitive, autoloader in your case is likely case-sensitive.
At the top of your controller namespace mentioned as
namespace backend/Controllers;
but in advanced template all directories are in lower case. So try to change this line to
namespace backend/controllers;
I am working on a Yii2 based project right now. Today when I was testing my application I noticed a very interesting bug in it. I have a Products table with it's model and controllers and views. (These are generated with gii)
When I list all the records in the index action it works fine. But here comes the bug. When I click on the edit or view action it alwasy renders the first record in the database. I was var_dump the result of the queries and always returnd the mentiond result. Only when I used createCommand got the proper result.
What do you think guys could be the problem with it?
The controller
<?php
namespace backend\controllers;
use Yii;
use app\models\Termek;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TermekController implements the CRUD actions for Termek model.
*/
class TermekController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Termek models.
* #return mixed
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Termek::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Termek model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
]);
}
/**
* Creates a new Termek model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Termek();
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 Termek 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 Termek 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 Termek model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Termek the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Termek::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
The index.php view file
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Termeks');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="termek-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Create Termek'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'nev',
'szelesseg',
'magassag',
'egyeb:ntext',
// 'ar',
// 'termek_kategoria_id',
// 'torolt',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Part of view.php view file:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'nev',
'szelesseg',
'magassag',
'egyeb:ntext',
'ar',
'termek_kategoria_id',
'torolt',
],
]) ?>
Model file:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "termek".
*
* #property integer $id
* #property string $nev
* #property double $szelesseg
* #property double $magassag
* #property string $egyeb
* #property string $ar
* #property integer $termek_kategoria_id
* #property string $torolt
*/
class Termek extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'termek';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['nev', 'termek_kategoria_id'], 'required'],
[['szelesseg', 'magassag'], 'number'],
[['egyeb'], 'string'],
[['ar', 'termek_kategoria_id'], 'integer'],
[['torolt'], 'safe'],
[['nev'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'nev' => Yii::t('app', 'Nev'),
'szelesseg' => Yii::t('app', 'Szelesseg'),
'magassag' => Yii::t('app', 'Magassag'),
'egyeb' => Yii::t('app', 'Egyeb'),
'ar' => Yii::t('app', 'Ar'),
'termek_kategoria_id' => Yii::t('app', 'Termek Kategoria ID'),
'torolt' => Yii::t('app', 'Torolt'),
];
}
/**
* #inheritdoc
* #return \app\models\Query\TermekQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\models\Query\TermekQuery(get_called_class());
}
}
Try modify the findModel function using find()->where instead of findOne
protected function findModel($id)
{
var_dump($id);
$model = Termek::find()->where(['id'=> $id])->one();
var_dump($model);
if (($model !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
I am not sure why but somehow the error solved. I had a function in TermekQuery that was supposed to query all the records that has the deleted field null. I removed it and now works fine.
I don't understand why this error occur.
get error on call a cms
http://localhost/yii-cms/web/cms
Calling unknown method: yii2mod\cms\controllers\CmsController::setInstance()
i am try to use of yii2-cms
cmsController
<?php
namespace yii2mod\cms\controllers;
use Yii;
use yii2mod\cms\models\CmsModel;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii2mod\cms\models\search\CmsModelSearch;
use yii2mod\editable\EditableAction;
use yii2mod\toggle\actions\ToggleAction;
/**
* Class CmsController
* #package yii2mod\cms\controllers
*/
class CmsController extends Controller
{
/**
* #var string view path
*/
public $viewPath = '#vendor/yii2mod/yii2-cms/views/cms/';
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'create' => ['get', 'post'],
'update' => ['get', 'post'],
'delete' => ['post']
],
]
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'edit-page' => [
'class' => EditableAction::className(),
'modelClass' => CmsModel::className(),
'forceCreate' => false
],
'toggle' => [
'class' => ToggleAction::className(),
'modelClass' => CmsModel::className(),
]
];
}
/**
* Lists all CmsModel models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CmsModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render($this->viewPath . 'index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
/**
* Creates a new CmsModel model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new CmsModel();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been created.'));
return $this->redirect(['index']);
}
return $this->render($this->viewPath . 'create', [
'model' => $model,
]);
}
/**
* Updates an existing CmsModel 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()) {
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been updated.'));
return $this->redirect(['index']);
}
return $this->render($this->viewPath . 'update', [
'model' => $model,
]);
}
/**
* Deletes an existing CmsModel 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();
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been deleted.'));
return $this->redirect(['index']);
}
/**
* Finds the CmsModel model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
*
* #param integer $id
*
* #return CmsModel the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = CmsModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('yii2mod.cms', 'The requested page does not exist.'));
}
}
}
i have following yii2-cms and it's work great
set instance error occur due to they can not find out given class and that's possible due to miss configuration.
follow Configuration Link https://github.com/yii2mod/yii2-cms#configuration
1) To use this extension first you need to configure the comments extension, after that you have to configure the main config in your application:
'modules' => [
'admin' => [
'controllerMap' => [
'cms' => 'yii2mod\cms\controllers\CmsController'
// You can set your template files
// 'layout' => '#app/modules/backend/views/layouts/main',
// 'viewPath' => '#app/modules/backend/views/cms/',
],
],
],
You can then access to management section through the following URL:
http://localhost/path/to/index.php?r=admin/cms/index
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
3) Add to SiteController (or configure via $route param in urlManager):
/**
* #return array
*/
public function actions()
{
return [
'page' => [
'class' => 'yii2mod\cms\actions\PageAction',
// You can set your template files
'view' => '#app/views/site/page'
],
];
}
And now you can create your own pages via the admin panel, and access them via the url of each page.
Yes error is solved by following proper Configuration STEP.
Error is occur due to miss configure second step
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
Full Configuration you need to did :
1) To use this extension first you need to configure the comments extension, after that you have to configure the main config in your application:
'modules' => [
'admin' => [
'controllerMap' => [
'cms' => 'yii2mod\cms\controllers\CmsController'
// You can set your template files
// 'layout' => '#app/modules/backend/views/layouts/main',
// 'viewPath' => '#app/modules/backend/views/cms/',
],
],
],
You can then access to management section through the following URL:
http://localhost/path/to/index.php?r=admin/cms/index
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
3) Add to SiteController (or configure via $route param in urlManager):
/**
* #return array
*/
public function actions()
{
return [
'page' => [
'class' => 'yii2mod\cms\actions\PageAction',
// You can set your template files
'view' => '#app/views/site/page'
],
];
}
And now you can create your own pages via the admin panel, and access them via the url of each page.
You seem to be using the cms extension in your site component as-is.
In your web.php file, add this:
'components' => [
...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages'
'sourceLanguage' => 'en',
],
],
],
]
...,
'controllerMap': => [
'cms' => 'yii2mod\cms\controllers\CmsController'
],
NOTE: You should exclude the path about configuring it as a component in the admin module since you're not using it anyway.
If you were using it in a module, then the steps documented in the README is just fine for you.