Yii2: Disable ActiveForm Ajax Validation on field blur - yii2

How disable Yii automatically(validation onblur) ajax validation?
I want to validate only after pressing the submit button.

You want to use the enableAjaxValidation to validate your form and at the same time do not want to trigger the ajax validation on every blur of the field once you type into it. You only want to trigger the validation on Submitting the form.
To do this with ajaxValidation your main options to be used are
validateOnBlur that is the ActiveForm option you need to turn it off by passing false as value to the option.
validateOnChange either in the ActiveForm options or you can specify it under the fieldConfig option of the ActiveForm to apply on all fields. You need to turn it off by passing false as a value.
The validateOnBlur will disable the validation if there is no value typed into the field, if you type in some text and then blur out it will trigger validation and to disable that we need to use the validateOnChange.
Your form configurations should look like below
$form = ActiveForm::begin ( [
'id' => 'my-form' ,
'validateOnBlur'=>false,
'enableAjaxValidation'=>true,
'validateOnChange'=>false,
] );

There is an attribute called $validateOnBlur which reads:
Whether to perform validation when an input field loses focus. If
yii\widgets\ActiveField::$validateOnBlur is set, its value will take
precedence for that input field.
Set it to false since default is true. For example:
$form = ActiveForm::begin([
'validateOnBlur' => false
]);

If you want to disable ajax validation completely, set enableAjaxValidation in your form to false:
$form = ActiveForm::begin([
'enableAjaxValidation' => false
]);
https://www.yiiframework.com/doc/api/2.0/yii-widgets-activeform#$enableAjaxValidation-detail

Related

Google recaptcha validation in yii2 always fails

