Yii2: How to make validation rule message not to be encoded? - php

In base PasswordResetRequestForm model:
public function rules()
{
return [
['email', 'exist',
'targetClass' => '\common\models\User',
'filter' => ['status' => User::STATUS_ACTIVE],
'message' => 'Such user is not registered. '.BaseHtml::a('Signup.',['site/signup'])
],
];
}
But link renders encoded. How to force it not to be encoded? Where should I do it, in ActiveForm, in field config, or in validation rule?

I don't know about the past, but now you can configure it in the fieldConfig:
$form = ActiveForm::begin([
'fieldConfig' => [
'errorOptions' => ['encode' => false],
],
]);

You can configure this on ActiveForm :
<?php $form = ActiveForm::begin([
'encodeErrorSummary' => false,
]); ?>
Read more : http://www.yiiframework.com/doc-2.0/yii-widgets-activeform.html#$encodeErrorSummary-detail

Related

Yii2 Unknown model map key

I'm extending the registrationForm model for yii2-usuario, and overriding the rules() function.
my model looks like this
namespace app\models\user\Form;
use Da\User\Form\RegistrationForm as BaseForm;
class RegistrationForm extends BaseForm
{
public $captcha;
public $firstname;
public $lastname;
public $password_repeat;
public function rules()
{
/** #var User $user */
$user = $this->getClassMap()->get(User::class);
return [
// username rules
'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255],
'usernameTrim' => ['username', 'filter', 'filter' => 'trim'],
'usernamePattern' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\.#]+$/'],
//'usernameRequired' => ['username', 'required'],
'usernameUnique' => [
'username',
'unique',
'targetClass' => $user,
'message' => Yii::t('usuario', 'This username has already been taken'),
],
...
...
}
}
but i'm getting this error
Unknown model map key: app\models\user\Form\User on this line $user = $this->getClassMap()->get(User::class);
Not sure how to fix this. The user.php model is in the correct directory app\models\user\Form\User.php
UPDATE:
in my main.php
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'classMap' => [
'RecoveryForm' => 'app\models\user\Form\RecoveryForm',
'RegistrationForm' => 'app\models\user\Form\RegistrationForm',
'ResendForm' => 'app\models\user\Form\ResendForm',
'User' => app\models\user\Model\User::class
],
'viewPath' => '#app/views/user',
'controllerMap' => [
'registration' => [
'class' => app\controllers\user\RegistrationController::class, //\Da\User\Controller\RegistrationController::class,
'on ' . \Da\User\Event\FormEvent::EVENT_AFTER_REGISTER => function (\Da\User\Event\FormEvent $event) {
\Yii::$app->session->setFlash('info', Yii::t('usuario', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'));
\Yii::$app->controller->redirect(['/user/security/login']);
},
'on ' . \Da\User\Event\FormEvent::EVENT_AFTER_RESEND => function (\Da\User\Event\FormEvent $event) {
\Yii::$app->session->setFlash('info', Yii::t('usuario', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'));
\Yii::$app->controller->redirect(['/user/security/login']);
},
],
],

Yii 2 Kartik input validation message is coming while clicking the browse button only

<?php use kartik\file\FileInput;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'import-pdf',
'options' => ['enctype' => 'multipart/form-data'],
]); ?>
<?=
$form->field($model, 'file_name')->widget(FileInput::classname(), [
'options' => ['multiple' => false],
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
],
]);
?>
//file_name is the attribute I'm using it
public function rules()
{
return [
[['file_name'], 'required'],
[['status', 'total_pages', 'processed_pages', 'file_type'], 'safe'],
[['total_pages', 'processed_pages', 'file_type'], 'integer'],
[['file_name'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
[['status'], 'string', 'max' => 255],
];
}
File name cannot be blank message is coming while clicking browse button only, It should show the validation message after selecting the file only
https://i.stack.imgur.com/GuENh.png
Have you tried to assign to $file_name the uploadedFile instance before the validation?
$model->file_name = UploadedFile::getInstance($model, 'file_name');
or
$model->file_name = UploadedFile::getInstanceByName('nameOfTheField');

Yii2 required validation rule on "select2" widget

I'm using kartik select2 widget in Yii2 framework. Required validation rule doesn't work on it.
Here is my view code:
$form->field($model, 'city')->widget(\kartik\select2\Select2::classname(), [
'data' => $cities,
'options' => [
'class' => 'form-control',
'placeholder' => 'Please select city...',
'multiple' => false,
],
'pluginOptions' => [
'allowClear' => true
],
])->label('City');
Here is my model rule code:
[['city'], 'required'],
[['city'], 'integer']
Any idea to make the dropdown required?
Use this in plugin option
pluginOptions' => [
'initialize' => true,
],
This is working code for me
$form->field($model, 'tech_type')->widget(Select2::classname(), [
'options'=>['id'=>'tech-id'],
'data' => ArrayHelper::map(Techtypes::find()->asArray()->all(), 'tech_id', 'tech_type'),
'pluginOptions'=>[
'initialize' => true,
'placeholder' => 'Select Technician Type ...',
]
]);

uploading multiple images using yii2 and kartik fileInput extension

I have this little problem in uploading multiple images using yii2 and Kartik fileInput extension.
this is the model:
public $file;
public static function tableName()
{
return 'news';
}
public function rules()
{
return [
[['news_desc', 'news_context', 'news_first_source', 'news_second_source', 'news_third_source', 'news_responsibe_party', 'news_first_testimony', 'news_second_testimony', 'news_body', 'news_lang'], 'string'],
[['news_gov_id', 'news_typ_id', 'news_is_in_slider', 'news_is_act', 'news_is_del'], 'integer'],
[['news_happened_date', 'news_created_date', 'file'], 'safe'],
[['news_typ_id', 'news_lang'], 'required'],
[['news_title'], 'string', 'max' => 255],
[['file'], 'file','maxFiles' => 6],
];
}
as you can notice I am using maxFiles but it didnt worked for me
Controller:
public function actionCreate_news()
{
$model = new News();
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstances($model, 'file');
var_dump($model->file);
die();}}
right now I am just var dump the files I get but the problem there is only one file not all the files i uploaded
view:
echo FileInput::widget([
'model' => $model,
'attribute' => 'file[]',
'name' => 'file[]',
'options' => [
'multiple' => 'true',
'accept' => 'image/*'
],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'allowedFileExtensions' => ['jpg','jpeg','png'],
'overwriteInitial' => false
],
]);
i have read all things about this issue and tried all the possible solutions but the problem is still there
when i press submit for the form only the last file will be submited
thanks
Remove 'name' => 'file[]', from this widget also single quotes from true.
echo FileInput::widget([
'model' => $model,
'attribute' => 'file[]',
'options' => [
'multiple' => true,
'accept' => 'image/*'
],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'allowedFileExtensions' => ['jpg','jpeg','png'],
'overwriteInitial' => false
],
]);
Original:
echo FileInput::widget([
'model' => $model,
'attribute' => 'attachment_1[]',
'options' => ['multiple' => true]
]);
Thank you all I figured out the solution for my question i was trying to upload the images when submitting the form but it turned that i was wrong so i used the widget to upload the images using ajax like in here:
http://webtips.krajee.com/ajax-based-file-uploads-using-fileinput-plugin/
then using the plugin event i took the names of files to save in the DB when the form submited

