I have been searching for the solution for the past few days but i could not get the correct solution include posting it to stackoverflow before Submitting Button Value to Controller but fail to post the value, but i decided to submit it again because the problem has changed since i already know the error.
I want to post multiple submit button to controller in yii2, at first i can get the submitbutton value from $_POST['chosen'] in controller if the code looks like (below):
<?php $form =ActiveForm::begin() ?>
<hr>
<div class="row">
<div style="float:left" >
<?= Html::submitButton('Add Row', [ 'name' => 'chosen', 'value' => 'addmore', 'class' => 'btn btn-info']) ?>
</div>
<div style="float:right" >
<?= Html::submitButton('Next Page', ['class' => 'btn btn-primary', 'name' => 'chosen', 'value' => 'nextpage']) ?>
</div>
</div>
<?php ActiveForm::end()?>
but when i add my function to generate a div, i could not get the $_POST['chosen'] anymore, but i still can get the $model object in controller. the function (addRelationForm) is used to generate div object dynamically so i can submit undertermined-size of array to the controlleer. i could add dynamically the div by pressing add row button.
<?php
use kartik\widgets\RangeInput;
use yii\app\clientScript;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
use frontend\models\relation;
$this->registerJsFile('http://code.jquery.com/jquery-2.1.4.min.js');
function addRelationForm($form, $item, $i){
return '<div class="col-md-12" id=\'r_'.($i).'\'>
<div class="form-group col-md-12">
<label> Friend ' . ($i + 1) . '</label>'.
$form->field($item, "[$i]user_friend_id") .
'<label> Closeness to you </label>
<div class="form-inline"> ' .
$form->field($item, "[$i]closeness")->widget(RangeInput::classname(), [
'options' => ['placeholder' => 'Rate (1 - 5)...'],
'html5Options' => [
'min' => 1, 'max' => 5,
'width' => '75%',
'addon' => ['append' => ['content' => '<i class="glyphicon glyphicon-star"></i>']]
]])->label(false).
'</div> '.
'<div class="form-inline" >
I know this person as a friend for approximately (in year) '.
$form->field($item, "[$i]known_for")->textInput(["type" => "number", "placeholder" => '(in year)'])->label(false).
'</div></div></div>';
}
?>
<h1>Friendship Survey</h1>
<p> Introverted the space below, list up to ten of your closest friends that are currently in Econs/ Math and Econs; a minimum of 5 is compulsory. *Please select their full names from the dropdown list provided. Also, please select on the scale how close you are to each friend. 1Note the incentives for this section </p>
<?php $form =ActiveForm::begin() ?>
<?php foreach ($items as $i => $item) {
echo addRelationForm($form ,$item, $i);
}
?>
<hr>
<div class="row">
<div style="float:left" >
<?= Html::submitButton('Add Row', [ 'name' => 'chosen', 'value' => 'addmore', 'class' => 'btn btn-info']) ?>
</div>
<div style="float:right" >
<?= Html::submitButton('Next Page', ['class' => 'btn btn-primary', 'name' => 'chosen', 'value' => 'nextpage']) ?>
</div>
</div>
<?php ActiveForm::end()?>
<?php
$this->registerJsFile('/advanced/frontend/web/js/partone-two.js');
?>
my controller looks like this:
public function actionTwo(){
if(\Yii::$app->user->isGuest){
$this->goHome();
}
$models = [];
var_dump($_POST);
Yii::trace("esting" .empty($_POST['chosen']));
for($i = 0; $i < 5 ; $i++){
$models[$i] = new RelationForm();
}
if(!empty($_POST['add'])){
if('addmore' == $_POST['add']){
Model::loadMultiple($models, Yii::$app->request->post('items'));
$model = new RelationForm();
array_push($models, $model);
return $this->render('two', ['items' => $models]);
}
}
if (Model::loadMultiple($models, Yii::$app->request->post()) )
{
$count = 0;
for($i = 0 ; $i < count($models); $i++){
if(!$models[$i]->validate()){
if($models[$i]->hasErrors()){
Yii::trace( Html::errorSummary($models[$i] ));
}
return $this->render('two', ['items' => $models]);
}
}
for($i = 0 ; $i < count($models); $i++){
if(!$models[$i]->store()){
return $this->render('two', ['items' => $models]);
}
}
Yii::$app->session->setFlash('success', "Processed {$count} records successfully.");
return $this->redirect('three', ['items' => $models]);// redirect to your next desired page
}
else {
Yii::trace("Render");
return $this->render('two', array('items' => $models));
}
return null;
}
Instead of <?= Html::submitButton('Add Row', [ 'name' => 'chosen', 'value' => 'addmore', 'class' => 'btn btn-info']) ?> which create <button type="submit" ... >Submit</button> use submitInput($label = 'Submit', $options = []) which create <input type="submit" name="chosen" value="addmore" class="btn btn-info">
Then in controller: $var = \Yii::$app->request->post('chosen');
you can check if variable is empty: empty($var) (different names for each submitInput with no values) or isset && $var === 'your_value' (same name, but diff. value in submitInput - not tested if it`s working)
Related
I have data that is being passed through an POST method. However when I try to get some data out of it and set it to a session variable, there is no data in it yet when I print_R($_POST) I see there is Data in it.
This is What I'm getting when I print_r() the POST data.
Array (
[_csrf] => nXRvIHfHWeao64YBdwcdFJa3fz-KShIyAuHDNtKQqhCkDRdwErUqkOrSyHQQamtR5cBHWc57QUNq16hflaftKQ==
[LoginForm] => Array (
[compayname] =>Termite Soup
[username] => Jim.Bot
[password] => 123456
[url] =>
)
[login-button] =>
)
This is what I've tried.
This is the form where form is being filled.
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-10\">{input}
</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-3 control-label'],
],
]);
?>
<?php echo $form->field($model,
'compayname')>dropDownList(['GF_TB_TNT' => 'GF-TNT',
'Chicken Soup' =>'Dog Soup',
'Termite Soup' =>'Termite Soup',
],
['prompt'=>'Select Company']); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'url')->hiddenInput()->label(''); ?>
<div class="row">
<div class="btn-group">
<!-- <div class="col-md-2">
</div> -->
<div class="col-md-6">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary pull-left', 'name' => 'login-button','style'=>'font-size: 15px;']) ?>
</div>
Getting the data and setting it to a Session Variable
if (Yii::$app->request->post()) {
$companyname = Yii::$app->request->post('compayname');
}
I want to set the companyname in the POST to a session Variable
What you can do is
foreach (Yii::$app->request->post('LoginForm') as $field) {
// some logic
}
Also I see a mistake in compayname. A "n" is missing in the word. But you can access it's value by Yii::$app->request->post('LoginForm')['compayname'];
You can shortly get this.
$arr = [];
foreach ($_POST as $param) {
if (is_array($param)) {
foreach ($param as $name) {
if ($name == 'LoginForm') {
array_push($arr, $name);
}
}
} else {
}
}
And you can figure out how the data is structured using var_dump
var_dump($arr);
I have two activeform in my view and one of them use pjax. And both of them requires second click to submit. I don't know what I am doing wrong. I search this problem in internet, but meet other cases of second click
<?php Pjax::begin(['id' => 'workers', "timeout" => 50000], ["options" => ["timeout" => 5000]]);?>
<?php
echo $this->render('_show', [
"model" => $searchModel,
"filials" => $filials,
"workers" => $workers,
"posts" => $posts,
]);
echo $this->render('_handle_form');
?>
<div class="row js-loader">
<div class="col-lg-12 col-md-12">
<div class="table-responsive">
<?=GridView::widget([
'dataProvider' => $dataProvider,
'emptyText' => 'Нет результатов',
'tableOptions' => ['class' => 'table table-hover table-claim table-claimadm', 'style' => 'font-weight:600;'],
'rowOptions' => ['class'=>'row-without-border row-open'],
'layout' => "{items}{pager}",
'columns' => [
[
...
]
]);?>
</div>
</div>
</div>
<?php Pjax::end();?>
<script>
window.onload = function () {
$(document).on('pjax:send', function (event) {
tbody = $('#' + event.target.id).find(".js-loader");
if (tbody.length != 0) {
tbody_height = tbody.height();
tbody.html('<div class="block-loader" style="width:100%"></div>');
}
});
$('#submit_with_answer').click(function() {
if ($.trim($('#text-claim').val()).length > 0)
{
$('#complaint_feedback').submit();
}
else
{
$('#textarea-group').addClass('has-error');
$('#answer_error').html('Заполните поле «Добавить текст ответа»');
}
});
};
</script>
The "_show" view is:
<?php $form = ActiveForm::begin([
'id' => 'complaints',
'action' => Url::to(['complaints/show']),
'method' => 'GET',
'options' =>
[
'class' => 'form-respons form-claimadm',
'data-pjax' => 1,
],
]);
active fields....
<div class="form-btns col-md-2 col-sm-6 col-xs-12">
<?= Html::submitButton('Применить', ['class' => 'btn btn-primary','style'=>"float:right;"]) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
and _handle_form is:
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>
<?php
$form = ActiveForm::begin([
'id' => 'complaint_feedback',
'action' => Url::to(['complaints/handle-complaint']),
'method' => 'POST',
'options' => ['class' => 'form-respons form-claim-feedback','style'=>'display:none;'],
]);
?>
<div id="textarea-group" class="form-group">
<label for="text-claim" class="hidden-xs">Добавить текст ответа</label>
<textarea class="form-control" id="text-claim" rows="3" name="complaint_answer" placeholder="Добавить текст ответа"></textarea>
<div id="answer_error" class="help-block"></div>
<input id="complaint_id" name="complaint_id" type="hidden" value="">
</div>
<div class="clearfix form-btns">
<button type="button" onclick="$('#complaint_feedback').submit();" class="btn btn-link">Обработать без ответа</button>
<button id="submit_with_answer" type="button" class="btn btn-primary">Отправить</button>
</div>
<?php ActiveForm::end(); ?>
<a id="hide_handle_form" style="display: none;" onclick="$('#complaint_feedback').hide(); $('.handle_button').removeClass('disabled'); $(this).hide();$('tr[data-key='+$('#complaint_id').val()+']').removeClass('row-open');" class="btn btn-link btn-show-hide">Свернуть
</a>
if I comment lines with pjax, everything works correctly. How can I fix this trouble?
When I submit this form all things are well n good but I want the controller function not shows in url. I want all things are done in same page. Still the url show
localhost/Naveen/CodeIgniter/welcome/insertform
but I don't want the form_open('') show's in url so how it is possible?
controller welcome.php
public function insertform()
{
if (isset($_POST['mysmt']))
{
$this->form_validation->set_rules('fname', 'Name', 'required');
$this->form_validation->set_rules('femail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('fmobile', 'Mobile', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_view');
}
else
{
$_POST['fname'];
$_POST['femail'];
$_POST['fmobile'];
if($this->test_model->insert('user_accounts',array('',$_POST['fname'],$_POST['femail'],$_POST['fmobile'])))
{
$success['success']="Thanks For Join Us";
$this->load->view('welcome_view',$success);
}
}
}
else
{
$this->load->view('welcome_view');
}
}
view welcome_view.php
<?php echo form_open('welcome/insertform'); // ?>
<div class="form-group">
<?php
if(isset($success))
{?>
<input type="button" class="form-control btn-success" value="<?php echo $success; ?>">
<?php }
else
{
echo "";
}?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Name <?php echo form_error('fname'); ?></label>
<?php
$entername = array(
'name' => 'fname',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Name',
'class' => 'form-control',
);
echo form_input($entername); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Email <?php echo form_error('femail'); ?></label>
<?php
$enteremail = array(
'name' => 'femail',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Email',
'class' => 'form-control',
);
echo form_input($enteremail); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Mobile <?php echo form_error('fmobile'); ?></label>
<?php
$entermobile = array(
'name' => 'fmobile',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Mobile',
'class' => 'form-control',
);
echo form_input($entermobile); ?>
</div>
<div class="form-group">
<?php
$f_formsmt = array(
'name' => 'mysmt',
'value' => 'Submit Form',
'class' => 'form-control btn btn-success',
);
echo form_submit($f_formsmt); ?>
</div>
<?php echo form_close(); ?>
You handle it through applications/config/routes.php
consider you url: localhost/Naveen/CodeIgniter/welcome/insertform
$route['add'] = 'welcome/insertform';
now you can use localhost/Naveen/CodeIgniter/add
You can change whatever the string you want for any controller/function using routes.
Hope you understood :)
You need to add the url in route and add link to your link href
In route.php add:
$route['custom_url'] = 'controller/method';
I used Header("location:../{whatever-filename}")
Then gave that "whatever-filename" the proper routing in the config/routes.php.
Routing without using the redirect function would load the appropriate page but the url would still show the controller and method you're using.
Hope it helps
user data has been lost if there is a validation error and error validation messages are also not showing on front end.
Here is my controller
public function add() {
$this->theme = 'Front';
if (!empty($this->logged_in)) {
return $this->redirect(Router::url('/', true) . $this->logged_in['Role']['alias']);
}
$this->set('title_for_layout', __('Create An Account'));
// hanlde post data
if ($this->request->is("post")) {
if (!empty($this->request->data)) {
$this->User->set($this->request->data);
if (!$this->User->validates()) {
$this->User->validationErrors;
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}
}
// die('sdsddsaf');
// if (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 2) {
unset($this->request->data['User']['specialization_id']);
$randomSt = $this->Custom->randomString(28);
$this->request->data['User']['activation_key'] = $randomSt;
// }
if ($this->User->save($this->request->data)) {
$user = $this->request->data;
if (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3) {
$this->Session->setFlash(__('Thank you for registering with us. Please check your email inbox/junk.'), 'message', array('class' => 'successs'));
// set mail variable
$to = $this->request->data['User']['email'];
$fname = $this->request->data['User']['first_name'];
$lname = $this->request->data['User']['last_name'];
//$activelink = SITEURL . 'activate?code=' . $randomSt;
$siteurl = Configure::read('Site.title');
$replace = array($fname, $lname, $siteurl);
// Send mail on Registration
$this->sendMail($to, 'RegisterDoctor', $replace);
} else {
$this->Session->setFlash(__('Thank you for registering with us. Please check your e-mail inbox/junk as your e-mail confirmation has just been sent.'), 'message', array('class' => 'successs'));
$activelink = Router::url('/', true) . 'activate/' . $this->User->id . '/' . $randomSt;
// set mail variable
$to = $this->request->data['User']['email'];
$fname = $this->request->data['User']['first_name'];
$lname = $this->request->data['User']['last_name'];
//$activelink = SITEURL . 'activate?code=' . $randomSt;
$siteurl = Configure::read('Site.title');
$replace = array($fname, $lname, $activelink, $siteurl);
// Send mail on Registration
$this->sendMail($to, 'Register', $replace);
}
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$reponse = array();
$roles = $this->User->rolesSignup();
$genders = $this->User->genders();
$specializations = $this->User->specializations();
$this->set(compact('roles', 'genders', 'specializations'));
}
And below is my view
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array('div' => false, 'label' => false, 'fieldset' => false),
'class' => 'ac p10',
// 'data-togglesd' => "validator",
'role' => 'form',
'type' => 'file',
'onSubmit' => 'return checksubmitPass()'
)
);
?>
<div class="ph10">
<div class="btn-group radio_group w100" data-toggle="buttons">
<label class="btn btn-primary col-md-6 <?php echo (empty($this->request->data['User']['role_id']) || #$this->request->data['User']['role_id'] == 2 ) ? 'active' : ""; ?> btn_roles">
<input type="radio" name="data[User][role_id]" value="2" class="role_id" <?php echo (empty($this->request->data['User']['role_id']) || #$this->request->data['User']['role_id'] == 2 ) ? 'checked="checked"' : ""; ?>> User
</label>
<label class="btn btn-primary col-md-6 <?php echo (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3 ) ? 'active' : ""; ?> btn_roles">
<input type="radio" name="data[User][role_id]" value="3" class="role_id" <?php echo (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3 ) ? 'checked="checked"' : ""; ?>> Doctor
</label>
</div>
</div>
<div class="form-group p10 cr">
<div class="cm upload_img round"><img src="<?php echo $this->webroot; ?>img/user_avtar(upload).png" class="user_pic_upload">
<?php echo $this->Form->file('image', array('class' => 'user_img', 'data-fv-file' => 'true', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-field' => 'data[User][image]')); ?>
</div>
<small style="display: none;" class="help-block" data-fv-validator="notEmpty" data-fv-for="data[User][image]" data-fv-result="VALID">This field cannot be left blank.</small>
</div>
<div class="form-group mt10 cr">
<div class="clearfix">
<div class="col-lg-6 first_name"><?php echo $this->Form->input('first_name', array('class' => 'form-control', 'placeholder' => 'First Name', 'data-stripe' => "alphabet", 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-regexp' => 'true', 'data-fv-regexp-regexp' => "^[a-zA-Z\s]+$", 'data-fv-regexp-message' => "The first name can consist of alphabetical characters and spaces only")); ?></div>
<div class="col-lg-6 last_name"><?php echo $this->Form->input('last_name', array('class' => 'form-control', 'placeholder' => 'Last Name', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-regexp' => 'true', 'data-fv-regexp-regexp' => "^[a-zA-Z\s]+$", 'data-fv-regexp-message' => "The last name can consist of alphabetical characters and spaces only", 'required')); ?></div>
</div>
</div>
<div class="form-group ph10 mt10">
<?php echo $this->Form->input('email', array('class' => "form-control", 'placeholder' => 'Email Address', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-emailaddress-message' => __('validemail'))); ?>
</div>
<div class="form-group mt10 ph10 row_org">
<div id="dropdown-menu">
<?php echo $this->Form->input('specialization_id', array('empty' => 'Select Speciallization', 'class' => 'selectpicker form-control', 'data-fv-notempty-message' => __('notEmpty'), 'required')); ?>
</div>
</div>
<div class="form-group ph10 mt10">
<?php echo $this->Form->input('password', array('class' => "form-control", 'placeholder' => 'Password', 'type' => 'password', 'data-fv-notempty-message' => __('notEmpty'))); ?>
</div>
<span id="result"></span>
<div class="form-group ph10 mt10">
<?php
echo $this->Form->input('verify_password', array(
'class' => "form-control",
'type' => 'password',
'placeholder' => 'Confirm Password',
'data-fv-notempty-message' => __('notEmpty'),
'data-fv-identical' => "true",
'data-fv-identical-field' => "data[User][password]",
'data-fv-identical-message' => __('passwordNotMatch')
)
);
?>
</div>
<div class="form-group mt10">
<div class="clearfix">
<div class="col-lg-6 mobile-custom">
<?php echo $this->Form->input('mobile', array('class' => 'form-control phonenumber', 'placeholder' => 'Mobile number', 'maxlength' => '14', 'minlength' => '10', 'data-fv-stringlength-message' => 'The mobile number must be 10 to 14 characters long', 'data-fv-numeric-message' => __('Please enter valid mobile numbers'), 'data-fv-numeric' => "true")); ?>
</div>
<div class="col-lg-6" id="dropdown-menu">
<?php //echo $this->Form->input('gender', array('class' => 'form-control selectpicker', 'data-fv-notempty-message' => __('notEmpty'),'empty' => 'I Am','error' => false, 'required')); ?>
<select id="UserGender" title="I Am" required="required" data-fv-notempty-message="This field cannot be left blank." class="form-control" name="data[User][gender]" style="display: none;" data-fv-field="data[User][gender]">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>
</div>
</div>
<div class="form-group ph10 mt10"><button type="submit" class="btn btn-info w100">Sign Up</button></div>
<p class="mt10"><small>By Signing up you are agree with <br>Terms & Conditions and Privacy Policy</small></p>
<p class="mt10 signup-text"><strong>Already on HealthDrop?</strong></p>
<div class="ph10">
<?php echo $this->Html->link('Sign In', Router::url('/', true) . 'login', array('class' => 'btn deep btn-primary w100')); ?>
</div>
<?php echo $this->Form->end(); ?>
it was working before bu suddenly stop to showing error and start loosing data.
I have check with this question but it is pointing out at field names in input and I have correct ones.
Any help appreciate.
You lost your data because there is redirect to sign-up url.
$this->redirect(Router::url('/', true) . 'sign-up/');
And after redirection
$this->request->data
is empty because you perform new request, the same with errors
According to your code there are two mistakes I found
you are using ! for validating the validations
Save method itself validate the data so no need to validate again.
So your code should be look like
if ($this->User->save($this->request->data)) {
//your code
}else{
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}
and validation error messages are automatically assign to view, no need to worry about them
This function was build manually, but we want to know if there is a way, using Yii 2, of getting the model JS validation function automatically. We did so just to test.
Question:
How should we do this, without manually build this for each submodel form field?
JavaScript to add dynamic submodels' fields:
var horsePreferredFoodValidateFunction = function(attribute, value, messages) {
yii.validation.required(value, messages, {"message": "mandatory field"});
};
$(window).load(function() {
$('.container').on('click', '#add-horse-preferred-food', function() {
var horsePreferredFoodsCount = (parseInt($('#horsePreferredFoodsCount').val())) + 1;
$.post(
'/horse/add-horse-preferred-food',
{index : horsePreferredFoodsCount},
function(data) {
$('#horsePreferredFoodsCount').val(horsePreferredFoodsCount);
$("#horse-preferred-food-list").append(data);
var horseForm = $('#horse-form');
console.log(horseForm.data('yiiActiveForm'));
How should we do the attributes adding if we have a submodel with many fields?
$(horseForm).yiiActiveForm('add', {
id: 'horsepreferredfood-' + horsePreferredFoodsCount + '-name',
input: '#horsepreferredfood-' + horsePreferredFoodsCount + '-name',
name: 'name',//'[' + horsePreferredFoodsCount + '][name]',
container: '.field-horsepreferredfood-' + horsePreferredFoodsCount + '-name',
validate: horsePreferredFoodValidateFunction,
error: '.help-block.help-block-error'
});
console.log(horseForm.data('yiiActiveForm'));
}
);
});
});
function removeHorsePreferredFood(id) {
$('#div-horse-preferred-food-' + id).remove();
}
Aditional info:
HorsePreferredFood's rules:
public function rules()
{
return [
[['name', 'horse_id'], 'required'],
[['horse_id'], 'integer'],
[['name'], 'string', 'max' => 255]
];
}
The main form (horse/_form.php):
<div class="horse-form">
<?php
$form = ActiveForm::begin(
[
'id' => 'horse-form',
'action' => '/horse/' . (($horse->isNewRecord) ? 'create' : 'update/' . $horse->id),
'errorCssClass' => 'errorMessage',
]
);
?>
<?= $form->field($horse, 'name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($horse, 'age')->textInput() ?>
<!-- HORSE PREFERRED FOODS -->
<fieldset class="fieldset">
<legend>Comidas Preferidas:</legend>
<div id ="horse-preferred-food-list">
<?php
$horsePreferredFoodsCount = count($horsePreferredFoods);
foreach ($horsePreferredFoods as $horsePreferredFoodIndex => $horsePreferredFood) {
$this->renderPartial(
'/horsePreferredFood/_form',
array(
'index' => $horsePreferredFoodIndex,
'horsePreferredFood' => $horsePreferredFood,
'form' => $form,
)
);
echo $form->field($horsePreferredFood, 'name')->textInput(['maxLength' => 255]);
}
?>
</div>
<div class="form-group">
<?php
echo \yii\bootstrap\Button::widget(
[
'label' => 'Adicionar Comida Preferida',
'options' => [
'id' => 'add-horse-preferred-food',
'class' => 'btn-lg',
],
]
);
?>
</div>
</fieldset>
<div class="form-group">
<?= Html::submitButton(
$horse->isNewRecord ?
'Criar' : 'Alterar',
[
'class' => $horse->isNewRecord ?
'btn btn-success' : 'btn btn-primary'
]
); ?>
</div>
<?php
ActiveForm::end();
echo Html::hiddenInput(
'horsePreferredFoodsCount',
$horsePreferredFoodsCount,
[
'id' => 'horsePreferredFoodsCount',
]
);
?>
</div>
The submodel form (horsePreferredFood/_form.php):
<?php
if (isset($isAjaxCall) && ($isAjaxCall)) {
$horsePreferredFood = new \app\models\HorsePreferredFood();
} else {
$isAjaxCall = false;
}
if (! isset($form)) {
$form = \yii\bootstrap\ActiveForm::begin(
[
'id' => 'horse-form',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
]
);
}
?>
<div class="form" id="div-horse-preferred-food-<?php echo $index; ?>">
<fieldset class="fieldset">
<div class="form-group">
<?php
echo \yii\helpers\Html::activeHiddenInput($horsePreferredFood, "[$index]id");
echo $form->field($horsePreferredFood, "[$index]name")->textInput(['maxlength' => 255]);
?>
</div>
</fieldset>
<div class="form-group">
<?php
echo \yii\bootstrap\Button::widget(
[
'label' => 'Remover Comida Preferida',
'options' => [
'id' => "btn-remove-horse-preferred-food-$index",
'class' => 'btn-lg',
'onClick' => "removeHorsePreferredFood($index);",
],
]
);
?>
</div>
</div>
In HorseController, the action invoked via AJAX to return the submodel fields:
public function actionAddHorsePreferredFood() {
$index = $_POST['index'];
$partialView = "/horsePreferredFood/_form";
return $this->renderPartial(
$partialView,
[
'index' => $index,
'isAjaxCall' => true,
]
);
}