My controller :
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}
Getting this error on submitting my form, dont know what's wrong with it..
Tried with $model->save(false); ..but not working as well
Try with getPrimaryKey() method:
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
else
{
// print_r($model->getErrors()); => check whether any validation errors are there
}
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}
Related
I need to do some stuff before saving my data in DB.
the problem is that the data changes during the validation and save process.
here is some code:
public function actionCreate()
{
$model = new Customers();
if ($model->load(Yii::$app->request->post()) && $model->validate('special_field')) {
// do some stuff
// data changes here
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
but $model->validate('special_field') function does not work
I've tried this and it worked properly
if ($model->load(Yii::$app->request->post())) {
// your stuff
if ($model->validate('special_field')) {
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
$errors = $model->errors;
var_dump($errors);
die();
}
}
My Controller:
public function actionCreate()
{
$model = new SuratMasuk(['scenario' => 'create']);
if ($model->load(Yii::$app->request->post()))
{
try
{
$picture = UploadedFile::getInstance($model, 'imageFile');
$model->imageFile = $_POST['SuratMasuk']['id_suratmasuk'].'.'.$picture->extension;
if($model->save())
{
$picture->saveAs('uploads/' . $model->id_suratmasuk.'.'.$picture->extension);
Yii::$app->getSession()->setFlash('success','Data saved!');
return $this->redirect(['view','id'=>$model->id_suratmasuk]);
}
else
{
Yii::$app->getSession()->setFlash('error','Data not saved!');
return $this->render('create', [
'model' => $model,
]);
}
}
catch(Exception $e)
{
Yii::$app->getSession()->setFlash('error',"{$e->getMessage()}");
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
getting this error message when i try to save my post. and it just uploads the text not images. i've tried $model->save(false); but not working
i'm newbie on yii, i'll appreciate your help
I guess this is because you try to pass id here:
return $this->redirect(['view', 'id' => $model->id_suratmasuk]);
and since actionView almost for sure requires id as parameter you get this error because $model->id_suratmasuk is empty.
You need to set proper rules() in SuratMasuk model.
Do not use POST variables directly, this is asking for being hacked.
Do not use save(false) if you need to save anything that comes from user (validation is a must!).
Add rules() for all attributes so there will be no surprises like with this id_suratmasuk being empty.
Check result of saveAs() on UploadedFile instance - this can go false as well.
I have a problem when uploading a file with a .php file extension. The problem is becoming blank pages and unsuccessfully redirected to index (files uploaded but the page is blank)
This does not happen when I use other extension files (jpeg, jpg, txt, doc, docx etc).
Ps. I am using Oracle as database and using yii2 UploadedFile
Here my model
public static function tableName()
{
return 'JOB';
}
public function rules()
{
return [
[['JOBNAME', 'CLASS', 'ACTION', 'SCHEDULE', 'STATUS'], 'required'],
[['ID', 'STATUS'], 'integer'],
[['JOBNAME'], 'string', 'max' => 30],
[['FILECOMMAND'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpeg, php, txt'],
[['CLASS', 'ACTION', 'SCHEDULE'], 'string', 'max' => 100],
[['ID'], 'unique'],
];
}
}
Here my controller
public function actionCreate()
{
$scheduleList = yii::$app->params['cronparam'];
$model = new JOB();
if (yii::$app->request->post()) {
$state = true;
$data = yii::$app->request->post()['JOB'];
try {
$transaction = Yii::$app->db->beginTransaction();
$model->JOBNAME = $data['JOBNAME'];
$model->CLASS = $data['CLASS'];
$model->ACTION = $data['ACTION'];
$model->SCHEDULE = $data['SCHEDULE'];
$model->STATUS = $data['STATUS'];
$model->files = UploadedFile::getInstance($model, 'FILECOMMAND');
$model->FILECOMMAND = $model->files;
$model->files->saveAs(yii::getAlias('#app') . yii::$app->params['pathJobFile'] . $model->files->baseName . '.' . $model->files->extension, false);
if (!$model->save()) {
$ErrorMessage = $model->getErrorMessage($model->getErrors());
throw new Exception($ErrorMessage);
}
$message = "Success insert Job " . ucwords($model->JOBNAME);
$transaction->commit();
} catch (Exception $e) {
$message = $e->getMessage();
$state = false;
$transaction->rollBack();
}
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
$this->redirect('index');
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
$this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
} else {
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
}
Add return statements here:
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
return $this->redirect('index'); //here
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]); //and here
}
My Code related is the following:
Model Rules
[['documentTypeId', 'itemId', 'name', 'document'], 'required'],
[['document'], 'file', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'doc', 'pdf'], 'checkExtensionByMimeType'=>false],
Model method
public function upload($file)
{
if ($this->validate()) {
$userFolder = Yii::getAlias("#app")."/uploads/".$this->item->userId;
if(BaseFileHelper::createDirectory($userFolder) !== false) {
$fileName = uniqid(rand(), false) . '.' . $this->document->extension;
$file->saveAs($userFolder.'/' . $fileName);
$this->document = $file->name;
return true;
} else {
return false;
}
} else {
return false;
}
}
Controller
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = UploadedFile::getInstance($model, 'document');
if($model->upload($file) !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
This is giving me a validation error: "Document can not be blank". If I set "Document" field as not required and submit form I get "Please upload a file."
I am uploading this through a form with some other fields.
Any ideas?
I have found the error it was the model->validate() on controller. When i do:
$model->load(Yii::$app->request->post())
File content is not loaded to the "document" field. Yii generates a hidden field which is empty. So I need first to do this:
$file = UploadedFile::getInstance($model, 'document');
So now my controller looks like this:
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if($model->validate()) {
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
And I removed the validation inside upload method on model. Hope it helps someone.
I am using yii2 for a weigh bridge project
Upon create, the user is redirected to view but my controller doesn't validate the information in such a way that even if data is not entered in the form fields a user is always redirected to view.
How can I implement the validation property
Controller code:
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) ) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
try this
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
for more on validation validation