Styling form in Yii2 (ActiveField / ActiveForm) - php

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]);

Related

Form validation in select field

Is there a way I can check if a user didn't manipulate the form? In my form, I get all available entries, but if a user changes the value id in the browser, I would just get an error. Any tips:)?
<div class="form-group-row club col-lg-10">
<label>Choose Product</label>
<select name="product_id" class="form-control" required>
#foreach($products as $product)
<option value="{{$product->id}}">{{$product-> product}}</option>
#endforeach
</select>
</div>
You could use a Rule to validate the received data like :
use Illuminate\Validation\Rule;
Validator::make($data, [
'product_id' => [
'required',
Rule::in([/*array of products ids here*/]),
],
]);
Take a look at https://laravel.com/docs/5.8/validation#rule-in
You could use exists like :
Validator::make($data, [
'product_id' => [
'required',
'exists:table_name,column_name'
],
]);
you can do select readonly
<select name="product_id" class="form-control" required readonly>
but user can change html by devtools
also you can check it on backend side like this
if ($products->pluck('id')->diff(request()->input('product_id'))->empty()) {
//not changed
}

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

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');
?>

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

How to validate form without entity in controller?

I have a basic form to send an email :
<form action="{{ path('user_send_mail') }}" method="post" enctype="multipart/form-data">
<input name="email_to" type="email" class="form-control" placeholder="To" required>
<input name="email_cc" type="email" class="form-control" placeholder="Cc">
<textarea name="message" id="email_message" class="form-control" placeholder="message" style="height: 120px;" required></textarea>
<input type="file" name="attachment"/>
<p class="help-block">Max. 2MB</p>
<button type="submit" class="btn btn-primary pull-left"><i class="fa fa-envelope"></i> Send the email</button>
</form>
And an action in my controller to validate the data and send the mail but validation doesn't work..
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;
public function sendMailToUserAction(Request $request)
{
$form = $this->createFormBuilder(null)
->add('email_to', 'email', array(
'required' => true,
'constraints' => new Email()
))
->add('email_cc', 'email', array(
'required' => false,
'constraints' => new Email()
))
->add('message', 'textarea', array(
'required' => true,
'constraints' => new NotBlank()
))
->add('attachment', 'file', array(
'required' => false,
'constraints' => new File()
))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
var_dump($data);exit;
} else {
var_dump("error");exit;
}
}
When I submit the form, I got always "error", so validation doesn't work but I don't know why... I have read a lot of topics about this but I get stuck..
EDIT : If I print form error using $form->getErrorsAsString() instead of var_dump("error");exit;, I got this :
string(97) "email_to: No errors email_cc: No errors message: No errors attachment: No errors "
please reffer to this: http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class it think you have to pass array with fields name that you want to validate (its like a default values)
p. s. why not using Simple PHP Object for that? Symfony2 forms fields name should contain brakets like (for example): data[email_to] instead of email_to

Place div infront of input element in Zend form

Im working on zend form..My problem is..
I have designed sigin and sign up froms using zend forms.My sample snippet is..
$this->addElement('Text', 'email', array(
'label' => $email,
'required' => true,
'allowEmpty' => false,
'inputType' => 'email',
'placeholder' => 'Hello#gmail.com',
));
<div id="email-element" class="form-element">
<input type="email" name="email" id="email" value="" autofocus="autofocus" placeholder="Hello#gmail.com"></div>
But I need to place a div with name email_icon with class name form_icon infront of input element to place an image..But Im unable to get snippets to place div in zend form elements.Could you please help me for few snippets..o tuts..or some guidance..
When displaying the email input element in your view script, as per Zend Framework 2, you can use below code snippet.
echo "<div id='email_icon_div'>";
echo $this->formRow($form->get('email'));
echo "</div><div class='clr'></div>";
I hope this helps.

Categories