Yii2, Custom validation message with attribute names

In Login form, I need to have glyphicon-remove icon at the end of every validation message with the corresponding field names. So I used below code in the Login model.
['email', 'required', 'message' => 'Email cannot be blank<span class="glyphicon glyphicon-remove"></span>'],
['password', 'required', 'message' => 'Password cannot be blank<span class="glyphicon glyphicon-remove"></span>']
Instead of this above code, Is there any possible way to use something like the below code.
[['email', 'password'], 'required', 'message' => $attribute.' cannot be blank<span class="glyphicon glyphicon-remove"></span>']
The idea of the above code is to get corresponding field name dynamically for every fields.
Please do the needful. Thanks.
Update
The HTML code (<span class="glyphicon glyphicon-remove"></span>) here I've used is output correctly by using encode=>'false'. But what I need is instead of defining separately for every fields, need to define commonly for all fields.
You can use {attribute} in your message to reference the attribute name.
public function rules()
{
return [
[
['email','password', 'password_verify', 'alias', 'fullname'],
'required',
'message' => '{attribute} is required'
],
[['email'], 'email'],
[['fullname'], 'string', 'max' => 50],
[['password', 'password_verify'], 'string', 'min' => 8, 'max' => 20],
[['password_verify'], 'compare', 'compareAttribute' => 'password'],
];
}
You can also use the other options set in the validator like {min} or {requiredValue}
Add this in your form:
_form.php
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'help-block']]
]);
?>
errorOptions default encoding is true so, your html code is encoded as message, so it won't work until you set 'encode' => false.

Categories