I'm using Yii2 for my developments and I'm trying to Add Rows to table using plus button.
I'm able To add new row from that. And i need to append Krajee Select2 to my appending row. is that possible? how Can I Do that?
Following is my code use for append.
$('#main_tbl_body').append(
'<tr class='+row_class+' id="tbl_rw_appent_'+new_count+'">\n\
<td><a onclick ="removeMoreCommentField(this.id)" id="a_link_remove_'+new_count+'"><img id="image_remove_'+new_count+'" src="images/minus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
<td><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">'+' <?php
//echo '<label class="control-label">Part Code</label>';
$data = ArrayHelper::map(Mproduct::find()
// where(['P_model' => $model->relatedToVehicle->V_model])
->all(), 'idProduct', 'P_description');
//$items = DealerHelper::getRemainItems();
echo Select2::widget([
'name' => 'part_description_1',
'data' => $data,
'options' => [
// 'class'=>'textBox mobviewmargin',
'placeholder' => 'Select Product',
// 'multiple' => true
],
'pluginOptions' => [
'closeOnSelect' => true,
'tags' => false,
'multiple' => false,
'allowClear' => false,
],
]);
?>'+'</div></td>\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\
<td></td>\n\ \n\
<td><a onclick ="addMoreCommentField()" id="a_link_add_'+new_count+'"><img id="image_add_'+new_count+'" src="images/plus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
</tr>'
);
Please Help me
Related
I'm doing a nested tab by using bootstrap and so i want to query the post data with specific the term_id itself. please see my code what I'm doing wrong.
I'v get the result just the first one of the term_id but another term_id is not get the result.
I assume in my case the loop just working only one time.
<!-- Nav tabs -->
<ul class="nav nav-tabs" id="myTab-<?php echo $cat->slug?>" role="tablist">
<?php
$args = array('child_of' => $cat->term_id);
$categories = get_categories( $args );
//print_r($categories);
$ix = 1;
foreach($categories as $category) :?>
<li class="nav-item">
<a class="nav-link <?php echo $ix?> <?php if($ix==1){echo "active";}?>" id="tab-<?php echo $category->term_id?>" data-toggle="tab" href="#tab-<?php echo $category->term_id.$ix?>" role="tab" aria-controls="tab-<?php echo $category->term_id.$ix?>" aria-selected="<?php if($ix==1){echo "true";}else{echo "false";}?>"><?php echo $category->name;?></a>
</li>
<?php $ix++; endforeach ?>
</ul>
<div class="tab-content">
<?php
$ix = 1;
foreach($categories as $category) :?>
<div class="tab-pane <?php echo $ix?> <?php if($ix==1){echo "active";}?>" id="tab-<?php echo $category->term_id.$ix?>" role="tabpanel" aria-labelledby="tab-<?php echo $category->term_id.$ix?>">
<?php echo "term_ID: ". $category->term_id?>
<ul class="row child_of_cat">
<?php
$qr = new WP_Query( $args = array(
'post_type' => 'services',
'parent' => 1,
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => -1, // Limit: two products
//'post__not_in' => array( get_the_id() ), // Excluding current product
'tax_query' => array( array(
'taxonomy' => $taxonomy,
'field' => 'term_id', // can be 'term_id', 'slug' or 'name'
'terms' => $category->term_id,
), ),
));
?>
<?php
if ( $qr->have_posts() ):
while( $qr->have_posts() ):
$qr->the_post();
if(get_the_post_thumbnail($qr->post->ID) ==''){
$img = '<img class="img-fluid" src="https://via.placeholder.com/300/ddd/fff.png">';
} else{
$img = get_the_post_thumbnail($qr->post->ID);
}
echo '<li class="col-6 col-sm-3">
<div class="loop-box">';
if (has_term($term = 'best-seller', $taxonomy = 'collection', $post = $qr->post->ID)){
echo '<img class="conner-bage-bg" src="'.get_template_directory_uri().'/img/bage_new.png">';
}
echo ''.$img.'
<a href="'.get_permalink().'"><div class="description">
<p class="woocommerce-loop-product__title">'.$qr->post->post_title.'xx</p>
</div></a>
</div>
</li>';
endwhile;
//wp_reset_postdata();
rewind_posts();
endif; ?>
</ul>
</div><!-- tab-pane -->
<?php $ix++; endforeach ?>
</div>
I have already fix it by using get_posts().
enter link description here
I have two model loaded when i user loads the page but only one of this model will take information base on user's preference, but my problem is when the user submit the form the two model are submitted and i get an error because the other model needs to take information before it can proceed too, i want to know how i can load just one of the model and ignore the other when base on which of the form the user filled
Contoller
public function actionSignup($mode)
{
//if($mode === 'personalAccount'){
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
// }else{
$model_business = new SignupFormbusiness();
if ($model_business->load(Yii::$app->request->post())) {
if ($user = $model_business->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
'model_business' => $model_business,
]);
// }
}
view
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
//if(isset($model_business))
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="container" style="width: 100%;">
<div class="row" style="background: #fcfcfc;">
<div class="col-md-12 login-form-top">
</div>
<div class="col-lg-12 signup-form ">
<div class="signup-form-container">
<?php $form = ActiveForm::begin(['id' => 'login-form' ]);
$loginUrl = \Yii::$app->UrlManager->createUrl(['site/login']);
?>
<h1>Sign Up</h1>
<p style="text-align: center;">Please fill in this form to create an account.<br/>
Already a Member? Login
</p>
<div class="form-radio col-xs-6" style="padding:0;">
<label class="radio-container">Personal Account
<input type="radio" checked="checked" value="personal" name="acc-type" id="personal_radio">
<span class="radio-checkmark"></span>
</label>
</div>
<div class="form-radio col-xs-6" style="padding:0;">
<label class="radio-container">Business Account
<input type="radio" value="enterprise" name="acc-type" id="enterprise_radio">
<span class="radio-checkmark"></span>
</label>
</div>
<hr>
<?php if(isset($model) && !empty($model)): ?>
<div id="personal">
<div class="col-xs-6" style="padding-left:0; padding-right:5px;">
<?= $form->field($model, 'last_name', [
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Surname'])->label(false) ?>
</div>
<div class="col-xs-6" style="padding-right:0; padding-left:5px;">
<?= $form->field($model, 'first_name', [
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Given Name'])->label(false) ?>
</div>
<div class="col-xs-12 col-nopadding">
<?= $form->field($model, 'username',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Username'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model, 'email',[])->textInput(['placeholder'=> 'Email'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model, 'phone1',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Phone Number'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model, 'password',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->passwordInput(['placeholder'=> 'Password'])->label(false) ?>
</div>
</div>
<?php endif;?>
<?php if(isset($model_business) && !empty($model_business)): ?>
<div id="enterprise">
<div class="col-xs-12" style="padding-right:0; padding-left:5px;">
<?= $form->field($model_business, 'business_name', [
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Business Legal name'])->label(false) ?>
</div>
<div class="col-xs-12 col-nopadding">
<?= $form->field($model_business, 'username',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Username'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model_business, 'email',[])->textInput(['placeholder'=> 'Business email'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model_business, 'phone1',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder'=> 'Business Phone Number'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model_business, 'password',[
'template'=>'{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->passwordInput(['placeholder'=> 'Password'])->label(false) ?>
</div>
</div>
<?php endif;?>
<!--<input class="signup-input" type="password" placeholder="Repeat Password" name="psw-repeat" >-->
<div class="col-md-12 col-nopadding">
<p class="signup-condition">By creating an account you agree to our Privacy Policy.</p>
</div>
<div class="form-group">
<?= Html::submitButton('Sign Up', ['class' => 'btn', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
<?php
$script = <<< JS
$(document).ready(function(){
$(function (){
$("#enterprise_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").show();
$("#personal").hide();
}
});
});
$(function (){
$("#personal_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").hide();
$("#personal").show();
}
});
});
});
JS;
$this->registerJs($script);
?>
The two images above is a brief description of what i'm trying to achieve but the forms are loaded from different model and must be filled before it can be validate and i only need user to fill one of this form at a time which means the other will be empty and cannot validate which will trigger an error, is there any way to solve this problem or a better way to fix this.
i fill in the first form the presonal account and click submit, nothing happens, then i check on the business account form and got this error which means it also want me to fill out the form before it can proceed with the submition
You should either create a custom FormModel or create 2 separate forms,that would show up whenever the relevant choice/radio input is selected, what yo are doing is that the models are differen and the form is combined for the fields of both models which is odd and creating problems.
If you choose to create a single FormModel you should use Conditional Validation which provides when and whenClient inside the rules for the validation checks.
A quick suggestion would be to create 2 different forms like below as both are different models and you should assign the fields for the models to 2 different forms, rather than trying to merge all the fields in a single form and keeping the models separate
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
//if(isset($model_business))
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="container" style="width: 100%;">
<div class="row" style="background: #fcfcfc;">
<div class="col-md-12 login-form-top">
</div>
<div class="col-lg-12 signup-form ">
<div class="signup-form-container">
<?php
$loginUrl = \Yii::$app->UrlManager->createUrl(['site/login']);
?>
<h1>Sign Up</h1>
<p style="text-align: center;">Please fill in this form to create an account.<br/>
Already a Member? Login
</p>
<div class="form-radio col-xs-6" style="padding:0;">
<label class="radio-container">Personal Account
<input type="radio" checked="checked" value="personal" name="acc-type" id="personal_radio">
<span class="radio-checkmark"></span>
</label>
</div>
<div class="form-radio col-xs-6" style="padding:0;">
<label class="radio-container">Business Account
<input type="radio" value="enterprise" name="acc-type" id="enterprise_radio">
<span class="radio-checkmark"></span>
</label>
</div>
<hr>
<?php if (isset($model) && !empty($model)): ?>
<?php $form = ActiveForm::begin(['id' => 'signup-form']); ?>
<div id="personal">
<div class="col-xs-6" style="padding-left:0; padding-right:5px;">
<?=
$form->field($model, 'last_name', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Surname'])->label(false)
?>
</div>
<div class="col-xs-6" style="padding-right:0; padding-left:5px;">
<?=
$form->field($model, 'first_name', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Given Name'])->label(false)
?>
</div>
<div class="col-xs-12 col-nopadding">
<?=
$form->field($model, 'username', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Username'])->label(false)
?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model, 'email', [])->textInput(['placeholder' => 'Email'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?=
$form->field($model, 'phone1', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Phone Number'])->label(false)
?>
</div>
<div class="col-md-12 col-nopadding">
<?=
$form->field($model, 'password', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>{error}{hint}'
])->passwordInput(['placeholder' => 'Password'])->label(false)
?>
</div>
<div class="col-md-12 col-nopadding">
<p class="signup-condition">By creating an account you agree to our Privacy Policy.</p>
</div>
<div class="form-group">
<?= Html::submitButton('Sign Up', ['class' => 'btn', 'name' => 'signup-button']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
<?php endif; ?>
<?php if (isset($model_business) && !empty($model_business)): ?>
<?php $form = ActiveForm::begin(['id' => 'signup-business']); ?>
<div id="enterprise">
<div class="col-xs-12" style="padding-right:0; padding-left:5px;">
<?=
$form->field($model_business, 'business_name', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Business Legal name'])->label(false)
?>
</div>
<div class="col-xs-12 col-nopadding">
<?=
$form->field($model_business, 'username', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Username'])->label(false)
?>
</div>
<div class="col-md-12 col-nopadding">
<?= $form->field($model_business, 'email', [])->textInput(['placeholder' => 'Business email'])->label(false) ?>
</div>
<div class="col-md-12 col-nopadding">
<?=
$form->field($model_business, 'phone1', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->textInput(['placeholder' => 'Business Phone Number'])->label(false)
?>
</div>
<div class="col-md-12 col-nopadding">
<?=
$form->field($model_business, 'password', [
'template' => '{input}<span class="asteric form-control-feedback">*</span>'
. ' {error}{hint}'
])->passwordInput(['placeholder' => 'Password'])->label(false)
?>
</div>
</div>
<div class="col-md-12 col-nopadding">
<p class="signup-condition">By creating an account you agree to our Privacy Policy.</p>
</div>
<div class="form-group">
<?= Html::submitButton('Sign Up', ['class' => 'btn', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php
$script = <<< JS
$(document).ready(function(){
$(function (){
$("#enterprise_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").show();
$("#personal").hide();
}
});
});
$(function (){
$("#personal_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").hide();
$("#personal").show();
}
});
});
});
JS;
$this->registerJs($script);
?>
Controller Code
function actionSignup($mode)
{
$model = new SignupForm();
$model_business = new SignupFormbusiness();
if (Yii::$aap->request->isPost) {
$accountType = Yii::$app->request->post("acc-type");
if ($accountType == 'personal' && $model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
if ($accountType == 'enterprise' && $model_business->load(Yii::$app->request->post())) {
if ($user = $model_business->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
}
return $this->render('signup', [
'model' => $model,
'model_business' => $model_business,
]);
}
Hoping that by default validation is activated for the two forms, the following solution will apply
First, give the two forms different ids say first_form_id and secod_form_id as follows:
//For the first form:
<?php $form = ActiveForm::begin(['id' => 'first_form_id']); ?>
//For the second form:
<?php $form = ActiveForm::begin(['id' => 'second_form_id']); ?>
Then you can modify the last part of your view file as below:
<?php
$script = <<< JS
$(document).ready(function(){
$(function (){
$("#enterprise_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").show();
$("#personal").hide();
// Here we are disabling the validation for the first form;
$('#first_form_id').yiiActiveForm('validate', false);
//Activate the validation of the second form just incase it was disabled
$('#second_form_id').yiiActiveForm('validate', true);
}
});
});
$(function (){
$("#personal_radio").on('click',function(){
$(this).prop('checked', true);
if($(this).is(':checked')){
$("#enterprise").hide();
$("#personal").show();
//Activate the validation of the first form
$('#first_form_id').yiiActiveForm('validate', true);
//De-activate the validation of the first form just incase it was disabled
$('#second_form_id').yiiActiveForm('validate', false);
}
});
});
});
JS;
$this->registerJs($script);
?>
I have a table AssetsAssignations, with hundreds of rows. In some cases, the user needs to select many rows with a checkbox, and change the "status" for all of them together.
In my controller, I have this function
public function editMultiple()
{
$assetStatuses = $this->AssetsAssignations->AssetStatuses->find('list');
$this->paginate = [
'contain' => ['Assets', 'AssetStatuses', 'Clients', 'Rooms'],
'sortWhitelist' => [
'Assets.model_number',
'Assets.serial_number',
'AssetStatuses.name',
'Clients.last_name',
'Rooms.name',
]
];
$assetsAssignations = $this->request->data;
$assetsAssignations_ids = array();
foreach($assetsAssignations as $a){
$assetsAssignations_ids[$a['id']] = $a['id'];
$this->AssetsAssignations->updateAll(
array('AssetAssignation.id' => $assetsAssignations_ids)
);
$this->Session->setFlash(__('Statsus is updated for the selcted entries!'));
}
debug($assetsAssignations);
$query = $this->AssetsAssignations->find()
->contain(['Assets', 'AssetStatuses', 'Clients', 'Rooms']);
$filter = $this->Filter->prg($query);
$assetsAssignations = $this->paginate($filter, ['maxLimit' => 10000, 'limit' => 10000]);
$this->set(compact('assetsAssignations', 'assetStatuses'));
$this->set('_serialize', ['assetsAssignations']);
}
In my edit_multiple.ctp, I use a javascript to filter the data. And I put this code:
<table class="hoverTable dataTable">
<thead>
<tr>
<th>Select</th><th>Model Number</th><th>Serial Number</th><th>Room</th><th>Client</th><th>Status</th>
</tr>
</thead>
</thead>
<?php foreach ($assetsAssignations as $assetsAssignation): ?>
<tr>
<td><input name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="AssetsAssignationsId1" type="checkbox"></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->model_number : '' ?></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->serial_number : '' ?></td>
<td><?= $assetsAssignation->has('room') ? $assetsAssignation->room->name : '' ?></td>
<td><?= $assetsAssignation->has('client') ? $assetsAssignation->client->last_name . ', ' . $assetsAssignation->client->first_name: '' ?></td>
<td><?= $assetsAssignation->has('asset_status') ? $assetsAssignation->asset_status->name : '' ?></td>
</tr>
<?php endforeach; ?>
</table>
<legend><?= __('') ?></legend>
</div>
<?= $this->Form->create($assetsAssignation) ?>
<fieldset>
<div class="row">
<div class="col-xs-3"><?= $this->Form->input('asset_status_id', ['options' => $assetStatuses, 'empty' => true, 'label' => __('Change Status To')]) ?></div>
</div>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
When I debug the result, checking 3 entries, I get this:
[
'data' => [
'AssetsAssignations' => [
'id' => [
(int) 0 => '411',
(int) 1 => '413',
(int) 2 => '415'
]
]
],
'asset_status_id' => '3'
]
My question is: How to pass the selected row IDs to the "Submit" button after selecting the checkboxes ?
Thanks in advance.
I think that what you want to do is something like
if($this->request->is('post')
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ]
['id IN' => $ids]
);
}
Based on what #Arilia suggested, tis worked for me. In my controller, function, I put this:
$this->request->data;
$data = $this->request->data;
debug($data);
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ],
['id IN' => $ids]
);
}
In my view, I put this:
<td><input type="checkbox" name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="ApplicationId1" ></td>
I am confused with one problem from couple of days and i could not solve it. I have a form which has different classes and when user clicks on add button i want to generate couple of fields. I can generate the fields but i am not able to pass that particular class_id with those dynamic generated fields. I am using this widget And here is how i am generating the dynamic fields.
Only involved model is Registration form. Other than that i am just firing query and displaying the data.One class can have multiple Registrations
Class Registration
is id
name class_id
firstname
lastname
This is my view code
<?php if (!empty($data)) {
foreach($data as $event){
$modelsRegistration = [new Registration()];
DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items'.$model['id'], // required: css class selector
'widgetItem' => '.item'.$model['id'], // required: css class
'limit' => 4, // the maximum times, an element can be added (default 999)
'min' => 0, // 0 or 1 (default 1)
'insertButton' => '.add-item'.$model['id'], // css class
'deleteButton' => '.remove-item'.$model['id'], // css class
'model' => $modelsRegistration[0],
'formId' => 'registration-form',
'formFields' => [
'firstname',
'lastname',
],
]);
?>
<div class="container">
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-12 col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Class Name</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Rounds</th>
</tr>
</thead>
<tbody>
<tr>
<td><?= $event['name'] ?></td>
<td><button type="button" id="<?= $event['id'] ?>" class="add-item<?=$model['id'] ?> btn btn-success btn-xs">Add Rounds <i
class="glyphicon glyphicon-plus"></i></button></td>
</tr>
</tbody>
</table>
<div class="row">
<div class="container-items<?=$model['id'] ?>"><!-- widgetBody -->
<?php foreach ($modelsRegistration as $i => $modelRegistration){
?>
<div class="item<?=$model['id'] ?>"><!-- widgetItem -->
<?php
// necessary for update action.
if (!$modelRegistration->isNewRecord) {
echo Html::activeHiddenInput($modelRegistration, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-5">
<?= $form->field($modelRegistration, "[{$i}]firstname")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-5">
<?= $form->field($modelRegistration, "[{$i}]lastname")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelRegistration, "[{$i}]class_id")->hiddenInput(['maxlength' => true])->label(false) ?>
</div>
<div class="col-sm-2">
<button type="button" class="remove-item<?=$model['id'] ?> btn btn-danger btn-xs"><i
class="glyphicon glyphicon-minus"></i></button>
</div>
</div>
<!-- .row -->
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<?php
DynamicFormWidget::end();
} } ?>
If you have a view showing only people of one class (therefore, adding more people means they all are the same class) you can use in your dynamicform only the first/last name fields and add this id_class later in the controller just before saving it.
Example:
// load and validation of the model
// ...
foreach ($modelsRegistration as $modelRegistration) {
$modelRegistration->class_id = $myClassId;
if (! ($flag = $modelRegistration->save(false))) {
$transaction->rollBack();
break;
}
}
Now, if in your view you have people of all class divided by sections and each section have this add button, i strongly recommend you remove this add buttons from there and make a new section just for add people (with a select for choose a class).
Steps:
Remove the option insertButton in the DynamicFormWidget class in all those sections. And remove the html button also (won't work anymore).
Add the new section, something like this:
<?php
$newModelsRegistration = [new Registration()];
DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper_registration', // required: [A-z0-9_]
'widgetBody' => '.container-items-registration', // required: css class selector
'widgetItem' => '.item-registration', // required: css class
'limit' => 1, // the maximum times, an element can be added (default 999)
'min' => 0, // 0 or 1 (default 1)
'insertButton' => '.add-item-registration', // css class
'deleteButton' => '.remove-item-registration', // css class
'model' => $newModelsRegistration[0], //
'formId' => 'registration-form',
'formFields' => [
'firstname',
'lastname',
'class_id'
],
]);
?>
<div class="panel-body">
<button type="button" class="add-item-registration btn btn-success btn-sm pull-right margin-b-base">
<i class="glyphicon glyphicon-plus"></i> Add
</button>
<div class="clearfix"></div>
<div class="container-items-registration"><!-- widgetBody -->
<?php foreach ($newModelsRegistration as $i => $newModelRegistration): ?>
<div class="item-registration panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Registration</h3>
<div class="pull-right">
<button type="button" class="remove-item-registration btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<div class="form-group row">
<div class="col-md-12">
<?= $form->field($newModelRegistration, "[{$i}]firstname")->textInput(['maxlength' => true]) ?>
<?= $form->field($newModelRegistration, "[{$i}]lastname")->textInput(['maxlength' => true]) ?>
<?= $form->field($newModelRegistration, "[{$i}]class_id")->dropDownList(
ArrayHelper::map(Class::find()->all(), 'id', 'name'),
['prompt' => 'Select']
) ?>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php DynamicFormWidget::end(); ?>
Make sure the limit option is set to 1. So, will be easy to avoid people trying to add too much registrations in the same class (if i understood correctly each class have a limit amount of registrations). You can add a new rule in your Registration model and check if it already reached the limit of that class. Same thing for that find() method used in the dropDownList.
But if you still want to have all this add button in the same view, you can always use js to add that value for you.
Example:
// begin of form
// ...
<?= $form->field($modelRegistration, "[{$i}]class_id")->hiddenInput(['maxlength' => true, 'class' => 'form-control add-class-id', 'data-event' => $event['id']])->label(false) ?>
// end of form
<?php
$js = <<<JS
$('#registration-form').on('submit', function (e) {
$('.add-class-id').each(function() {
$(this).val($(this).attr('data-event'));
});
});
JS;
$this->registerJs($js);
?>
Let me know if any of this ideas works for you.
Hey guys we have a perfectly working web page (index_admin) of the Relationships controller, but after adding pagination its all crashing.
Coming up with:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Relationship.sender_id' in 'where clause'
Customers and businesses build 'relationships' so they can exchange invoices over our website. Here is the DB schema:
id, sender_id, receiver_id, active, requested, expiry_date
Sender_id and receiver_id are both foreign keys to the Account Table. So in other words tells the db which accounts are linked to each other.
Relationship model 'BELONGSTO' 'RECEIVER AND SENDER ACCOUNT MODELS':
public $belongsTo = array(
'ReceiverAccount' =>array(
'className' => 'Account',
'foreignKey' =>'receiver_id',
'associationForeignKey' => 'accounts_id',
),
'SenderAccount' =>array(
'className' => 'Account',
'foreignKey' =>'sender_id',
'associationForeignKey' => 'accounts_id',)
);
Index_admin:
public function index_admin(){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array(
"OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid)
);
//Find all Invoices where receiver_id = accountid
$relationships=$this->Relationship->find('all', array(
'conditions' => $conditions));
debug($conditions);
$compName = $this->Account->field('account_name', array('id' => 'Relationship.id'));
$this->paginate = array(
'limit' => 10,
'conditions'=> $conditions
);
$this->set('accountid', $accountid);
$this->set('relationship', $this->paginate());
$this->set('compName', $compName);
}
Index_admin view (partial):
<table id="data">
<tr>
<td colspan=7 align='right'>
<?php
echo $this->Paginator->prev('<' . __('previous'), array(), null, array('class'=>'prev disabled'));
echo ' ';
echo $this->Paginator->numbers(array('seperator'=>''));
echo ' ';
echo $this->Paginator->next(__('next') . '>', array(), null, array('class'=>'next disabled'));
?>
</td>
</tr>
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('sender_id'); ?></th>
<th><?php echo $this->Paginator->sort('receiver_id'); ?></th>
<th><?php echo $this->Paginator->sort('expiry_date'); ?></th>
<th>Status</th>
<th>Actions</th>
</tr>
<?php foreach($relationship as $relationships):?>
<?php
if($relationships['Relationship']['requested']==1)
{
$status = 'Requested';
$bgcol = '#F8FAC0';
}
else if($relationships['Relationship']['active']==1)
{
$status = 'Active';
$bgcol = '#CFDAE8';
}
else if($relationships['Relationship']['active']==0)
{
$status = 'Expired';
$bgcol = '#FAB9B9';
}
if($relationships['Relationship']['active']==0 && $relationships['Relationship']['requested']==0)
{
$action = 'Reactivate';
}
else
{
$action = 'Edit Expiry';
}
if($relationships['Relationship']['sender_id']==$accountid)
{
$start = '<font color="#191970">';
$end = '</font>';
}
else
{
$start = NULL;
$end = NULL;
}
if($relationships['Relationship']['receiver_id']==$accountid)
{
$startr = '<font color="#191970">';
$endr = '</font>';
}
else
{
$startr = NULL;
$endr = NULL;
}
if($relationships['Relationship']['sender_id']==$accountid)
{
$acctname = $relationships['ReceiverAccount']['account_name'];
}
else if($relationships['Relationship']['receiver_id']==$accountid)
{
$acctname = $relationships['SenderAccount']['account_name'];
}
?>
<tr>
<td align='center'><?php echo $relationships['Relationship']['id']; ?></td>
<td align='center'><?php echo $start?><?php echo $relationships['SenderAccount']['account_name']; ?><?php echo $end ?></td>
<td align='center'><?php echo $startr?><?php echo $relationships['ReceiverAccount']['account_name']; ?><?php echo $endr ?></td>
<td align='center'><?php echo date('d.m.Y', strtotime($relationships['Relationship']['expiry_date'])); ?></td>
<td align='center' bgcolor='<?php echo $bgcol ?>'><?php echo $status ?></td>
<td align='center'>
<?php echo $this->Form->Html->link('Delete', array('controller' => 'Relationships','action'=>'delete',$relationships['Relationship']['id']), NULL, 'Are you sure you want to delete '. $acctname);
?> | <?php echo $action ?> </td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=7 align='right'>
<?php
echo $this->Paginator->prev('<' . __('previous'), array(), null, array('class'=>'prev disabled'));
echo ' ';
echo $this->Paginator->numbers(array('seperator'=>''));
echo ' ';
echo $this->Paginator->next(__('next') . '>', array(), null, array('class'=>'next disabled'));
?>
</td>
</tr>
</table>
Like I said it was all working before hand, now it isn't, but I can't see why.
It is always wise to set the debug mode on to see all possible errors in detail. You've just shared the sql error part from which it is clear that the intended table doesn't have the "sender_id" field. I'm assuming you've debug mode on. So first have a look at the generated query. Then you'll find which table the query is trying to dig in.
If your query is referencing the correct table, you can try this:
public function index_admin(){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array(
"OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid)
);
App::import('Model', 'Relationship');
$objRelationship = new Relationship();
$this->paginate = array( "conditions" => $conditions, 'limit' => 10 );
$relationships = $this->paginate( $objRelationship );
$compName = $this->Account->field('account_name', array('id' => 'Relationship.id'));
$this->set('accountid', $accountid);
$this->set('relationship', $this->paginate());
$this->set('compName', $compName);
}