Yii2 - 在模型中提交时如何从Widget获取数据?
问题描述:
我正在使用一个小工具来裁剪和上传图像到Yii2服务器。
Yii2 - CropperYii2 - 在模型中提交时如何从Widget获取数据?
我实现了在视图中的小部件,基于控件的文档,并submited的数据模型至极应该上传的文件名保存到数据库中的一个新条目。但是,它始终将其保存为Null。
newform.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\budyaga\cropper\Widget;
use yii\helpers\Url;
$this->title='Upload New';
?>
<h1><?= Html::encode($this->title) ?></h1>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title') -> textInput();?>
<?= $form->field($model, 'description') -> textInput(); ?>
<?= $form->field($model, 'link') -> textInput(); ?>
<?= $form->field($model, 'image')-> widget(Widget::className(), [
'uploadUrl' => Url::toRoute('/admin/uploadPhoto'),
'width' => 236,
'height' => 234,
'cropAreaWidth' => 500,
'cropAreaHeight' => 500,
'thumbnailWidth' => 236,
'thumbnailHeight' => 234,
]);?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']); ?>
</div>
<?php ActiveForm::end(); ?>
在控制器方法
public function actionNews(){
$model = new NewsForm();
$model->setScenario('addNew');
if ($model->load(Yii::$app->request->post()) && $model->addNew()) {
return $this->render('newsmanager');
} else {
return $this->render('newform', ['model' => $model]);
}
}
模型
class Newnews extends \yii\db\ActiveRecord{
public static function tableName()
{
return 'news';
}
public function rules()
{
return [
[['visits', 'user_id'], 'integer'],
[['user_id'], 'required'],
[['title', 'image'], 'string', 'max' => 45],
[['description', 'link'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
public function attributeLabels()
{
return [
'idnew' => 'Idnew',
'title' => 'Title',
'description' => 'Description',
'image' => 'Image',
'visits' => 'Visits',
'user_id' => 'User_ID',
'link' => 'Link',
'dateu' => 'Dateu'
];
}
}
NewsForm.php
class NewsForm extends Model
{
public $image;
public $title;
public $description;
public $link;
public function rules()
{
return [
[['title','description','link'],'required'],
['image','safe', 'on'=>'addNew']
];
}
public function addNew(){
if($this->validate()){
$newnew=new Newnew();
$newnew->title=$this->title;
$newnew->description=$this->description;
$newnew->link=$this->link;
$newnew->image;
$newnew->user_id=Yii::$app->getUser()->getId();
$newnew->visits=0;
$newnew->dateu=date("Y-m-d H:i:s");
return $newnew->save();
}
}
}
当我尝试保存数据,我得到了图像的空。我不知道如何从wiget获取数据以提取模型中图像的名称。我如何访问这些数据?
答
加入NewsForm:
/**
* @var UploadedFile
*/
public $imageFile;
和在验证规则:
[['imageFile'], 'file', 'mimeTypes' => 'image/jpeg, image/png', 'maxSize' => 5000000],
在ADDNEW()函数:
$this->imageFile = UploadedFile::getInstance($this, 'imageFile');
$file = $this->imageFile;
$fname = $file->baseName
$fext = $file->extension
//etc...
//then validate and save file and model as you want.
在视图形式:
<?= $form->field($model, 'imageFile ')-> widget(Widget::className(), [
//config...
]);