我正在使用 yii2 构建一个具有注册功能的简单应用程序。问题是当我使用活动表单呈现文件输入标签时,它会呈现文件输入字段和隐藏字段。验证器然后选择一个隐藏的并且总是说需要配置文件图像,尽管它将它保存在我的上传目录中,并且还将路径添加到数据库,但仍然返回此错误。谢谢你的帮助。
这是代码:查看:
<?php $form = ActiveForm::begin(['id' => 'form-signup' , 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'profile_path')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]); ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
SignupForm // 模型类
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public $profile_path;
/**
* @inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
[['profile_path'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->setProfilePicture($this->profile_path);
if ($user->save(false)) {
return $user;
}
}
return null;
}
public function upload()
{
if ($this->validate()) {
$this->profile_path->saveAs('uploads/' . $this->profile_path->baseName . date('Y-m-d H:i:s') . '.' . $this->profile_path->extension);
$this->profile_path = 'uploads/' . $this->profile_path->baseName . '.' . $this->profile_path->extension;
return true;
} else {
return false;
}
}
}
输出:
<label class="control-label" for="signupform-profile_path">Profile Path</label>
<input type="hidden" value="" name="SignupForm[profile_path]">
<input id="signupform-profile_path" type="file" name="SignupForm[profile_path]">
<p class="help-block help-block-error">Please upload a file.</p>