How to add contextual classes in Yii 2 ActiveField / ActiveForm? - php

In Bootstrap 3 we can add a contextual class to a form-group container which will color that form field container in a specific color, ie. has-error will render it reddish:
<div class="form-group has-error">
<label for="field">Erroneous label</label>
<input type="text" class="form-control" placeholder="Erroneous input" id="field" />
<p class="help-block">Erroneous help-block</p>
</div>
Label, the input's text color and border and final p.help-block will all become red.
In Yii 2 we can use ActiveForm and ActiveField to do the same in one-liner:
<?= $form->field($model, 'field')
->textInput(['maxlength' => true, 'placeholder' => 'Erroneous input'])
->label('Erroneous label')
->hint('Dummy hint') ?>
And it generates roughly the same markup as above, in a form-group container.
I have gone through the docs and didn't find a way to add a has-error class to the form-group container.
$hintOptions
$inputOptions
$labelOptions
Do not work for this scenario.

Yii automatically adds has-error class in case of validation errors.
If you want to add any CSS-class to ActiveField container then you can use options property. For example:
<?= $form->field($model, 'field', [
'options' => [
'class' => 'form-group has-error',
],
])
->textInput(['maxlength' => true, 'placeholder' => 'Erroneous input'])
->label('Erroneous label')
->hint('Dummy hint');
?>

Related

How to disable button when text input is empty in yii2?