I use himiklab/yii2-recaptcha-widget. I always get a validation error when I submit the form.
{"captcha":["The verification code is incorrect."]}.
Form:
$form->field($model, 'captcha',['template' => "{input}\n{hint}\n{error}"])->widget(
\himiklab\yii2\recaptcha\ReCaptcha::className(),
[
'siteKey' => <mysitekey>,
'widgetOptions' => ['id'=>'recaptcha1']
])
Controller:
if(isset($_POST['Contact'])){
if ($model->load(Yii::$app->request->post()) && $model->save()) {
What am I doing wrong?
The problem is that Yii always run validation twice, on validation() method and during the save executes again the validation, this cause that the first validation is successful however the second returns an error.
So, for the second case you will need to save without running the validations, which save(false).
The second chance might be to unhook the validation of the captcha just before the safe() method.

Symfony 2 / Doctrine Not Saving Any Zeros in varchar field

UPDATE
As asked for,
$NewUser = new Users();
$Form = $this->createForm(new UserType(), $NewUser, [])
->add('save', 'submit', ['label' => 'Save',
'attr' => ['class' => 'SaveButton ftLeft'],
]);
$Form->handleRequest($request);
if ($Form->isValid()) {
/*
Sometimes add more data to the entity.....
*/
$em = $this->getDoctrine()->getManager();
$em->persist( $NewUser );
$em->flush();
}
$FormRender = $Form->createView();
return $this->render('xxxxBundle:Users/add.html.twig',
['AddUser' => $FormRender]);
Sometimes I will add extra to the entity, on fields being set within the php code, e.g. account sign up date, but in most cases just save the entity with the form data.
Very simple issue, I have a new (ish) system and have notice that when trying to save zeros, for anything, phone number inputs, it does not save any zeros?
I am using YMAL files to control my doctrine ORM, here is how I have set it up within my User table,
mobileNumber:
type: string
nullable: false
length: 50
options:
fixed: false
column: mobile_number
This does save/make the field has a varchar, and thought nothing about it until I did a random test and saw it was not saving any leading zeros?
I know you can not save leading zeros in a int field type, but this is a varchar. Also when I go into the database, and manually add a zero to that input, its fine, so I take its not the database. Something to do with how I get doctrine to save the data?
If so how do I change that? I have just been saving the data with a standard persist() and flush() commands? Not sure why it would not save the zeros? I was thinking that I had to change the YMAL type to something like phone? I have been over the docs, can not see it.
All help most welcome..
Thanks.
The reason is in your comment:
User form type has the mobile number set to 'number' input.
This value is being casted to int by the Form component. Change the field type to regular string.
If you want to validate value to be only digits, use Validation component

YII2 : Use activeForm and linkPager toghether

I would like to use an activeForm and linkPager together.
I mean in the same view, I have defined an activeform with some fields, an sqldataprovider and the showing of the model result (of sqldataprovider). All is nice when I click on the submit button of the activeform.
Now, I would like to add a linkPager by using :
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
And when I click and one of buttons of linkpager (to change page), the fields of the activeform are not linked, I mean : the datasqlprovider does not filter with these fields...
I think, you need to populate the ActiveForm manually based on the request parameter:
$searchModel = new JobSeekerSearch(); // extended from JobSeeker
$params = Yii::$app->request->queryParams; // this is the query string parameter
if( !empty( $params['JobSeekerSearch'] ) ){
$searchModel->fullName = $params['JobSeekerSearch']['fullName']; // populate your model
}
$dataProvider = $searchModel->search($params); // submit the search parameter to your search model
then make sure to create your ActiveForm based on the model(JobSeekerSearch for this example)

how to change a checkbox to 2 radio buttons. Value doesn't pass back 'true'

My table in the DB contains 2 fields. 'Title' and 'IsBusiness'(which is stored as a bool on wether the record is a business account or not.
When adding a new record on screen the editorFor is used to display a checkbox for 'IsBusiness' which passes back true or false.
#Html.EditorFor(x => x.IsBusiness)
#Html.ValidationMessageFor(x => x.IsBusiness)
I want to change this to 2 radio buttons. 'Product' and 'Business' which passes back false if product is selected and true is business is selected.
So far my code below keeps passing back false. It wont store 'True'...any ideas?
<label>#Html.RadioButtonFor(x => x.IsBusiness, "Business")Business</label>
<label>#Html.RadioButtonFor(x => x.IsBusiness, "Product")Product</label>
Try:
<label>#Html.RadioButtonFor(x => x.IsBusiness, true) Business</label>
<label>#Html.RadioButtonFor(x => x.IsBusiness, false) Product</label>
See also: ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Get value of disabled drop down in asp.net mvc

I have an ASP.NET MVC application. I am having multiple drop-down list in my page (HTML SELECT), I have to disable them, as user goes on selected them one by one. When the user posts it back to the controller, I am getting null as the function (action method) paramters. I searched and found that HTML does not send value of disabled fields in the form data. Replacing disabled attribute with readonly would not work as it would render drop-down working.
I am generating the dropdowns dynamically using javascript as user goes on. So there isn't a single dropdown, but as many as user wants.
Can someone please tell me how should I get the values ?
One possibility is to make the dropdown list disabled="disabled" and include a hidden field with the same name and value which will allow to send this value to the server:
#Html.DropDownListFor(x => x.FooId, Model.Foos, new { disabled = "disabled" })
#Html.HiddenFor(x => x.FooId)
If you have to disabled the dropdown dynamically with javascript then simply assign the currently selected value of the dropdown to the hidden field just after disabling it.
This is the default behavior of disabled controls. I suggest you to add a hidden field and set the value of your DropDownList in this hidden field and work with this.
Something like:
//just to create a interface for the user
#Html.DropDownList("categoryDump", (SeectList)ViewBag.Categories, new { disabled = "disabled" });
// it will be send to the post action
#Html.HiddenFor(x => x.CategoryID)
You could also create your own DropDownListFor overload which accepts a bool disabled parameter and does the heavy lifting for you so your view isn't cluttered with if disablethisfield then ....
Something among these lines could do:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, bool disabled)
{
if (disabled)
return MvcHtmlString.Create(htmlHelper.HiddenFor(expression).ToString() + htmlHelper.DropDownListFor(expression, selectList, new { disabled="disabled" }).ToString());
else
return htmlHelper.DropDownListFor(expression, selectList);
}
There are 6 overloads for DropDownListFor alone so it's a lot of monkeycoding but it pays off in the end imho.
Create a hidden field with a specified Id and set it before disabling the drop-down-list.
In MVC,
#Html.DropDownListFor(x => x.FooId, Model.Foos)
#Html.HiddenFor(x => x.FooId, new { #id = "hdnFooId" })
In JQuery,
function handleDropDownListFooChange(){
// Get the selected value from drop-down-list before disabling it.
var selectedFooId = $('#FooId').val();
$('#FooId').prop("disabled", "disabled");
$("#hdnFooId").val(selectedFooId);
// Load any data the depends on selected FooId using `selectedFooId` variable.
}
The selected value will automatically be binded to Model.FooId.
before submit call $('#FooId').removeAttr('disabled')