Yii2 making checkbox required doesn't work - php

This is my form:
<?php $form = ActiveForm::begin(); ?>
<?php echo $form->field($invite, 'email')->textInput([
'id' => 'register-email',
'placeholder' => Yii::t('UserModule.views_auth_login', 'email')]);
?>
<?php echo $form->field($invite, 'check')->checkbox([
'id' => 'check',
'uncheck' => null])->label(
Yii::t('UserModule.views_auth_login', 'I have read and accept') . ' <a href="#">'
. Yii::t('UserModule.views_auth_login', 'Terms & Conditions') . '</a> '
. Yii::t('UserModule.views_auth_login', 'and')
. ' <a href="#">' . Yii::t('UserModule.views_auth_login', 'Privacy Policy')
. '</a>' . '.');
?>
<hr>
<?php
echo \humhub\widgets\AjaxButton::widget([
'label' => Yii::t('UserModule.views_auth_login', 'Register'),
'ajaxOptions' => [
'type' => 'POST',
'beforeSend' => new yii\web\JsExpression('function(){ setModalLoader(); }'),
'success' => 'function(html){ $("#globalModal").html(html); }',
'url' => Url::to(['/user/auth/login']),
],
'htmlOptions' => [
'class' => 'btn btn-primary', 'id' => 'registerBtn'
]
]);
?>
<?php ActiveForm::end(); ?>
rules:
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'unique'],
[['email'], 'email'],
[['email'], 'unique', 'targetClass' => \humhub\modules\user\models\User::className(), 'message' => Yii::t('UserModule.base', 'E-Mail is already in use! - Try forgot password.')],
[['check'], 'required'],
[['check'], 'compare', 'compareValue' => 1, 'message'=>'bla-bla-bla'],
];
}
How do I do my form valid only if both 'email' is not empty an valid and 'check' is checked? Now the issue is 'check' does not validate. Thanks.

Remove the compare rule and update the required rule as shown below.
[['check'], 'required', 'requiredValue' => 1, 'message'=>'bla-bla-bla'],

Try the following:
Add this method in your model:
public function validateCheckWithEmail($attribute, $params)
{
if (empty($this->check) && !empty($this->email) && $this->validateAttribute($this, 'email')) {
$this->addError($attribute, $this->getAttributeLabel($attribute).' field cannon be empty.');
}
}
In your rules add:
[['check'], 'validateCheckWithEmail', 'skipOnEmpty' => false, 'skipOnError' => false],

Related

My filter on index.php is not working

