Yii2 create data row works but update doesn't - php

I saw red some answers on similar questions but still can't understand where is my problem. I have a _form.php which is used when data row is created and updated аlso. When i create data row it is OK but when it redirects me to return $this->redirect(['view', 'id' => $model->id]); but the data is not updated. Tried to var_dump($model->getErrors()) (as I saw in the answers of another question) but it returns me and empty array.
These are my files:
Controller action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$settings = new Settings();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$languages = Lang::find()->all();
foreach ($languages as $language) {
if ($language->default != 1) {
$names = 'names_' . $language->url;
$varNames = Yii::$app->OutData->sanitize($model->$names);
$model->$names = $varNames;
$review = 'review_' . $language->url;
$varReview = Yii::$app->OutData->sanitize($model->$review);
$model->$review = $varReview;
$metaDesc = 'meta_desc_' . $language->url;
$varMetaDesc = Yii::$app->OutData->sanitize($model->$metaDesc);
$model->$metaDesc = $varMetaDesc;
$url = 'url_' . $language->url;
$varUrl = Yii::$app->OutData->sanitize($model->$url);
$model->$url = $varUrl;
$cBirth = 'country_birth_' . $language->url;
$varcBirth = Yii::$app->OutData->sanitize($model->$cBirth);
$model->$cBirth = $varcBirth;
}
else
{
$model->names = Yii::$app->OutData->sanitize($model->names);
$model->review = Yii::$app->OutData->sanitize($model->review);
$model->meta_desc = Yii::$app->OutData->sanitize($model->meta_desc);
$model->url= Yii::$app->OutData->sanitize($model->url);
$model->country_birth = Yii::$app->OutData->sanitize($model->country_birth);
}
}
//записване на изображенията + thumb
if (isset($_POST["Author"]["imageFiles"]) and ! empty($_POST["Author"]["imageFiles"])) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
if (isset($model->imageFiles) and count($model->imageFiles) > 0) {
foreach ($model->imageFiles as $key => $file) {
$parseProdTitle = MakeURL::parseImageName($model->names.'_'.$model->id);
$fileName = $parseProdTitle . '_' . $model->id . '.' . $file->extension;
$fileName = Yii::$app->translate->cyr_to_lat($fileName);
$model->filename = $fileName;
$model->save(false);
$pic = Yii::getAlias('#frontend/web') . '/authors/thumb-270/' . $fileName;
$pic2 = Yii::getAlias('#frontend/web') . '/authors/' . $fileName;
$file->saveAs(Yii::getAlias('#frontend/web') . '/authors/' . $fileName);
$image = file_get_contents(Yii::getAlias('#frontend/web') . '/authors/' . $fileName);
file_put_contents($pic, $image);
$model->resizeImg($pic);
$settings->compress($pic, $pic, 90);
$settings->compress($pic2, $pic2, 90);
}
}
}
if($model->update()){
var_dump(1);die;
}else{
var_dump($model->getErrors());die;// it dumps here but it returns an empty array
}
if($model->validate()){
var_dump(1);die;// it dumps here so validate is ok ( I guess )
}else{
var_dump($model->getErrors());die;
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
And my model:
<?php
namespace backend\models;
use Yii;
use omgdef\multilingual\MultilingualBehavior;
use omgdef\multilingual\MultilingualQuery;
use kartik\helpers\Html;
/**
* This is the model class for table "author".
*
* #property integer $id
* #property integer $active
* #property string $filename
* #property integer $sort
* #property data $birthday
*
* #property AuthorLang[] $authorLangs
*/
class Author extends \yii\db\ActiveRecord
{
public $imageFiles;
private $languages = array();
public function __construct() {
foreach(Yii::$app->params['languages'] as $langArr){
$langParam = new Lang;
$langParam->id = $langArr['id'];
$langParam->url = $langArr['url'];
$langParam->local = $langArr['local'];
$langParam->name = $langArr['name'];
$langParam->default = $langArr['default'];
$langParam->active = $langArr['active'];
$this->languages[] = $langParam;
}
parent::__construct();
}
public static function find()
{
return new MultilingualQuery(get_called_class());
}
public function behaviors()
{
$languagesArray = [];
foreach($this->languages as $language){
if($language->default){
$defLang = $language->url;
}
$languagesArray[$language->local] = $language->name;
}
return [
'ml' => [
'class' => MultilingualBehavior::className(),
'languages' => $languagesArray,
//'languageField' => 'language',
//'localizedPrefix' => '',
//'requireTranslations' => false',
//'dynamicLangClass' => true',
//'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
'defaultLanguage' => $defLang,
'langForeignKey' => 'author_id',
'tableName' => "{{%authorLang}}",
'attributes' => [
'names',
'review',
'meta_desc',
'url',
'country_birth',
]
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'author';
}
/**
* #inheritdoc
*/
public function rules()
{
$required = ['names', 'review', 'meta_desc', 'url', 'birthday', 'country_birth'];
$this->checkLanguage([$required]);
return [
[['active', 'sort'], 'required'],
[$required, 'required'],
['names', 'string', 'max' => 255],
['country_birth', 'string', 'max' => 255],
['review', 'string'],
['meta_desc', 'string', 'max' => 170],
['url', 'string', 'max' => 60],
[['active', 'sort'], 'integer'],
[['filename'], 'string'],
];
}
protected function checkLanguage($megaArr = [])
{
foreach ($this->languages as $language)
{
if($language->default != 1)
{
foreach ($megaArr as $fields)
{
foreach ($fields as $field)
{
$field .= '_' . $language->url;
}
}
}
}
}
public function changeActiveForm() {
$active = "";
if ($this->active == 1) {
$active = 'checked="checked"';
}
return '<label class="switch switch-custom block mbn taCenter">
<input type="checkbox" value="1" id="check_' . $this->id . '" name="field_types" class="legend-switch" ' . $active . ' onchange="changeStatusActive(' . $this->id . ', \'author\');"></input>
<label data-off="' . Yii::t('app', 'Не') . '" data-on="' . Yii::t('app', 'Да') . '" for="check_' . $this->id . '"></label>
<span></span>
</label>';
}
public function getKartikImagesList() {
$doctorImagesArr = array();
$doctorImages = Author::find()->where('id = :id', [':id' => $this->id])->orderBy(['id' => SORT_ASC])->one();
if(isset($doctorImages->filename) and $doctorImages->filename!="" and $doctorImages->filename!=Null) {
$fileName = Yii::getAlias('#frontend/web') . "/authors/" . $doctorImages->filename;
if (file_exists($fileName)) {
$fileNameUrl = Yii::$app->urlManagerFrontend->baseUrl . "/authors/thumb-270/" . $doctorImages->filename;
$doctorImagesArr[] = Html::img($fileNameUrl, ['class' => 'file-preview-image', 'style' => 'width: 350px;']) .
'<span class="glyphicons glyphicons-bin"></span>';
}
}
return $doctorImagesArr;
}
public function resizeImg($img) {
$sz = getimagesize($img);
$ratio = $sz[0] / $sz[1]; // w/h
$w2 = Yii::$app->params['thumbswidth']; // thumb 1 width
$image = new SimpleImage();
$image->load($img);
$image->resize($w2, round($w2 / $ratio));
$image->save($img);
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'active' => Yii::t('app','app.Active' ),
'filename' => Yii::t('app','app.Filename' ),
'sort' => Yii::t('app','app.Sort' ),
'country_birth' => Yii::t('app','app.Birth Country' ),
'names' => Yii::t('app','app.Names' ),
'meta_desc' => Yii::t('app','app.Meta Desc' ),
'filename' => Yii::t('app','app.Image' ),
'birthday' => Yii::t('app','app.Birthday' ),
'imageFiles' => Yii::t('app','app.Image' ),
'description' => Yii::t('app','app.Review' ),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAuthorLangs()
{
return $this->hasMany(AuthorLang::className(), ['author_id' => 'id']);
}
}
I didn't post the _form.php because it is the same for both actions (create and update) and I think that the problem is not in it.If you need it will update my question immediately. Thank you in advance!

For some reason it is possible that the update does not affect any row in the table. In this case the function return 0 .. for check this situation you should chek this this way
http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html#update()-detail
if($model->update() !== false){
var_dump(1);die;
}else{
var_dump($model->getErrors());die;// it dumps here but it returns an empty array
}
then, just for debugging, you could also try using $model->save(false) instead of $model->update() ... this way the $model is saved without regarding the validation rules ..

Related

Example module how to save data in the database

I cloned a module of prestashop 1.7 and everything works perfectly without any problem. What I would like to do (please) is save the data in the prestashop database itself but I can't do it I hope I have explained myself better
code
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class Stagenti extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'stagenti';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'Lab';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Lab Agenti');
$this->description = $this->l('Gestionale per agenti di commercio');
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
}
public function install()
{
if (Shop::isFeatureActive()) Shop::setContext(Shop::CONTEXT_ALL);
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
//$values[] = Tools::getValue('SOMETEXT_TEXT_'.$lang['id_lang']);
Configuration::updateValue('STAGENTI_TEXT_' . $lang['id_lang'], '', true);
Configuration::updateValue('STAGENTI_TEXT2_' . $lang['id_lang'], '', true);
}
include(dirname(__FILE__).'/sql/install.php');
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('displayBanner');
}
public function uninstall()
{
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
//$values[] = Tools::getValue('SOMETEXT_TEXT_'.$lang['id_lang']);
Configuration::deleteByName('STAGENTI_TEXT_' . $lang['id_lang']);
Configuration::deleteByName('STAGENTI_TEXT2_' . $lang['id_lang']);
}
include(dirname(__FILE__).'/sql/uninstall.php');
return parent::uninstall();
}
public function getContent()
{
if (((bool)Tools::isSubmit('submitStagentiModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
return $output . $this->renderForm();
}
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitStagentiModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Impostazioni'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 9,
'type' => 'text',
'desc' => $this->l('inserisci lo slogan che desideri far visualizzare'),
'name' => 'STAGENTI_TEXT2',
'label' => $this->l('Messaggio Slogan'),
'autoload_rte' => true,
'lang' => true
),
array(
'col' => 9,
'type' => 'textarea',
'desc' => $this->l('se inserisci una img le misure devono essere 1140 x 270 px'),
'name' => 'STAGENTI_TEXT',
'label' => $this->l('Messaggio riepilogo'),
'autoload_rte' => true,
'lang' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
protected function getConfigFormValues()
{
$languages = Language::getLanguages(false);
$values = array();
foreach ($languages as $lang) {
$values['STAGENTI_TEXT'][$lang['id_lang']] = Configuration::get('STAGENTI_TEXT_' . $lang['id_lang']);
$values['STAGENTI_TEXT2'][$lang['id_lang']] = Configuration::get('STAGENTI_TEXT2_' . $lang['id_lang']);
}
return $values;
}
protected function postProcess()
{
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
Configuration::updateValue('STAGENTI_TEXT_' . $lang['id_lang'], Tools::getValue('STAGENTI_TEXT_' . $lang['id_lang']), true);
Configuration::updateValue('STAGENTI_TEXT2_' . $lang['id_lang'], Tools::getValue('STAGENTI_TEXT2_' . $lang['id_lang']), true);
}
}
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
}
public function hookHeader()
{
$this->context->controller->addJS($this->_path . 'views/js/front.js');
$this->context->controller->addCSS($this->_path . 'views/css/front.css');
}
public function hookDisplayBanner()
{
$some_string = Configuration::get('STAGENTI_TEXT_' . $this->context->language->id);
$this->context->smarty->assign([
'module_dir' => $this->_path,
'stagenti_message' => $some_string
]);
$some_string = Configuration::get('STAGENTI_TEXT2_' . $this->context->language->id);
$this->context->smarty->assign([
'module_dir' => $this->_path,
'stagenti_message5' => $some_string
]);
return $this->display(__FILE__, 'message.tpl');
}
}
database
<?php
$sql = array();
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . '` (
`id_stagenti` int(11) NOT NULL AUTO_INCREMENT,
`stagenti_text` text NOT NULL,
`stagenti_text2` text NOT NULL,
PRIMARY KEY (`id_infomess`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
Db::getInstance()->insert('your_table', array(
'stagenti_text' => pSQL($value1),
'stagenti_text2' => pSQL($value2),
));

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 file upload returns UPLOAD_ERR_PARTIAL

Images fail to upload when I create a new item but on updating the newly created item the file is successfully uploaded. Any reasons?
Trending News Model
class TrendingNews extends \yii\db\ActiveRecord
{
const EVENT_ADD_TRENDING_NEWS = 'add-trending-news';
public $featuredFile;
public function init() {
$this->on(self::EVENT_ADD_TRENDING_NEWS, [$this, 'saveToLog']);
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'trending_news';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['headline_text','news_info', 'news_url', 'author', 'published', 'date_added', 'date_modified'], 'required'],
[['headline_text', 'image_url', 'news_info', 'news_url'], 'string'],
[['date_added', 'date_modified'], 'safe'],
[['author'], 'string', 'max' => 20],
[['published'], 'string', 'max' => 2],
[['featuredFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'headline_text' => 'Headline',
'image_url' => 'Image Url',
'news_info' => 'Source',
'news_url' => 'News Url',
'author' => 'Author',
'published' => 'Published',
'date_added' => 'Date Added',
'date_modified' => 'Date Modified',
'featuredFile' => 'Featured Image',
];
}
public function uploadBanner()
{
if ($this->validate()) {
$ymd = date("Ymd");
$save_path = \Yii::getAlias('#backend') . '/web/uploads/' . $ymd . '/';
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true);
}
$fileName = "trending_".Yii::$app->security->generateRandomString(20);
$this->featuredFile->saveAs($save_path . $fileName .'.' . $this->featuredFile->extension);
$this->image_url = $ymd . '/'. $fileName . '.' . $this->featuredFile->extension;
return true;
} else {
return false;
}
}
public function upload()
{
if ($this->validate()) {
$ymd = date("Ymd");
$save_path = \Yii::getAlias('#backend') . '/web/uploads/' . $ymd . '/';
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true);
}
$fileName = Yii::$app->security->generateRandomString(20);
$this->featuredFile->saveAs($save_path . $fileName .'.' . $this->featuredFile->extension);
$this->image_url = $ymd . '/'. $fileName . '.' . $this->featuredFile->extension;
return true;
} else {
return false;
}
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->date_added = date("YmdHis");
$this->author = Yii::$app->user->identity->id;
}
else {
$this->date_modified = date("YmdHis");
}
return true;
}
else{
return false;
}
}
public function saveToLog($event)
{
//assigning attributes
// echo 'mail sent to admin using the event';
$app_log_model = new AppLog();
$app_log_model->log_time = date("YmdHis");
$app_log_model->log_activity = 'Added a trending news';
$app_log_model->user_id = Yii::$app->user->identity->id;
$app_log_model->device = "1";
if ($app_log_model->save()) {
return true;
} else {
return $app_log_model->getErrors() ;
}
}
}
usage
public function actionCreate()
{
$model = new TrendingNews();
if ($model->load(Yii::$app->request->post())) {
$model->featuredFile = UploadedFile::getInstance($model, 'featuredFile');
if(isset($model->featuredFile)){
$model->upload();
$model->save(false);
} else {
// file is uploaded successfully
$model->save();
//$model->trigger(BlogArticle::EVENT_EDIT_ARTICLE);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->featuredFile = UploadedFile::getInstance($model, 'featuredFile');
if(isset($model->featuredFile)){
$model->upload();
$model->save(false);
} else {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
the app log shows this
$_FILES = [
'TrendingNews' => [
'name' => [
'featuredFile' => 'another_evento.jpg'
]
'type' => [
'featuredFile' => ''
]
'tmp_name' => [
'featuredFile' => ''
]
'error' => [
'featuredFile' => 3
]
'size' => [
'featuredFile' => 0
]
]
]
featuredFile is not a database field
Is there something that is being done wrong?
I am using xampp,tried on a live server and the issue is same
You are doing it wrong if you have to require a file input on insert and not on the update you should add a scenario for it so that it asks you to provide file when adding a new record only.
Secondly you are using the same ActiveRecord model and added a custom attribute in it to be used as a file input and in the upload() function you are calling validate() and returning false if not validated but on the same time you are not checking for true or false in you controller action and on the very next line you are calling $model->save(false) with false so technically your script would never intimate the user if there is any validation error.
The file should be uploaded after the record is saved not before saving the record so that there are no extra files uploaded in case of error, although you want the file to be required on insert so technically if file is not uploaded the record should not be saved, and for this reason we have transactions for database insertions you should use a transaction block to save the rcord and the file along with it
You should only call the validate() method for file uploading if you have a separate FormModel for file uploading otherwise you should load the instance from the UploadedFile to the model field and call the $model->save() which will automatically validate the model before saving you should just check for the empty filename before uploading so that when you are updating any record and not submitting a file the previous file should be kept as is.
You need to update your validation rules to the following first
/**
* #inheritdoc
*/
public function rules()
{
return [
[['headline_text','news_info', 'news_url', 'author', 'published', 'date_added', 'date_modified'], 'required'],
[['headline_text', 'image_url', 'news_info', 'news_url'], 'string'],
[['date_added', 'date_modified'], 'safe'],
[['author'], 'string', 'max' => 20],
[['published'], 'string', 'max' => 2],
[ [ 'featuredFile' ] , 'required' , 'on' => 'insert' ] ,
[ [ 'featuredFile' ] , 'file' , 'extensions' => 'png, jpg' , 'maxSize' => 200000 , 'tooBig' => 'Limit is 500KB' ] ,
];
}
Change the upload() function to the following
public function upload( $ymd , $fileName ) {
if ( $this->featuredFile !== null && $this->featuredFile->name !== '' ) {
$save_path = \Yii::getAlias ( '#backend' ) . '/web/uploads/' . $ymd . '/';
if ( !file_exists ( $save_path ) ) {
mkdir ( $save_path , 0777 , true );
}
if ( !$this->featuredFile->saveAs ( $save_path . $fileName ) ) {
$this->addError ( 'featuredFile' , 'File could not be uploaded' );
throw new \Exception ( 'File upload error' );
}
}
}
Then add another method inside your model to remove old file in case of new file uploaded on update
public function unlinkOldFile( $filename ) {
if ( $filename !== '' ) {
$save_path = \Yii::getAlias ( '#backend' ) . '/web/uploads/' . $filename;
unlink ( $save_path );
}
}
after that change your create and update actions to the following so that they use transation blocks for database operations
public function actionCreate() {
$model = new TrendingNews(['scenario'=>'insert']);
if ( $model->load ( Yii::$app->request->post () ) ) {
$model->featuredFile = UploadedFile::getInstance ( $model , 'featuredFile' );
if ( $model->featuredFile !== null ) {
$ymd = date ( "Ymd" );
$fileName = Yii::$app->security->generateRandomString ( 20 ) . '.' . $model->featuredFile->extension;
$model->image_url = $ymd . '/' . $fileName;
}
$transaction = Yii::$app->db->beginTransaction ();
try {
if ( !$model->save () ) {
throw new \Exception ( 'Error Occoured' );
}
$model->upload ( $ymd , $fileName );
$transaction->commit ();
return $this->redirect ( [ 'view' , 'id' => $model->id ] );
} catch ( \Exception $ex ) {
$transaction->rollBack ();
}
}
return $this->render ( 'create' , [
'model' => $model ,
] );
}
public function actionUpdate( $id ) {
$model = $this->findModel ( $id );
if ( $model->load ( Yii::$app->request->post () ) ) {
$model->featuredFile = UploadedFile::getInstance ( $model , 'featuredFile' );
//$oldFile = '';
$oldFile = $model->image_url;
if ( $model->featuredFile !== null ) {
$ymd = date ( "Ymd" );
$fileName = Yii::$app->security->generateRandomString ( 20 ) . '.' . $model->featuredFile->extension;
$model->image_url = $ymd . '/' . $fileName;
}
$transaction = Yii::$app->db->beginTransaction ();
try {
if ( !$model->save () ) {
throw new \Exception ( 'Model error' );
}
$model->upload ( $ymd , $fileName );
$model->unlinkOldFile ( $oldFile );
$transaction->commit ();
return $this->redirect ( [ 'view' , 'id' => $model->id ] );
} catch ( Exception $ex ) {
$transaction->rollBack ();
}
}
return $this->render ( 'update' , [
'model' => $model ,
] );
}

Yii2:Trying to get property of non-object

public function actionCreate()
{
$model = new Bookings();
$temp = new RoomTypes();
if ($model->load(Yii::$app->request->post()))
{
$roomtype = $model->room_type;
$totalremain = RoomTypes::find('total_remain')->where(['room_type' => $model->room_type])->one();
if ($roomtype->$totalremain > 0)
{
$imageName = $model->first_name;
$mobile = $model->primary_mobile;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension);
//save the path in the db column
$model->id_image = 'uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
echo "This room Types are full ";
}
}
else {
return $this->render('create', [
'model' => $model,
'temp' => $temp,
]);
}
}
I need to check total_remain from Roomtypes model is > 0 from room_types in Bookings model, before submitting the form if user submit the form it should get flash meassage saying "this room are full"
Getting this error, how to solve this
getting error at if ($roomtype->$totalremain > 0)
Room types model
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "room_types".
*
* #property integer $id
* #property integer $room_id
* #property string $room_type
* #property integer $total_count
* #property string $description
* #property integer $extra_beds
* #property string $images
* #property string $status
* #property integer $rate
* #property integer $adults_count
* #property integer $child_count
* #property integer $total_people
*/
class RoomTypes extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public $imageFiles;
public static function tableName()
{
return 'room_types';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['room_id','total_booked','total_remain','total_count', 'extra_beds', 'rate', 'adults_count', 'child_count'], 'integer'],
[['status'], 'string'],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4,'skipOnEmpty' => true, 'on' => 'update-photo-upload'],
[['room_type'], 'string', 'max' => 40],
[['description'], 'string', 'max' => 300],
[['images'], 'string', 'max' => 500]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'room_id' => 'Room Number',
'room_type' => 'Room Type',
'total_count' => 'Total Count',
'description' => 'Description',
'extra_beds' => 'Extra Beds',
//'images' => 'Images',
'status' => 'Status',
'rate' => 'Rate',
'adults_count' => 'Adults Count',
'child_count' => 'Child Count',
'total_remain' =>'Remaing Rooms',
'total_booked' => 'Total Rooms Booked',
];
}
}
The code if ($roomtype->$totalremain > 0) is causing the problem.Change it like if ($totalremain->total_remain > 0)

