Добавление информации???

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Arta
Сообщения: 41
Зарегистрирован: 2016.10.26, 11:08

Добавление информации???

Сообщение Arta »

Уважаемые пользователи этого форума подскажите пожайлуста почему при добавлении информации в бд информация добавляеться но - должна открываться подробно а в моём случае выводиться такая ошибка Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\module\admin\models\Category::created,подскажите как это решить и по возможности дайте пожайлуста ответ как мне добавить информацию но чтобы поля id не было в форме добавления сериала а id в самой таблице выводилось от 10-ти и выше при каждом добавлении нового сериала???вот контроллер,модель и форма что сдесь нужно изменить для нормальной работы,подскажите мне пожайлуста...
Модель

Код: Выделить всё

<?php

namespace app\module\admin\models;

use Yii;
use yii\web\UploadedFile;
/**
 * This is the model class for table "category".
 *
 * @property integer $id
 * @property string $name
 * @property string $names
 * @property string $janr
 * @property string $opis
 * @property integer $god
 * @property integer $start
 * @property integer $end
 * @property string $status
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
	public $file;
	
    public static function tableName()
    {
        return 'category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            
            [['id'], 'required'],
            [['id','god', 'start', 'end'], 'integer'],
            [['opis'], 'string'],
            [['file'], 'file'],
            [['name', 'names', 'janr', 'status'], 'string','max' => 255],
          
        ];
    }
    /**
     * @return \yii\db\ActiveQuery
    public function getEpizod()
    {
        return $this->hasOne(Epizod::className(), ['sezon' => 'id']);
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
		    'id' => 'ID',
            'name' => 'Название',
            'names' => 'Орегинальное название',
			'file' => 'Постер',
            'janr' => 'Жанр',
            'opis' => 'Описание',
            'god' => 'Год выпуска',
            'start' => 'Начало периода',
            'end' => 'Конец периода',
            'status' => 'Статус',
	];
	}
		    public function getJanr()
    {
		$janr = [];
		for ($i = 2017; $i > 1989; $i--) {
			$janr[$i] = $i;
		}
		
        return $janr;
    }
	
    public function getGod()
    {
		$god = [];
		for ($i = 2017; $i > 1989; $i--) {
			$god[$i] = $i;
		}
		
        return $god;
    }
	    public function getStart()
    {
		$start = [];
		for ($i = 2017; $i > 1989; $i--) {
			$start[$i] = $i;
		}
		
        return $start;
    }
	    public function getEnd()
    {
		$end = [];
		for ($i = 2017; $i > 1989; $i--) {
			$end[$i] = $i;
		}
		
        return $end;
    }
	
	    public function getStatus()
    {
		$end = [];
		for ($i = 2017; $i > 1989; $i--) {
			$end[$i] = $i;
		}
		
        return $end;
    }
}
Контроллер

Код: Выделить всё

<?php

namespace app\module\admin\controllers;

use Yii;
use app\module\admin\models\Category;
use app\module\admin\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CategorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Category();
            
		if ($model->load(Yii::$app->request->post()) && $model->save()){
           /* $model->file=UploadedFile::getInstance($model,'file');
            $model->file->saveAs('uploads/'. $model->file->baseName .'.'.$model->file->extension);
            
            $model->foto = 'uploads/'.$model->file->baseName .'.'.$model->file->extension;
			*/
            $model->created-date('Y-m-d h:m:s');
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Category 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 Category 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 Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Форма

Код: Выделить всё

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\module\admin\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="category-form">

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
  
    <?= $form->field($model, 'id')->textInput() ?>
	
    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'names')->textInput(['maxlength' => true]) ?>
	
	<?= $form->field($model, 'file')->fileInput() ?>
	
	<?= $form->field($model, 'opis')->textarea(['rows' => 6]) ?>
	
    <?= $form->field($model, 'janr')->textInput() ?>
	
    <?= $form->field($model, 'god')->dropDownList($model->getGod()) ?>

    <?= $form->field($model, 'start')->dropDownList($model->getStart()) ?>

    <?= $form->field($model, 'end')->dropDownList($model->getEnd()) ?>

    <?= $form->field($model, 'status')->textInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

что нужно изменить в этих данных для нормальной работы???
Anton1999
Сообщения: 26
Зарегистрирован: 2017.04.28, 14:55

Re: Добавление информации???

Сообщение Anton1999 »

Arta писал(а): 2017.05.17, 13:47 как мне добавить информацию но чтобы поля id не было в форме добавления сериала
В правилах убери описание id.

Код: Выделить всё

    public function rules()
    {
        return [
            
            [['god', 'start', 'end'], 'integer'],
            [['opis'], 'string'],
            [['file'], 'file'],
            [['name', 'names', 'janr', 'status'], 'string','max' => 255],
          
        ];
    }
В форме удали

Код: Выделить всё

 <?= $form->field($model, 'id')->textInput() ?>
Аватара пользователя
yiijeka
Сообщения: 3103
Зарегистрирован: 2012.01.28, 09:14
Откуда: Беларусь
Контактная информация:

Re: Добавление информации???

Сообщение yiijeka »

Код: Выделить всё

$model->created-date('Y-m-d h:m:s'); 
- код из унитаза, в нём всё дело, удалите или перепише как вам нужно.
Ответить