I want to disable button when text input is empty in yii2?
can you help me?
this is my code
thanks
<div class="pemesanan-search thumbnail padding-baru col-sm-6 input">
<?php $form = ActiveForm::begin([
'action' => ['menubayar'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'NO_REKENING') ?>
<?= $form->field($model, 'NO_KARTU') ?>
<?= $form->field($model, 'NAMA') ?>
<div class="form-group">
<center><?= Html::submitButton('Cek Kartu Kredit', ['class' => 'btn btn-default']) ?></center>
</div>
<?php ActiveForm::end(); ?>
</div>
First disable the submit button by default, by using disabled attribute
in button's option.
After that you have to register a JS code using Yii2 RegisterJS.
Then trigger event using jQuery to remove disabled attribute after the input value is changed.
$( "# [id of the input that needs value]" ).change(function() {
$('input[type="submit"]').removeAttr('disabled');
});
By using above code, if you change the value of the input whith this id, it means that its not empty anymore and the disabled attribute will be removed.
Or also you can check if $("# [id of the input that needs value]").val(); is not empty remove the disabled attribute again with this code:
$('input[type="submit"]').removeAttr('disabled');
P.S: You may also define rules in its model and make that attribute as Required in the model rule, and let Yii handles the validation. You can learn more about that by reading This document.

Possible to Display Entered Data in Dynamically Created Fields?

I am using Laravel 5.3.18 to build a form that allows the user to enter one or more dates. I am also using the HTML/Form library from the Laravel Collective along with a FormRequest object to validate the fields. My problem is when the user dynamically adds in more date inputs (via JavaScript) and submits the form, if it doesn't pass validation, the "dynamically" added data (and inputs) are not redisplayed on the form.
My question is: Does Laravel handle this use case? And if so, how can I make this work (or what am I doing wrong)? Your insights and help are much appreciated!
Here is the actual snippet of code that initially generates the date inputs:
#foreach ($eventDates as $index=>$eventDate)
<div class="form-group{{ $errors->has('eventDates.'.$index.'.start_datetime') ? ' has-error' : '' }}" id="{{ 'event_date_group_'.$index }}">
{!! Form::label('eventDates['.$index.'][start_datetime]', 'Event Dates (Day '.($index + 1).')', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-3">
{!! Form::text('eventDates['.$index.'][start_datetime]', $eventDate['start_datetime'], ['id' => 'start_datetime_'.$index, 'class' => 'datetimepicker form-control']) !!}
#if ($errors->has('eventDates.'.$index.'.start_datetime'))
<span class="help-block"><strong>{{ $errors->first('eventDates.'.$index.'.start_datetime') }}</strong></span>
#endif
</div>
</div>
#endforeach
which generates this:
<div class="form-group" id="event_date_group_0">
<label for="eventDates[0][start_datetime]" class="col-md-4 control-label">Event Dates (Day 1)</label>
<div class="col-md-3">
<input id="start_datetime_0" class="datetimepicker form-control" name="eventDates[0][start_datetime]" type="text">
</div>
</div>
So, if the user dynamically creates another date input, it will look as follows:
<div class="form-group" id="event_date_group_0">
<label for="eventDates[0][start_datetime]" class="col-md-4 control-label">Event Dates (Day 1)</label>
<div class="col-md-3">
<input id="start_datetime_0" class="datetimepicker form-control" name="eventDates[0][start_datetime]" type="text">
</div>
</div>
<div class="form-group" id="event_date_group_1">
<label for="eventDates[1][start_datetime]" class="col-md-4 control-label">Event Dates (Day 2)</label>
<div class="col-md-3">
<input id="start_datetime_1" class="datetimepicker form-control" name="eventDates[1][start_datetime]" type="text">
</div>
</div>
And here is part of my FormRequest object:
public function rules() {
return [
'name' => 'required|max:100',
'eventDates.*.start_datetime' => 'required',
'eventDates.*.end_datetime' => 'required',
...
];
}
public function messages() {
return [
'eventDates.*.start_datetime.required' => 'Start date/time is required.',
'eventDates.*.end_datetime.required' => 'End time is required.',
...
];
}
Lastly, the validation works. The error messages show up for the dates input. In fact, if I dynamically create the extra date inputs. Fill everything out but leave just the dynamic date inputs blank, the validation will fail and the form will redisplay but the dynamic inputs and data don't show up. I also put in the following debug statement in the template to see how many elements come back in the array and it always show just 1.
<p>Number of Dates: {{ count($eventDates) }}</p>

Styling form in Yii2 (ActiveField / ActiveForm)

I'm really struggling getting my layout into Yii2. To be as close as possible to the state-of-the-art, I read about styling the ActiveField and ActiveForm, which kinda works, but not to 100%. Maybe you see whats wrong.
Let me start of with my HTML, which I want to have:
// normal state without any validations
<p>
<label for="signup_name">Name, Surname:<span class="required">*</span></label>
<input type="text" name="signup_name" id="signup_name" value="" />
</p>
// input field after validation fails (ajax + reload)
<p>
<label for="signup_email">E-mail:<span class="required">*</span></label>
<input class="error-input" type="text" name="signup_email" id="signup_email" value="" />
<span class="error-msg">E-mail must be filled !</span>
</p>
This is the current state, in which the layout is in:
<p>
<label class="control-label" for="signupform-username">Username</label>
<input id="signupform-username" class="form-control" type="text" name="SignupForm[username]">
<span class="error-msg">Username may not be empty</span>
</p>
This is my PHP / Yii2-part
<?php
$form = ActiveForm::begin([
'id' => 'form-signup',
'fieldConfig' => [
'template' => "<p>{label}{input}{error}</p>",
'errorOptions' => [
'tag' => 'span',
'class' => 'error-msg',
],
],
]);
echo $form->field($model, 'username', [
'inputTemplate' => '{input}',
])->textInput(['autofocus' => false])
?>
The Problems:
The <span class="error-msg"> is always rendered, even though there is no error yet. To clarify: The span has no content and is rendered like this:
<span class="error-msg"></span> (I want it to be there if there IS actually an error, not as a placeholder before
I can't figure out on how to apply an error-class to the input, which works for the ajax-validation, as well as the not JS-way.
Any help is appreciated,
thanks
you can add class for each field if you want
<?= $form->field($model, 'title')->textInput(['class'=>'form-control'])->label('Your Label',['class'=>'label-class']) ?>
Try to disable ajax validation of input field.
echo $form->field($model, 'username', ['enableAjaxValidation' => false]);
or
echo $form->field($model, 'username', ['enableClientValidation' => false]);

How to Customizing/add a class to the ActiveForm items with Material Bootstrap design classes on Yii2

I'm trying to add a class for a TextField like this one:
<div class="form-group-lg">
<?= $form->field($model, 'email'); ?>
</div>
Output:
And that would be something like this?(the label will be inside the TextField).i mean, can we use it like below codes?
Example:
I need something like this:
<div class="form-group label-floating">
<label class="control-label" for="focusedInput1">Write something to make the label float</label>
<input class="form-control" id="focusedInput1" type="text">
</div>
http://fezvrasta.github.io/bootstrap-material-design/bootstrap-elements.html
Forms section-first one.
So, the question is,
How can i add a class to this item with above codes on Yii2 ActiveForm?
You need to use fieldConfig Propertie in ActiveForm.
Like as
<?php $form = ActiveForm::begin([
'id' => 'active-form',
'fieldConfig' => [
'template' => "<div class=\"form-group label-floating\">{label}{input}{error}</div>",
],
]); ?>
For more info read Docs

Zend Framework. How to add extra class to label

My problem is after the form has been generated, the label class has assigned to a default which is optional and the html code looks like this:
<div class="form_wrapper">
<label for="email" class="optional">Username(e-mail):</label>
<input type="text" name="email" id="email" value="">
</div>
My zend code inside action is:
$form->addElement('text', 'email');
$usernameElement = $form->getElement('email');
$usernameElement->setLabel('Username(e-mail):');
$usernameElement->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div','class'=>'form_wrapper'))
));
But in some case, I want it to be set as a different value that I can easily style in css. The html code I want is this(get rid of "optional"):
<div class="form_wrapper">
<label for="email" class="email_label">Username(e-mail):</label>
<input type="text" name="email" id="email" value="">
</div>
Assuming this is ZF1, I dug this out the reference for 1.12.3:
$form->getElement('elementname')
->setDecorators(array(
array('ViewHelper',
array('helper' => 'formText')),
array('Label',
array('class' => 'another'))
));
The above provides you with an additional class. So you'll get something like:
<label for="elementname" class="another optional">Your Label Text</label>
OR
<label for="elementname" class="another required">Your Label Text</label>
Take a look at this similar question:
Zend_Form - add CSS Class :: How can I add css class to label in Zend_Form?
Adding a class to the form element itself is as simple as:
$usernameElement->class = 'email_label';
It appears that if you want to set the class on the label though, you'll want to add a Zend_Form_Decorator_Label and pass in the classname.

Categories