ACL not working for some controller which have upload component & imageresize component in cakephp

My cakephp version is 1.3.10, I have added acl component for assign authorize policy.
Its working fine for all controller. But in two controller I have added Upload component (For upload files) and Image Resize component (For resize image)
var $components = array('Upload','ImageResize');
When i try to access my controller AffiliatesController and AwardsController it going in loop and i get error: page is not redirect properly.
If i commented those component then its working fine. Can anyone suggest me what is the issue?
My acl controller is looks like below,
<?php
class AclController extends AppController {
var $name = 'Aco';
var $components = array('Acl');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
}
function build_aco() {
error_reporting(0);
if (!Configure::read('debug')) {
return $this->_stop();
}
$log = array();
$aco = $this->Acl->Aco;
$root = $aco->node('controllers');
if (!$root) {
$aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
$root = $aco->save();
$root['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for controllers';
} else {
$root = $root[0];
}
App::import('Core', 'File');
$Controllers = App::objects('controller');
$appIndex = array_search('App', $Controllers);
if ($appIndex !== false ) {
unset($Controllers[$appIndex]);
}
$baseMethods = get_class_methods('Controller');
$baseMethods[] = 'build_acl';
$Plugins = $this->_getPluginControllerNames();
$Controllers = array_merge($Controllers, $Plugins);
// look at each controller in app/controllers
foreach ($Controllers as $ctrlName) {
$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));
// Do all Plugins First
if ($this->_isPlugin($ctrlName)){
$pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
if (!$pluginNode) {
$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
$pluginNode = $aco->save();
$pluginNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
}
}
// find / make controller node
$controllerNode = $aco->node('controllers/'.$ctrlName);
if (!$controllerNode) {
if ($this->_isPlugin($ctrlName)){
$pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
$aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
$controllerNode = $aco->save();
$controllerNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
} else {
$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
$controllerNode = $aco->save();
$controllerNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $ctrlName;
}
} else {
$controllerNode = $controllerNode[0];
}
//clean the methods. to remove those in Controller and private actions.
foreach ($methods as $k => $method) {
if (strpos($method, '_', 0) === 0) {
unset($methods[$k]);
continue;
}
if (in_array($method, $baseMethods)) {
unset($methods[$k]);
continue;
}
$methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
if (!$methodNode) {
$aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
$methodNode = $aco->save();
$log[] = 'Created Aco node for '. $method;
}
}
}
if(count($log)>0) {
debug($log);
}
exit;
}
function _getClassMethods($ctrlName = null) {
App::import('Controller', $ctrlName);
if (strlen(strstr($ctrlName, '.')) > 0) {
// plugin's controller
$num = strpos($ctrlName, '.');
$ctrlName = substr($ctrlName, $num+1);
}
$ctrlclass = $ctrlName . 'Controller';
$methods = get_class_methods($ctrlclass);
// Add scaffold defaults if scaffolds are being used
$properties = get_class_vars($ctrlclass);
if (array_key_exists('scaffold',$properties)) {
if($properties['scaffold'] == 'admin') {
$methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
} else {
$methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
}
}
return $methods;
}
function _isPlugin($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) > 1) {
return true;
} else {
return false;
}
}
function _getPluginControllerPath($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[0] . '.' . $arr[1];
} else {
return $arr[0];
}
}
function _getPluginName($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[0];
} else {
return false;
}
}
function _getPluginControllerName($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[1];
} else {
return false;
}
}
/**
* Get the names of the plugin controllers ...
*
* This function will get an array of the plugin controller names, and
* also makes sure the controllers are available for us to get the
* method names by doing an App::import for each plugin controller.
*
* #return array of plugin names.
*
*/
function _getPluginControllerNames() {
App::import('Core', 'File', 'Folder');
$paths = Configure::getInstance();
$folder =& new Folder();
$folder->cd(APP . 'plugins');
// Get the list of plugins
$Plugins = $folder->read();
$Plugins = $Plugins[0];
$arr = array();
// Loop through the plugins
foreach($Plugins as $pluginName) {
// Change directory to the plugin
$didCD = $folder->cd(APP . 'plugins'. DS . $pluginName . DS . 'controllers');
// Get a list of the files that have a file name that ends
// with controller.php
$files = $folder->findRecursive('.*_controller\.php');
// Loop through the controllers we found in the plugins directory
foreach($files as $fileName) {
// Get the base file name
$file = basename($fileName);
// Get the controller name
$file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
if (!App::import('Controller', $pluginName.'.'.$file)) {
debug('Error importing '.$file.' for plugin '.$pluginName);
} else {
/// Now prepend the Plugin name ...
// This is required to allow us to fetch the method names.
$arr[] = Inflector::humanize($pluginName) . "/" . $file;
}
}
}
}
#echo "<pre>";
#print_r ($arr);exit;
return $arr;
}
/**
* Setting up permissions, To allow ARO's access to ACO's
*/
function build_permission() {
$group =& $this->User->Group;
//Allow developers to everything
$group->id = 1;
$this->Acl->allow(array('model' => 'Group', 'foreign_key' => 1), 'controllers');
//Allow administrator to everything except "Admin Groups", "Payment Gateways"
$group->id = 2;
$this->Acl->allow(array('model' => 'Group', 'foreign_key' => 2), 'controllers');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Groups');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/view');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/add');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/edit');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/delete');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Staticpages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmstags');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmstagpositions');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmspages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Emailtemplates');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Affiliates');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Awards');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Faqs');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Newsletters');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Newslettersubscribers');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Packages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Transactions');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Testimonials');
//we add an exit to avoid an ugly "missing views" error message
echo "all done";
exit;
}
}
?>

Categories