The model is Booking.php. I need to get data from another model called ServiceCategory.php and add a filter to it in Gridview on my index.php. I created filter on view/index.php as below.
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(app\models\Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
This is my index.php
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\models\Servicecategory;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BookingSerach */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bookings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="list-booking">
<h1 class=""><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p class="form-inline text-right">
<label>Client:</label>
<?= Html::dropDownList('client', null, ArrayHelper::map($clients, 'id', 'fullname'), ['prompt' => 'Please Select', 'class' => 'form-control']) ?>
<?= Html::a('+ New Booking', ['booking/create/'], ['class' => 'btn btn-primary client-create']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'value' => 'user.client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
//'numberOfDays',
//'date',
//'followUpEmail:email',
// 'followUpEmailSent:ckeckbox',
//'Status',
['attribute' => 'status', 'value' => 'Status', 'filter' => array_filter(\app\models\Booking::$statuses)],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp(this, "' . $url . '")', 'checked' => false, 'id' => 'followup'];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:15%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
},
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
},
],
],
],
]);
?>
</div>
<?php
$script = <<< JS
$('.client-create').on('click', function () {
select = $(this).prev();
if(select.val()){
location.href = $(this).attr('href')+"/"+select.val();
} else {
$(this).parent().addClass('has-error');
}
return false;
});
JS;
$this->registerJs($script);
$this->registerJs("
function followUp(e, url){
$('#modal').modal('show').find('#modalContent').load(url);
}", yii\web\View::POS_END);
?>
I can get the data to the column on gridview but the filter is not working. Can anyone help me with this?
I solved it myself. For your information I post it here. I changed the attribute as the model contains and added the value as category.name
['attribute' => 'categoryID', 'value' => 'category.name','filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],

Add filter on checkbox column Yii2 Gridview widget

Can you help me to add a filter on checkbox column on Grid view widget yii2? I used yii\grid\CheckboxColumn to add the check box column in the Gridview on my index.php. But I couldn't add a filter above the column as the other columns. Please look into my code below.
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'attribute' => 'name', 'value' => 'client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
[
'attribute' => 'categoryID',
'value' => 'category.name',
'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')
],
[
'attribute' => 'status',
'headerOptions' => ['style' => 'width:12%'],
'value' => 'Status',
'filter' => array_filter(\app\models\Booking::$statuses),
'filterInputOptions' => ['class' => 'form-control', 'prompt' => 'All']
],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:10%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
/* 'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
}, */
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
}
],
],
],
]);
Following is the checkbox column.
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
Can someone help with this?
You may use your Gii tool-> CRUD generator to create your filter file.
Then you can pass your params to search model like this:
$searchModel = new SearchModel;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
You will need to return your $dataProvider from SearchModel
Use the search file for implement filters on grid.
I suggest that do not use gridview filter in your case.
Write your search related code in search file and add checkbox on search form.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="ideas-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?php echo $form->field($model, 'name[]')->checkboxList(
['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

Unable to locate message source for category 'mtrelt'

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

YII2 - How to merge row yii2 gridview?

i have gridview table like this :
i want to merge store 1(example) with 4 row detail information. is it possible to do it with?
i have a code in gridview :
<?php Pjax::begin(['id' => 'pjax_filesetting','timeout'=>false]) ?>
<?php
$this->registerJs(
"
$('.btneditfile').click(function(){
var hqid = $(this).attr('data-hqid');
var storeid = $(this).attr('data-storeid');
var filename = $(this).attr('data-filename');
location.href = '/pos/editfilesetting?hqid='+hqid+'&storeid='+storeid+'&filename='+filename;
return false;
});
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'options' => ['class' => 'grid-view active-table'],
'columns' =>
[
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Store Name',
'attribute' => 'store_name',
'encodeLabel' => false,
],
[
'label' => 'Filename',
'attribute' => 'filename',
'encodeLabel' => false,
],
[
'label' => 'Datecheck',
'attribute' => 'datecheck',
'encodeLabel' => false,
'value' => function($model){
$datecheck = $model["datecheck"];
if($datecheck)
{
return $model["datecheck"] = "Check";
}
else
{
return $model["datecheck"] = "Not Check";
}
}
],
[
'label' => 'Timecheck',
'attribute' => 'timecheck',
'encodeLabel' => false,
'value' => function($model){
$timecheck = $model["timecheck"];
if($timecheck)
{
return $model["timecheck"] = "Check";
}
else
{
return $model["timecheck"] = "Not Check";
}
}
],
[
'label' => 'Maintenance code',
'attribute' => 'maincode',
'encodeLabel' => false,
],
[
'label' => 'Final Filename',
'attribute' => 'usedfilename',
'encodeLabel' => false,
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '<div align="center">{update} {delete}</div>',
'buttons' => [
'update' => function ($url, $model) use ($controller) {
return Html::button(
'<span class="glyphicon glyphicon-pencil"></span>',
[
'class' => 'btn btn-primary btn-xs btneditfile',
'title' => Yii::t( $controller->transmodule, 'Edit' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'id' => 'editfile',
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
'delete' => function ($url, $model)use ($controller){
return Html::button(
'<span class="glyphicon glyphicon-trash"></span>',
[
'class' => 'btn btn-danger btn-xs btndeletefile',
'title' => Yii::t( $controller->transmodule, 'Delete' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
],
]
],
]) ?>
<?php Pjax::end() ?>
what must i do to merge it?
what i need is if the store name is same, merge it column .
Is the store and other details in one table or separate table? If it is in separate tables, the $dataProvider should query from the store table. In the store model create a hasMany relation to the other table which contain the details. So in the view, in the gridview column function you can loop through those values and display it in the same row.

Compare rule yii2 doesn't work correctly

I have my rules method like this:
public function rules()
{
return [
[['username', 'email', 'password'],'filter', 'filter' => 'trim'],
[['username', 'email', 'password'],'required', 'message' => '{attribute} can not be empty'],
['username', 'string', 'min' => 2, 'max' => 255],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'required', 'message' => 'This field can not be empty'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match", 'skipOnError' => true],
['username', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
['email', 'email'],
['email', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
];
}
And my view code is like this:
<?php $form = ActiveForm::begin(['action' => 'login/register']); ?>
<?= $form->field($registration, 'username',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_username', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password_repeat', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'email',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_email', 'class' => 'md-input']) ?>
<div class="uk-margin-medium-top">
<button class="md-btn md-btn-primary md-btn-block md-btn-large">Sign in</button>
</div>
<?php ActiveForm::end(); ?>
When I'm filling all given fields I have an error Passwords don't match when repeat the password even when it's correct at first time. Is there something with my validation rules or is it a bug in Yii Validator?
UPD: I've tried 'skipOnError' => true. I found it as an answer for the similar question but it still doesn't work as it's expected.
UPD: I did some validation in my console:
var a = $('#register_password')
undefined
a.val()
"Halloha"
var b = $('#register_password_repeat')
undefined
b.val()
"Halloha"
But it still shows Passwords don't match error message
try using the rule like this
// validates if the value of "password" attribute equals to that of
['password', 'compare', 'message'=>"Passwords don't match"],
it automatically compares the password value to attribute password_repeat instead of doing it in the other order as explained in the documentation .
http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare
Try avoid the id in password input (the id is automatically generated by yii2)
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput([ 'class' => 'md-input']) ?>

Categories