There is a form. The submit button does not apply to ActiveForm with id = "modal-btn-register-request". In JQuery, by clicking on this button I call $("#modal-btn-register-request").submit() and the form has been validated or not sent to the action. How can I validate before clicking the button. It's all about the button, if you insert the standard Html::submitButton, if there are errors in the form, the data is not sent
rules in model
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
[['password','password_confirm'], 'required'],
];
}
form in view
<?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up']); ?>
<?php echo $form->field($registerForm, 'email')->textInput(['placeholder' => 'Input login', 'class' => 'modal-login__input inp-main']); ?>
<?php echo $form->field($registerForm, 'password')->passwordInput(['placeholder' => 'Input password', 'class' => 'modal-login__input inp-main']) ?>
<?php echo $form->field($registerForm, 'password_confirm')->passwordInput(['placeholder' => 'Confirm the password','class' => 'modal-login__input inp-main']) ?>
<?php \yii\widgets\ActiveForm::end(); ?>
<div class="modal-login__form-btns-cont clearfix">
<div class="modal-login__form-btn-wp modal-login__form-submit-cont text-md-right float-md-right">
<a class="modal-login__submit-btn" id="modal-btn-register-request" href="">Come in</a>
</div>
</div>
jQuery code
$("#modal-btn-register-request").click(function() {
$("#w3").submit();
});
if there is an incorrect field, do not send the form and vice versa?
or how you can send the form when clicking on an element that does not belong to ActiveForm and take into account the validation
Use event.preventDefault() and the yiiActiveForm object:
$("#modal-btn-register-request").click(function(event) {
event.preventDefault();
jQuery('#w3').yiiActiveForm().submit();
});
try this
<?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up']); ?>
<?php echo $form->field($registerForm, 'email')->textInput(['placeholder' => 'Input login', 'class' => 'modal-login__input inp-main']); ?>
<?php echo $form->field($registerForm, 'password')->passwordInput(['placeholder' => 'Input password', 'class' => 'modal-login__input inp-main']) ?>
<?php echo $form->field($registerForm, 'password_confirm')->passwordInput(['placeholder' => 'Confirm the password','class' => 'modal-login__input inp-main']) ?>
<div class="modal-login__form-btns-cont clearfix">
<div class="modal-login__form-btn-wp modal-login__form-submit-cont text-md-right float-md-right">
<a class="modal-login__submit-btn" id="modal-btn-register-request" href="">Come in</a>
</div>
</div>
<?php \yii\widgets\ActiveForm::end(); ?>
At first glance seems your button in not witnin the actual form.
Edit:
I think for what you need you can go about doing in two ways:
1) use an AJAX validation or
2)Use javascript (or JQuery if you prefer) in your view to process the fields before yo call $("#modal-btn-register-request").submit()
For (1) you can do like so:
Edit your form begin like so <?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up', 'enableAjaxValidation' => true]); ?>
Next add the rule you want to verify ofr example:
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
['email', 'unique'], //<---for example
[['password','password_confirm'], 'required'],
];
}
Now you would need to add to your action (the one that renders the form) an if statement to catch this AJAX call in your controller like so
public function actionSignup(){ //<-- assuming its the signup action
$model = new User();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
return $this->render('signup',[
'model' => $model
]);
}
If you want to validate without even checking in your database then is can be doe strictly with javascript (or JQuery) and option (2) is your choice. In that case check out the question check length of input field?
Hope this helps.
Related
$user
id
name
001
user 1
002
User 2
<ul>
<?php foreach($user as $user( { ?>
<input class="is-selected" type="checkbox" value="<?= $value->user->id ?>" />
<?php } ?>
</ul>
<button type="submit" class="btn is-primary">Send Reminder</button>
I'm using YII2, I'm displaying a list of inactive users. I'm using the checkbox to select the user. I'm going to send an email to the user I tagged.
how can i get id value from that checkbox and send data to controller?
I try to use javascript/jquery but i can't solved yet, i need some help from you guys
The above screenshot and your implementation is like you are talking 2 different things.
You would just be required a Grid View with CheckboxColumn
<?php
use yii\bootstrap\ActiveForm;
use yii\grid\GridView;
use yii\helpers\Html;
$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'id' => 'user_form',
'options' => ['class' => 'lfp-listing']
]);
echo Html::submitButton('Send Reminder', ['class' => 'btn is-primary', 'name' => 'action', 'value' => 'send_reminder']);
echo GridView::widget([
'dataProvider' => $dataprovider,
'columns' => [
'id',
'name',
'email',
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' =>
function ($model) {
return ['value' => $model->id, 'class' => '', 'id' => 'checkbox'];
}
],
]
]);
ActiveForm::end();
Considering your Action is actionIndex()
public function actionIndex()
{
if (isset($_REQUEST['action']) && isset($_REQUEST['selection']) && 'send_reminder' == $_REQUEST['action'] ) {
foreach ($_REQUEST['selection'] as $userIds) {
//write down the email code here....
}
}
Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.
I have tried this
1. the select2 widget
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
echo $form->field($model, 'unitid')->widget(Select2::classname(), [
'data' => ArrayHelper::map($model2,'unitid','unitname'),
'language' => 'de',
'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?php ActiveForm::end(); ?>
The javascript code to save data on form submit which is on the view:
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
console.log(\$form.serialize());
$.post(
\$form.attr("action"),
\$form.serialize()
)
.done(function(result) {
console.log("Succesifully saved" + result);
}).fail(function(err)
{
console.log("failed to save" + err);
});
return false;
});
JS;
$this->registerJs($script);
?>
This generates this output on the console(for the serialized form output
_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9
the output is always passed as a string that is after trying
echo json_encode($model->unitid);
On the controller it returns a string instead of an integer
that is
["5"]
How can i convert ($model->unitid) to integer for the post params
Just use
$model->unitid = (int) $model->unitid;
Thats all.
i have a gridview of checkin model with checkbox action column
and on the same view i have form of model message with 2 field message and fileinput but i want to send one more data on the submit button click of message model form which is the keys of checkbox.
How can i so that?
it can be done only via javascript or there is some other technique as well?
here is my grid and view code
<div class="row">
<p>
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<div class="form-group col-xs-3 col-lg-3">
<?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group col-xs-3 col-lg-3">
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-danger','id'=>'sendMessage']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</p>
</div>
<div class="checkin-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?php Pjax::begin(['id' => 'checkin-grid', 'timeout' => false]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showOnEmpty'=>true,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
],
[
'attribute' => 'user_id',
'label' => 'Email',
'value' => 'users.email',
],
'user_type',
],
]);
?>
<?php Pjax::end(); ?>
And here is my checkin/index code where i can access the message and fileinput but i want list of keys as well...
So user must check at least one row before sending message
public function actionIndex()
{
$model = new Message();
$searchModel = new CheckinSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
You can extend your Message model adding the fields you need
class Message extends \yii\db\ActiveRecord
{
public $yourField;
public static function tableName()
{
...
}
this way in your model you have one more field not mapped to database and yon can use for your need....
When you submit your value, the submit related action you shuold manage the models like this way
$models = $dataProvider->getModels();
if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
...... your code for models managemnt
}
F
I have the below cake php form in my view:
<?php $form_id = 'message_form ' + $profile_id ?>
<?php echo $this->Form->create('Post', array('id' => $form_id, 'url' => array('app' => true, 'controller' => 'messages', 'action' => 'new', $profile_id))); ?>
<?php echo $this->Form->input('text', array('type' => 'textarea', 'class' => 'form-control', 'label' => false, 'data-validate' => 'not-empty', 'name' => 'data[Message][content]', 'placeholder' => 'Reply...')); ?>
<?php echo $this->Form->input('hidden', array('type' => 'hidden', 'class' => 'form-control', 'label' => false, 'name' => 'data[Message][parent_id]', 'value' => 1)); ?>
<div class="message-reply-options">
<i class="fa fa-camera"></i>
<i class="fa fa-paperclip"></i>
<i class="fa fa-trash"></i>
<span class="pull-right">
<?php echo $this->Form->submit('Send', array('class' => 'form-control')); ?>
</span>
</div>
<?php echo $this->Form->end(); ?>
This works fine, however I need to be able to change the hidden fields value via javascript depending on something the user does else where on the page.
Below is my current javascript I am using for this, however it does not change the value (but gives no error either).
var newestmessage = response.ChildMessage[response.ChildMessage.length-1];
var parentid = newestmessage.parent_message_id;
document.getElementsByName('data[Message][parent_id]').value = $parentid;
This would have probably been a comment, but since I don't have enough reputation...
I guess you are trying to change/assign the value to hidden field on a particular, action.
I just assume a click event.
Jquery required
$('.classNameOfClickableObjt').clilck(function(){
$('input[name="data[Message][parent_id]"]').val(parentid);
/*Another alternative, you might assign attribute, like
$('input[name="data[Message][parent_id]"]').attr('value', parentid); */
})
You can try jquery and ajax functionally to check the value of hidden input box.
Form rendered using ajax:
<?php $form = ActiveForm::begin(['id' => 'que',
'enableClientValidation' => true
]); ?>
<?php echo $form->field($model, 'fk_subject')
->dropDownList(ArrayHelper::map($subjects, 'id_subject', 'name'), [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'ng-model' => 'que.fk_subject',
'prompt' => 'Select subject',
'ng-change' => 'fillTopic(que);'
]); ?>
<?php echo $form->field($model, 'fk_topic')
->dropDownList([], [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'ng-model' => 'que.fk_topic',
'prompt' => 'Select topic',
'ng-change' => 'openAddTopic(que);',
'ng-options' => 'topic.id_subject as topic.name for topic in topics',
]); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]); ?>
<?php echo Html::submitButton('Save',
['class' => 'btn btn-primary',
'name' => 'Save']) ?>
<?php ActiveForm::end(); ?>
I loaded the above form using ajax in yii2 and problem is client side validation is not working with it. If I load the form content on window load it works fine.
OK I find the solution, I will have to use renderAjax to get the form html or will have to add beginpage and beginend function if I use renderPartial
<?php $this->beginPage(); ?>
<?php $this->beginBody(); ?>
// Form and content redenered using ajax
<?php $this->endBody(); ?>
<?php $this->endPage(); ?>
so that yii can add client validation script with the rendered content
make sure you use renderAjax() method in your controller to load this form via ajax, this way It's needed scripts will register when it loads.
other than that you need to assign a unique ID to your form to prevent possible conflicts when this form is loaded in other views.