I'm a begginer so sorry if it's obvious. So, I would like different rules depends on what the user select. I have an update form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'news_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'news_content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'check')->label('Picture update:')
->radioList(
[ 2 => 'Yes', 1 => 'No', 0 => 'Delete']) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And only if the radioList has a value '2' I would like to require the fileInput. I mean if the user select 1 => 'No', or 0 => 'Delete' the fielInput can be empty.
public function rules() {
return [
[['news_content'], 'string'],
[['news_content'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['news_title'], 'required'],
[['news_picture'], 'required'],
[['file'], 'file', 'skipOnEmpty' => $this->checkRadio(), 'extensions' => 'png, jpg',],
[['check'], 'required', 'message' => 'Please ....'],
];
}
public function checkRadio() {
if ($this->check == 2) {
return false;
} else {
return true;
}
}
I tried to write a function in the model but the $check variable always has a 0 value and I don't really understand why. Is there any solution in Yii2 for this?
Here is the documentation which is quite straight forward but something like this should be sufficient
[
'file', 'required',
'when' => function ($model) {
return $model->check == 2;
},
'whenClient' => "function (attribute, value) {
return $('#signupform-check-2').is(':checked');
}",
'message' => 'Please....'
]
As long as you have client validation enabled, you always have to do two checks. backend and front end.
*********** Your Controller Like This ***********************
public function actionCreate(){
$model = new Model();
if(Yii::$app->request->post())
{
if($model->check ==2)
{
$model->scenario ='fileInputRequired';
}
else{
$model->scenario ='fileInputNotRequired';
}
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
********** Your Model Like This *****************
public function rules() {
return [
[['news_content','news_title','news_picture','check'], 'required'],
[['news_content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['file'], 'file', 'on' =>'fileInputRequired', 'extensions' => 'png, jpg',],
];
}
function scenario()
{
return [
'fileInputRequired' => ['news_content', 'news_picture', 'news_title','file','check'];
'fileInputNotRequired' => ['news_content', 'news_picture','news_title','check'];
}
Related
If I try to update records,I get following error without any ideas, what's about or what this error could have been caused by.
Furthermore, it's strange, that this error only will be bred by records having been imported by a dump. There will be no error, if I will update a record having been created using saveasnew option. Unfortunately, I can't delete this record in order to recreate it,'cause it would expel against referential integrity.
Here is error:
Invalid Configuration – yii\base\InvalidConfigException
Unable to locate message source for category 'mtrelt'.
throw new InvalidConfigException("Unable to locate message source for category '$category'.")
2. in ...\vendor\yiisoft\yii2\i18n\I18N.php at line 88 – yii\i18n\I18N::getMessageSource('mtrelt')
3. in ...\vendor\yiisoft\yii2\BaseYii.php at line 509 – yii\i18n\I18N::translate('mtrelt', 'Data can't be deleted because it...', [], 'de-DE')
4. in ...\vendor\mootensai\yii2-relation-trait\RelationTrait.php at line 312 – yii\BaseYii::t('mtrelt', 'Data can't be deleted because it...')
Here is model:
<?php
namespace common\modules\lookup\models\base;
use Yii;
use mootensai\behaviors\UUIDBehavior;
class LPersonArt extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
public function relationNames()
{
return [
'eAppEinstellungArts',
'lKontaktVerwendungszwecks',
'people'
];
}
public function rules()
{
return [
[['person_art'], 'string', 'max' => 50],
[['zieltabelle'], 'string', 'max' => 100],
[['bemerkung'], 'string', 'max' => 255]
];
}
public static function tableName()
{
return 'l_person_art';
}
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'person_art' => Yii::t('app', 'Personengruppen'),
'zieltabelle' => Yii::t('app', 'Zieltabelle'),
'bemerkung' => Yii::t('app', 'Bemerkung'),
];
}
public function getEAppEinstellungArts()
{
return $this->hasMany(\common\modules\erweiterung\models\EAppEinstellungArt::className(), ['id_person_art' => 'id']);
}
public function getLKontaktVerwendungszwecks()
{
return $this->hasMany(\common\modules\lookup\models\LKontaktVerwendungszweck::className(), ['id_person_art' => 'id']);
}
public function getPeople()
{
return $this->hasMany(\common\modules\basis\models\Person::className(), ['id_person_art' => 'id']);
}
public function behaviors()
{
return [
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
public static function find()
{
return new \common\modules\lookup\models\LPersonArtQuery(get_called_class());
}
}
Here is Controller:
public function actionUpdate($id)
{
$model = new LPersonArt();
if (!Yii::$app->request->post('_asnew') == '1'){
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Here is view:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="lperson-art-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'id', ['template' => '{input}'])->textInput(['style' => 'display:none']); ?>
<?=
$form->field($model, 'person_art')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 50,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<?=
$form->field($model, 'bemerkung')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 255,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<div class="form-group">
<?php if (Yii::$app->controller->action->id != 'save-as-new'): ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php endif; ?>
<?php if (Yii::$app->controller->action->id != 'create'): ?>
<?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn btn-info', 'value' => '1', 'name' => '_asnew']) ?>
<?php endif; ?>
<?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer, ['class' => 'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Problem will be solved adding following code into components of
common/config/main-local.php
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages', // if advanced application, set #frontend/messages
'sourceLanguage' => 'de',
],
],
],
I was having a similar problem, but the Yii2 error message was
Unable to locate message source for category ''
I was running Gii from console:
php yii gii/crud --controllerClass="app\controllers\StcDocumentTypeController" --messageCategory="stc_document_type" --enableI18N=1 --enablePjax=1 --interactive=0 --modelClass="app\models\StcDocumentType" --searchModelClass="app\models\StcDocumentTypeSearch" --overwrite=1
The solution was to add the i18n configuration on the console.php config file:
'components' => [
...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en-US',
],
]
],
...
]
If you're running from web check also that config in web.php
Hello I am working on Yii2 project. I have user module, in that while update any user the input filed password is coming with original password. I want to make password field null on update page.
I am using password hash, but in update page password coming with its original value, I tried to null that filed but with bad luck.
I tried :
<?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true,'value'=>null]) ?>
Even I tried
$model->password_hash="" in controller but nothing happen.
But nothing happen still password field coming with its value.
This is my user model rules :
public function rules() {
return [
[['first_name', 'last_name', 'address', 'mobile', 'email', 'password_hash', 'role_id'], 'required'],
[['address'], 'string'],
[['role_id'], 'integer'],
[['email'], 'email'],
[['email'], 'unique', 'targetAttribute' => ['email']],
[['created_at', 'updated_at'], 'safe'],
[['first_name', 'last_name', 'email', 'password_hash'], 'string', 'max' => 255],
[['mobile'], 'required','on'=>'create,update'],
//[['mobile'], 'string','max'=>10],
[['mobile'], 'number','numberPattern' => '/^[0-9]{10}$/','message'=>"Mobile must be integer and should not greater then 10 digit"],
[['password_hash'],'string','min'=>6],
//[['mobile'], 'number'],
[['status'], 'string', 'max' => 1,'on'=>'create,update'],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
];
}
User controller :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$roles= Roles::find()->all();
$model->password_hash="";
if ($model->load(Yii::$app->request->post())) {
$input=Yii::$app->request->post();
if($input['Users']['password_hash']!=""){
$model->password_hash=User::setPassword($model->password_hash);
}
//$model->auth_key=User::generateAuthKey();
$model->status=$input['Users']['status'];
unset($model->created_at);
$model->updated_at=date('Y-m-d H:i:s');
//echo "<pre>";print_r($model);exit;
$model->save();
Yii::$app->session->setFlash('success', "Record has been updated successfully !");
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
'roles'=>$roles
]);
}
}
User Form :
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="row">
<div class="col-md-8">
<?= $form->field($model, 'address')->textarea(['rows' => 6]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true,'value'=>""]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'status')->dropDownList(['0'=>'Active','1'=>'InActive']); ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'role_id')->dropDownList(ArrayHelper::map(Roles::find()->all(),'id','name')) ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => 'btn green']) ?>
<?= Html::a('Cancel', ['/ag-consumer'], ['class' => 'btn default']) ?>
</div>
<?php ActiveForm::end(); ?>
Dont take password_hash. You have to create new variable in model e.g password
public $password;
public function rules() {
return [
[['first_name', 'last_name', 'address', 'mobile', 'email', 'password', 'role_id'], 'required'],
[['address'], 'string'],
[['role_id'], 'integer'],
[['email'], 'email'],
[['email'], 'unique', 'targetAttribute' => ['email']],
[['created_at', 'updated_at'], 'safe'],
[['first_name', 'last_name', 'email', 'password'], 'string', 'max' => 255],
[['mobile'], 'required','on'=>'create,update'],
//[['mobile'], 'string','max'=>10],
[['mobile'], 'number','numberPattern' => '/^[0-9]{10}$/','message'=>"Mobile must be integer and should not greater then 10 digit"],
[['password'],'string','min'=>6],
//[['mobile'], 'number'],
[['status'], 'string', 'max' => 1,'on'=>'create,update'],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
];
}
View
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true,'value'=>null]) ?>
Model or Controler example
if ($this->validate()) {
$user = User::findOne($id);
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save(false);
}
Why not remove it on update at all?
Like so :
<?= $model->isNewRecord ? $form->field($model, 'password_hash')->passwordInput(['maxlength' => true]) : "" ?>
Happy coding. :)
UPDATE
If the password field is really need to be there, then try this in Controller :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$password = $model->password_hash; // backup the value first;
$model->password_hash = "";
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->password_hash = $password; // retreive the value back
$model->save();
// redirect here
}
return $this->render('update', [
'model' => $model,
]);
}
tips : username and email is check by ajaxValidation with validate method.
all is correct but i guess captcha is changed in server but the old picture is in client.
i googling alot no result found.
this is view:
<?php
$form = \yii\widgets\ActiveForm::begin([
'id' => 'form-signup',
'action' => 'signup',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
'validationUrl' => 'validation',
'validateOnBlur' => true,
'fieldConfig' => [
'template' => '<div class="col-md-4" >{label}{input}{error}</div>'
]
]);
?>
<?= $form->field($signup, 'username', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'name') ?>
<?= $form->field($signup, 'family') ?>
<?= $form->field($signup, 'mobile') ?>
<?= $form->field($signup, 'password')->passwordInput() ?>
<?= $form->field($signup, 'password_repeat')->passwordInput() ?>
<?= $form->field($signup, 'email', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'verifyCode', ['enableAjaxValidation' => false])->widget(yii\captcha\Captcha::className()) ?>
<div class="form-group">
<?= yii\helpers\Html::submitButton('signup', ['class' => 'btn btn-green margin-right', 'name' => 'signup-button']) ?>
</div>
controller:
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
} else {
;
\yii\widgets\ActiveForm::validate($model);
}
} else {
return $this->render('/partials/_signup', ['signup' => $model]);
}
ajax validation controller method:
public function actionValidation() {
$model = new SignupForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
}
model:
public $name;
public $family;
public $mobile;
public $username;
public $email;
public $password;
public $password_repeat;
public $verifyCode;
public function rules() {
return [
[['name', 'family', 'mobile'], 'default'],
['name', 'string', 'max' => 50],
['family', 'string', 'max' => 50],
['mobile', 'string', 'max' => 11],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'string', 'min' => 2, 'max' => 255],
[['username'], 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'username already taken.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'email name already taken.'],
['password', 'required'],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
];
}
there is no behaviour in controller
enableAjaxValidation of a form takes precedence over that of a field, so it's hard to tell what exactly you are trying to do with your current settings
Make sure you have verifyCode declared as an attribute on your model
Captcha verification code is saved in the session. The session key is a combination of controller's and action's ids. So you might have a misconfigured session. Or your captcha's action name is not 'captcha', - you are missing that part of your source code in the question.
I have to create 2 signup form for different user but,I have use one table for both signup form. table is 'User' but in both form some field are different and table is same for both.But when I validate first form that time second form also validate.please help me I am new in yii2.
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<button type = "submit" class = "btn btn-primary pull-right">
<strong>Signup User</strong>
</button>
</div>
<?php ActiveForm::end(); ?>
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model2, 'fname') ?>
<?= $form->field($model2, 'mname') ?>
<?= $form->field($model2, 'lname') ?>
<?= $form->field($model2, 'username') ?>
<?= $form->field($model2, 'email') ?>
<?= $form->field($model2, 'password')->passwordInput() ?>
<?= $form->field($model2, 'designation') ?>
<?= $form->field($model2, 'contact_no') ?>
<button type = "submit" class = "btn btn-success pull-right">
<strong>Signup Vendor</strong>
</button>
<?php ActiveForm::end(); ?>
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['fname', 'required'],
['mname', 'required'],
['lname', '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],
['designation', 'required'],
['designation', 'string', 'max' => 100],
['contact_no', 'required'],
['contact_no', 'number', 'max' => 12],
];
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
return $this->redirect(['login']);
if (Yii::$app->getUser()->login($user)) {
}
}
}
$model2 = new SignupForm2();
if ($model2->load(Yii::$app->request->post())) {
if ($user = $model2->signup()) {
return $this->redirect(['login']);
if (Yii::$app->getUser()->login($user)) {
}
}
}
return $this->render('signup', [
'model' => $model,
'model2' => $model2,
]);
}
Now It's Work,I am create 2 signupForm.php in front end models.and in siteController create two models in actionSignup
validate
Change id in Active::begin
...
<?php $form = ActiveForm::begin(['id' => 'form-signup-one']); ?>
...
<?php $form = ActiveForm::begin(['id' => 'form-signup-two']); ?>
...
I am new to yii and php.
I want to upload a file and save its path to database but while doing so I got an error.
My controller class is:
public function actionCreate()
{
$model = new Quiz();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$fileName = $model->name;
$model->file =UploadedFile::getInstance($model,'file');
$model->file->saveAs('uploadQuiz/'.$fileName.'.'.$model->file->extension );
$model->filePath = 'uploadQuiz/'.$fileName.'.'.$model->file->extension ;
$model->save();
return $this->redirect(['view', 'id' => $model->idQuiz]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
My database column name where I save my file path is "filePath".
My view file is:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Quiz */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="quiz-form">
<?php $form = ActiveForm::begin(['option' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'Course_idCourse')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'duration')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'time')->textInput() ?>
<?= $form->field($model, 'file')->fileInput(); ?>
<?= $form->field($model, 'totalMarks')->textInput(['maxlength' => 100]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My rules and attributes are:
public function rules()
{
return [
[['Course_idCourse', 'duration', 'time'], 'required'],
[['Course_idCourse', 'duration', 'totalMarks'], 'integer'],
[['time'], 'safe'],
[['file'],'file'],
[['name', 'filePath'], 'string', 'max' => 200],
[['description'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idQuiz' => 'Id Quiz',
'Course_idCourse' => 'Course Id Course',
'name' => 'Name',
'description' => 'Description',
'duration' => 'Duration',
'time' => 'Time',
'file' => 'Quiz ',
'totalMarks' => 'Total Marks',
];
}
Now I already refer this site for the same question but I find it for update not for create . kINDLY HELP ME.
When I run try to create I got an error
Call to a member function saveAs() on a non-object
I don't figure where am I going wrong.
No file is being uploaded. The option parameter in the ActiveForm initialization should be options
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>