I'm using yii2 dynamic form to collect data. Within the dynamic form, I want a button in each row. And on click of it, It'll call a javascript function to take fingerprint and put it in the image. The button is showing good for the first row, but from second row, It's not properly coming up.
Secondly when I click on the Click here to Scan button, it takes the fingerprint and put it in the first row.
How can I solve this 2 issue.
The Code I'm using in this form is -
<div class="row">
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Crew Members</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 200, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
//'scanButton' => '.scan-item',
'model' => $modelsProductsales[0],
'formId' => 'dynamic-form',
'formFields' => [
//'wpc_wpno',
'wpc_crewid',
'wpc_crewname',
'wpc_auth',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsProductsales as $i => $modelsProductsales): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelsProductsales->isNewRecord) {
echo Html::activeHiddenInput($modelsProductsales, "[{$i}]wpc_id");
}
?>
<div class="row-fluid">
<div class="form-group">
<div class="col-xs-4 col-sm-4 col-lg-4 nopadding">
<div class="col-xs-12 col-sm-12 col-lg-12 nopadding" >
<?= $form->field($modelsProductsales, "[{$i}]wpc_crewid")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Crew ID No','autocomplete' => 'off','onchange' => 'getCrewName($(this));','onkeyup' => 'getCrewName($(this));','class' => 'crewid']) ?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12 nopadding" >
<?= $form->field($modelsProductsales, "[{$i}]wpc_crewname")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Crew Name','readOnly'=>true]) ?>
</div>
</div>
</div>
<div class="col-xs-5 col-sm-5 col-lg-5 nopadding">
<div align="center">
<div class="col-xs-12 col-sm-12 col-lg-12 nopadding" >
<img id="FPImage1-<?= $i ?>-image" alt="Fingerpint Image" height=100 width=95 align="center" src="/images/PlaceFinger.bmp"> <br>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12 nopadding" >
<div class="col-xs-6 col-sm-6 col-lg-6 nopadding" >
<input type="[{$i}]button" class="btn btn-success btn-xs" value="Click to Scan" onclick="CallSGIFPGetData(SuccessFunc1, ErrorFunc)"><br>
</div>
<div class="col-xs-6 col-sm-6 col-lg-6 nopadding" >
<input type="[{$i}]button" class="btn btn-success btn-xs" value="Click here to Verify" onclick="matchScore(succMatch, failureFunc)"><br>
</div>
</div>
</div>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding" >
<?= $form->field($modelsProductsales, "[{$i}]wpc_auth")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Verification','readOnly'=>true]) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs" onClick="workmanPlus()"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs" onClick="workmanMinus()"><i class="glyphicon glyphicon-minus"></i></button>
</div>
</div>
</div>
</div><!-- .row -->
</div>
</div><!-- item panel default -->
<?php endforeach; ?>
</div><!-- container item -->
<?php DynamicFormWidget::end(); ?>
</div><!-- panel body -->
</div><!-- panel default -->
</div><!-- outer row -->
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12 col-lg-12">
<h2><center><u>Select Safety Precaution Taken : Operations</u></center></h2>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-10 col-sm-10 col-lg-10">
<?= $form->field($model, 'wp_pt1')->textInput(['maxlength' => true,'readOnly'=>true])->label(false) ?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2">
<div class="form-inline">
<? $model->wp_ptst1 = 'Yes'; ?>
<?= $form->field($model, 'wp_ptst1')->radioList(['Yes'=>'Yes','No'=>'No','NA'=>'NA'])->label(false); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-10 col-sm-10 col-lg-10">
<?= $form->field($model, 'wp_pt2')->textInput(['maxlength' => true,'readOnly'=>true])->label(false) ?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2">
<div class="form-inline">
<? $model->wp_ptst2 = 'Yes'; ?>
<?= $form->field($model, 'wp_ptst2')->radioList(['Yes'=>'Yes','No'=>'No','NA'=>'NA'])->label(false); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-10 col-sm-10 col-lg-10">
<?= $form->field($model, 'wp_pt3')->textInput(['maxlength' => true,'readOnly'=>true])->label(false) ?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2">
<div class="form-inline">
<? $model->wp_ptst3 = 'Yes'; ?>
<?= $form->field($model, 'wp_ptst3')->radioList(['Yes'=>'Yes','No'=>'No','NA'=>'NA'])->label(false); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-10 col-sm-10 col-lg-10">
<?= $form->field($model, 'wp_pt4')->textInput(['maxlength' => true,'readOnly'=>true])->label(false) ?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2">
<div class="form-inline">
<? $model->wp_ptst4 = 'Yes'; ?>
<?= $form->field($model, 'wp_ptst4')->radioList(['Yes'=>'Yes','No'=>'No','NA'=>'NA'])->label(false); ?>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group pull-right">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Submit', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the itemid */
$script = <<< JS
function workmanPlus() {
var workMen = $(".wmn").val();
workMen++;
//alert(workMen);
$(".wmn").val(workMen);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
<?php
/* start getting the itemid */
$script = <<< JS
function workmanMinus() {
var workMen = $(".wmn").val();
workMen--;
//alert(workMen);
$(".wmn").val(workMen);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
<?php
/* start getting the crew name and template 2 details */
$script = <<< JS
function getCrewName(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
product = item.val();
//alert(product);
$.get('index.php?r=workpermit/workpermit/get-for-crewdetails',{ prodname : product }, function(data){
//alert(data);
var data = $.parseJSON(data);
var getItemid = data;
itemID = "wpcrew-".concat(index).concat("-wpc_crewname");
template_2 = getItemid["cr_pw1"];
//alert(template_2);
$("#"+itemID+"").val(getItemid["cr_name"]);
});
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the item details */
?>
<script type="text/javascript">
var template_1 = "";
function SuccessFunc1(result) {
if (result.ErrorCode == 0) {
/* Display BMP data in image tag
BMP data is in base 64 format
*/
if (result != null && result.BMPBase64.length > 0) {
document.getElementById('FPImage1-<?= $i ?>-image').src = "data:image/bmp;base64," + result.BMPBase64;
}
template_1 = result.TemplateBase64;
}
else {
alert("Fingerprint Capture Error Code: " + result.ErrorCode + ".\nDescription: " + ErrorCodeToString(result.ErrorCode) + ".");
}
}
function ErrorFunc(status) {
/*
If you reach here, user is probabaly not running the
service. Redirect the user to a page where he can download the
executable and install it.
*/
alert("Check if SGIBIOSRV is running; status = " + status + ":");
}
function CallSGIFPGetData(successCall, failCall) {
var secugen_lic = "";
var uri = "https://localhost:8443/SGIFPCapture";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fpobject = JSON.parse(xmlhttp.responseText);
successCall(fpobject);
}
else if (xmlhttp.status == 404) {
failCall(xmlhttp.status)
}
}
xmlhttp.onerror = function () {
failCall(xmlhttp.status);
}
var params = "Timeout=" + "10000";
params += "&Quality=" + "50";
params += "&licstr=" + encodeURIComponent(secugen_lic);
params += "&templateFormat=" + "ISO";
xmlhttp.open("POST", uri, true);
xmlhttp.send(params);
}
function matchScore(succFunction, failFunction) {
var idQuality = 100;
//alert(template_2);
//alert("matchscore is called!");
//alert("Template 1 = " + template_1 + " & Template 2 = " + template_2);
if (template_1 == "" || template_2 == "") {
alert("Please scan finger again!!");
return;
}
var uri = "https://localhost:8443/SGIMatchScore";
var secugen_lic = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fpobject = JSON.parse(xmlhttp.responseText);
succFunction(fpobject);
}
else if (xmlhttp.status == 404) {
failFunction(xmlhttp.status)
}
}
xmlhttp.onerror = function () {
failFunction(xmlhttp.status);
}
var params = "template1=" + encodeURIComponent(template_1);
params += "&template2=" + encodeURIComponent(template_2);
params += "&licstr=" + encodeURIComponent(secugen_lic);
params += "&templateFormat=" + "ISO";
xmlhttp.open("POST", uri, false);
xmlhttp.send(params);
}
function succMatch(result) {
//var idQuality = document.getElementById("quality").value;
var idQuality = 100;
if (result.ErrorCode == 0) {
if (result.MatchingScore >= idQuality){
alert("MATCHED Found!");
//verification = "Verified";
//verification = "wpcrew-".concat(index).concat("-wpc_auth");
document.getElementById('wpcrew-<?= $i ?>-wpc_auth').value = "Verified";
//break loopedfunction;
}
else
alert("NOT MATCHED !");
}
else {
alert("Error Scanning Fingerprint ErrorCode = " + result.ErrorCode);
}
}
function failureFunc(error) {
alert ("On Match Process, failure has been called");
}
</script>
After implementing Vandro's solution -
The button values are showing in every row.
But on clicking "Click to scan" in the second row, it's scanning and passing the value to the first row image.
Also, On click on "Click to scan" the form is trying to get submitted.
Try this:
change how you call your image for way this:
<?= \yii\bootstrap\Html::img('/images/PlaceFinger.bmp', [
'id'=>"FPImage-0-image",
'alt' => 'Fingerpint Image',
'height'=>'100',
'width'=>'95',
'align'=>"center"
]) ?>
and change your bottoms to this:
<div class="col-xs-12 col-sm-12 col-lg-12 nopadding">
<div class="col-xs-6 col-sm-6 col-lg-6 nopadding">
<?= yii\bootstrap\Button::widget([
'label' => "Click to Scan",
'options' => [
'id' => "btnCallSGIFPGetData",
'class' => 'btn btn-success btn-xs',
'onclick' => "CallSGIFPGetData(SuccessFunc1, ErrorFunc)"
],
]);
?>
</div>
<div class="col-xs-6 col-sm-6 col-lg-6 nopadding">
<?= yii\bootstrap\Button::widget([
'label' => "Click here to Verify",
'options' => [
'id' => 'btnMatchScore',
'class' => 'btn btn-success btn-xs',
'onclick' => "matchScore(succMatch, failureFunc)"
],
]);
?>
</div>
</div>
then let me know your progress to see on what else can i help
UPDATE
first change the button id for something like:
'id' => "btn-0-CallSGIFPGetData",
on your onclick send your button to with $(this):
'onclick' => "CallSGIFPGetData(SuccessFunc1, ErrorFunc, $(this))"
then edit your CallSGIFPGetData function to be like:
function CallSGIFPGetData(successCall, failCall, btn)
then on your successCall inside CallSGIFPGetData send the button Id to:
successCall(fpobject, btn.attr('id'));
and then edit your SuccessFunc1 function to be like:
function SuccessFunc1(result, btnId)
then inside the SuccessFunc1 function get your index:
var index=btnId.split('-')[1].split('-')[0];
and placed on:
document.getElementById('FPImage-'+index+'-image').src...
hope it works
Related
I'm dynamically building part of a Razor view based upon the number of entries in a model list.
At design time, I get a little red dot before this ending div in this if:
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}
And at design time, I'm getting an "End tag is missing a start tag" at the bottom.
How do I resolve that? How do I build this dynamically if I get that?
At run-time, as expected, I get: Encountered end tag "div" with no matching start tag. Are your start/end tags properly balanced?
Here's the .cshtml file (the view):
<h2>Test</h2>
#model GbngWebClient.Models.UserProfileForMaintVM
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading aboutyou">It's All About You!</div>
<br />
<h5 class="single">General</h5>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
#Html.LabelFor(model => model.UserProfileSingleVM.WhoIAmDescr)
#Html.TextAreaFor(model => model.UserProfileSingleVM.WhoIAmDescr, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserProfileSingleVM.WhoIAmDescr, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
#Html.LabelFor(model => model.UserProfileSingleVM.ThinkingDescr)
#Html.TextAreaFor(model => model.UserProfileSingleVM.ThinkingDescr, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserProfileSingleVM.ThinkingDescr, "", new { #class = "text-danger" })
</div>
</div>
<br />
</div>
<div class="panel-body">
#{
var lastOne = 'n';
var colCount = 1;
}
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
if (colCount == 1)
{
<div class="row">
}
<div class="col-md-3">
#Html.LabelFor(Model => Model.UserProfileMultiList25[i].Description))
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
</div>
if (colCount == 3)
{
</div> #* Finishes the row. *#
colCount = 1;
lastOne = 'y';
}
else
{
colCount += 1;
}
}
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}
</div> #* Finishes the panel. *#
<div class="panel-body">
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
It works but does not surround it with a:
<div class="row">....</div>.
Gets the job done:
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
<div class="col-md-3">
<div>
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
<label>
#Html.DisplayFor(Model => Model.UserProfileMultiList25[i].Description)
#Html.HiddenFor(Model => Model.UserProfileMultiList25[i].SelectionId)
#Html.HiddenFor(Model => Model.UserProfileMultiList25[i].ProfileCategoryId)
</label>
</div>
</div>
}
You are declaring colCount inside of your loop, and it's getting initialized to 1 each time. I'm guessing what you mean to do is to declare and initialize it outside the loop so it's an actual counter:
#{
var lastOne = 'n';
var colCount = 1;
}
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
if (colCount == 1)
{
<div class="row">
}
<div class="col-md-3">
#Html.LabelFor(Model => Model.UserProfileMultiList25[i].Description))
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
</div>
if (colCount == 3)
{
</div> #* Finishes the row. *#
colCount = 1;
lastOne = 'y';
}
else
{
colCount++;
}
}
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}
I have data table with search filed. I am trying to filter table using data range and order status. I want to filter table also using range and status and also want to export into excel sheet. Code is working for only search and simple export (Not filtered data).
Thanks
This is my file (View, Controller and Model)
View:-
<a class="pull-right btn btn-primary btn-xs" href="<?php echo base_url()?>order/createXLS"><i class="fa fa-file-excel-o"></i> Export Data</a>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" >Custom Filter : </h3>
</div>
<div class="panel-body">
<form id="form-filter" method="POST" action="order/ajax_list" class="form-horizontal">
<div class="form-group">
<label for="FirstName" class="col-sm-2 control-label">From</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="from">
</div>
</div>
<div class="form-group">
<label for="LastName" class="col-sm-2 control-label">To</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="to">
</div>
</div>
<div class="form-group">
<label for="LastName" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="status">
</div>
</div>
<div class="form-group">
<label for="LastName" class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<button type="button" id="btn-filter" class="btn btn-primary">Filter</button>
<button type="button" id="btn-reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
</div>
</div>
<table class="table table-bordered table-striped" id="mytable">
<thead>
<tr>
<th width="80px">No</th>
<th>Order Number</th>
<th>Service Date</th>
<th>Service Location</th>
<th>Customer Name</th>
<th>Contact Number</th>
<th>Order Status</th>
<th>Payment Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$start = 0;
foreach ($job_positions_data as $job_positions)
{
?>
<tr>
<td>
<?php echo ++$start ?>
</td>
<td>
<?php echo $job_positions->order_number ?>
</td>
<td>
<?php echo $job_positions->service_date ?>
</td>
<td>
<?php if($job_positions->service_location == 1)
{
echo 'vkool_branch';
}
else
{
echo 'customer_location' ;
}
?>
</td>
<td>
<?php echo $job_positions->firstname ?>
</td>
<td>
<?php echo $job_positions->contact_number ?>
</td>
<td>
<?php if($job_positions->order_status == 0)
{
echo 'Action Pending';
}
elseif($job_positions->order_status == 1)
{
echo 'Under Process' ;
}
elseif($job_positions->order_status == 2)
{
echo 'Cancelled' ;
}
elseif($job_positions->order_status == 3)
{
echo 'Completed' ;
}
elseif($job_positions->order_status == 4)
{
echo 'Refund' ;
}
?>
</td>
<td>
<?php if( $job_positions->payment_status == 1)
{
echo 'Pending (Pay at Store)';
}
elseif($job_positions->payment_status == 0)
{
echo 'Pending (Pay Online)';
}
elseif($job_positions->payment_status == 14)
{
echo 'Paid';
}?>
</td>
<td style="text-align:center" width="200px">
<i class="fa fa-search-plus"></i>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#mytable").dataTable();
});
</script>
Controller : -
public function createXLS() {
$fileName = 'data-'.time().'.xlsx';
require_once APPPATH . "/third_party/PHPExcel/Classes/PHPExcel.php";
$orderInfo = $this->Order_model->get_For_Export();
$ordervalue = json_encode($orderInfo, true);
/*echo '<pre>';
print_r($orderInfo);
echo '</pre>';
exit;*/
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
// set Header
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'S.No');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Order Number');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Service Location');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'First Name');
$objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Last Name');
$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Contact_No');
$objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Order Status');
$objPHPExcel->getActiveSheet()->SetCellValue('H1', 'Payment Status');
// Style
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'font' => array(
'bold' => true,
'color' => array('rgb' => '2F4F4F'),
'size' => 20,
),
);
$styleHeading = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'font' => array(
'bold' => true,
'size' => 15,
),
);
// set Row
$rowCount = 2;
foreach ($orderInfo as $element) {
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $element['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $element['order_number']);
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $element['service_location']);
$objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $element['firstname']);
$objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $element['lastname']);
$objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, $element['contact_number']);
$objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, $element['order_status']);
$objPHPExcel->getActiveSheet()->SetCellValue('H' . $rowCount, $element['payment_status']);
$rowCount++;
}
// download file
$filename = "jobSummery". date("Y-m-d-H-i-s").".xls";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
public function list_view()
{
$job_positions = $this->Order_model->get_all();
$data = array(
'job_positions_data' => $job_positions
);
$this->load->view('order/index', $data);
}
Model :-
public function get_all()
{
$this->db->order_by('id', 'DESC');
$this->db->from('tbl_order');
$query = $this->db->get();
$result = $query->result();
return $result;
}
public function get_For_Export()
{
$this->db->order_by('id', 'DESC');
$this->db->from('tbl_order');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
I have a program to store some financial values using batch process. Main tables are finance_budget & finance_budget_issue. finance_budget.budget_id = finance_budget_issue.budget_id (1 to many join)
I tried to edit some records using following code
Controller
public function editIssues($id)
{
$this->checkPermissions('edit', 'allocationIssues');
$bc = array(array('link' => 'budget/regIssues', 'page' => 'Allocation Issues'), array('link' => '#', 'page' => 'Edit'));
$meta = array('page_title' => 'Allocation Issues', 'bc' => $bc);
$this->form_validation->set_rules('vote_id', 'Vote', 'required');
$this->form_validation->set_rules('budget_date', 'Budget Date', 'required');
if ($this->form_validation->run() == true) {
$ustock = array(
'vote_id' => $this->input->post('vote_id'),
'budget_date' => $this->input->post('budget_date'),
'ref_no' => $this->input->post('ref_no'),
'usr' => $this->session->userdata('id_user'),
'added_time' => date('Y-m-d h:i:s'),
'budget_status' => 'issues',
'transfer_status' => 'Pending'
);
$count = count($this->input->post('office'));
$offices = $this->input->post('office');
$amount = $this->input->post('amount');
$notes = $this->input->post('notes');
for ($x = 0; $x < $count; $x++) {
$details[$x]['budget_id'] = $id;
$details[$x]['office'] = $offices[$x];
$details[$x]['amount'] = $amount[$x];
$details[$x]['notes'] = $notes[$x];
}
}
if ($this->form_validation->run() == true && $this->Budget_model->editIssuedAllocations($ustock, $details, $id)) {
$this->session->set_flashdata('message', 'Successfully Updated ..!!');
redirect('budget/regIssues');
} else {
$this->data['vote'] = $this->Budget_model->getVote(array('office_id'=>$this->session->userdata('office_id')));
$this->data['office'] = $this->Budget_model->getOffice();
$this->data['issues'] = $this->Budget_model->budgetById($id);
$this->render('budget/editIssues', $meta, $this->data);
}
}
Model
function editIssuedAllocations($ustock,$details,$id)
{
if(!empty($id)){
$this->db->trans_start();
$this->db->update('finance_budget',$ustock,array('budget_id'=>$id));
if($id!=1){
$this->db->where('budget_id', $id);
$this->db->delete('finance_budget_issue');
$this->db->insert_batch('finance_budget_issue', $details);
}
$this->db->trans_complete();
return $this->db->trans_status();
}
return false;
}
View
<?php
if (!empty($purchase)) {
$details = $purchase;
$purchase = $purchase[0];
}
?>
<script type="text/javascript">
$(document).ready(function () {
var i = $('#last').val();
$(".add-new").click(function () {
i++;
// $('.tab_logic').append();
$('#addr' + i).html("<td><a href='javascript:void(0);' id='add-post' class='external add-new'><i style='color: #00C853 !important;' class='fa fa-2x fa-plus-circle'></i></a></td>" +
"<td><select name='office[]' id='office" + i + "' class='select2 form-control' required>" +
"<option value=''></option>" +
<?php
if (!empty($office)) {
foreach ($office as $row) {
?>
"<option value='<?= $row->office_id ?>'><?= addslashes($row->office_name) ?></option>" +
<?php
}
}
?>
"</select></td>" +
"<td><input name='amount[]' type='number' step='any' placeholder='Amount' class='form-control input-md' required></td>" +
"<td><input name='notes[]' type='text' placeholder='Notes' class='form-control input-md'></td>" +
"<td><a href='javascript:void(0);' class='external remove'><i style='color: #dd4b39 !important;' class='fa fa-2x fa-minus-circle' id='addIcon'></i></a></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
$('#i').val(i);
// alert($('#i').val());
$('#item' + i).select2();
});
$(document).on("click", ".remove", function () {
var count = $('#tab_logic>tbody').children().length;
if (count > 0) {
$(this).closest('tr').remove();
}
});
});
</script>
<div class="box box-info">
<div class="box box-info collapsed-box">
<div class="box-header with-border">
<h3 class="box-title">Edit Issued Allocations</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" style="font-size: 16px;" data-widget="collapse"><i
class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body" style="display: block">
<form action="<?= site_url('budget/editPurchase/' . $purchase->budget_id) ?>" method="post">
<div class="row">
<div class="col-md-2">
<div class="form-group"><label>Budget ID</label>
<input type="text" name="budget_id" id="budget_id" class="form-control" disabled
value="<?= $purchase->budget_id ?> ">
</div>
</div>
<div class="col-md-4">
<div class="form-group"><label>වැය ශීර්ෂය</label>
<select name="vote_id" id="vote_id" class="form-control select2" required>
<option value="<?= $purchase->vote_id ?>"><?= $purchase->vote ?></option>
<?php
if (!empty($vote)) {
foreach ($vote as $row) {
?>
<option value="<?= $row->vote_id ?>"><?= $row->vote ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group"><label>යොමු / ගොණු අංකය</label>
<input type="text" name="ref_no" id="ref_no" class="form-control"
value="<?= $purchase->ref_no ?>">
</div>
</div>
<div class="col-md-2">
<div class="form-group"><label>දිනය</label>
<input type="date" name="budget_date" id="budget_date" class="form-control"
value="<?= $purchase->budget_date ?>">
</div>
</div>
</div>
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr>
<th class="text-center">
</th>
<th class="text-center">
Office
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Notes
</th>
<th class="text-center">
</th>
</tr>
</thead>
<tbody>
<?php
//dd($details);
$x = 0;
foreach ($details as $i => $values) {
// foreach ($values as $key => $value) {
$x = $i;
?>
<tr id='addr0'>
<td>
<a href="javascript:void(0);" id="add-post" class="external add-new"><i
style="color: #00C853 !important;"
class="fa fa-2x fa-plus-circle"></i></a>
</td>
<td style="width: 50%">
<input type="hidden" name="i" id="i" value="<?= $i ?>">
<select name="office[]" id="<?= "office" . $i ?>" class="form-control select2" required>
<option value="<?= $details[$i]->office_id ?>"><?= $details[$i]->office_name ?></option>
<?php
if (!empty($office)) {
foreach ($office as $row) {
?>
<option value="<?= $row->office_id ?>"><?= $row->office_name ?></option>
<?php
}
}
?>
</select>
</td>
<td>
<input type="number" name='amount[]' placeholder='Amount' class="form-control"
value="<?= (-1) * $details[$i]->amount ?>" required/>
</td>
<td>
<input type="text" name="notes[]" placeholder='Notes'
value="<?= $details[$i]->notes ?>" class="form-control"/>
<input type="hidden" name="table_id"
value="<?= $details[$i]->notes ?>">
</td>
<td><a href='javascript:void(0)' class='external remove'><i
style='color: #dd4b39 !important;'
class='fa fa-2x fa-minus-circle ' id='addIcon'></i></a>
</td>
</tr>
<tr id='addr1'></tr>
<?php
//print " $key => $value\n";
// }
//print "}\n";
}
?>
</tbody>
</table>
</div>
<!--table-->
<div class="row">
<div class="col-md-8"></div>
<div class="col-md-4">
<input type="hidden" value="<?= $x ?>" name="last" id="last">
<input type="submit" value="Update" class="btn btn-primary btn-block">
</div>
</div>
</form>
<!--end of table-->
</div>
</div>
</div>
Desired Output
Should be edit some values in the finance_budget & finance_budget_issue tables that related with same budget_id (Eg:- budget_id =2995)
Error
After editing some values in my view that is working & save properly. When I press the save button in my view without editing any value, the record in finance_budget_issue table that is related to finance_budget table by budget_id is deleted.
I can not understand what I am going wrong ? Can anyone help me ?
You could modify the model to check whether $details are empty or not to leave the finance_budget_issue table intact :
function editIssuedAllocations($ustock,$details,$id)
{
if(!empty($id)){
$this->db->trans_start();
$this->db->update('finance_budget',$ustock,array('budget_id'=>$id));
if($id!=1 && !empty($details[0])){
$this->db->where('budget_id', $id);
$this->db->delete('finance_budget_issue');
$this->db->insert_batch('finance_budget_issue', $details);
}
$this->db->trans_complete();
return $this->db->trans_status();
}
return false;
}
I have modified the for loop as follows in the controller.
$count = count($this->input->post('office'));
$offices = $this->input->post('office');
$votes = $this->input->post('vote_id');
$amount = $this->input->post('amount');
$notes = $this->input->post('notes');
$bdate = $this->input->post('budget_date');
for ($x = 0; $x < $count; $x++) {
$details[$x]['budget_id'] = $id;
$details[$x]['office'] = $offices[$x];
$details[$x]['vote_id'] = $votes[$x];
$details[$x]['amount'] = (-1)*$amount[$x];
$details[$x]['notes'] = $notes[$x];
$details[$x]['budget_date'] = $bdate[$x];
$details[$x]['status'] = 1;
}
Now the issue was fixed partially. But the saving vote_id of finance_budget_issue table is incorrect without editing.
I want to use dynamic form widget (wbraganca).
I tried it using the tutorial by 'doingItEasy' channel & also by github.
I can create and delete,but I can't update.:
Controller:
public function actionUpdate($id) {
$model = $this->findModel($id);
$modelsDentalist = $model->dentalists;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsDentalist, 'id', 'id');
$modelsDentalist = Model::createMultiple(Dentalist::classname(), $modelsDentalist);
Model::loadMultiple($modelsDentalist, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsDentalist, 'id', 'id')));
$valid = $model->validate();
$valid = Model::validateMultiple($modelsDentalist) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
CalItem::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsDentalist as $modelDentalist) {
$modelDentalist->denta_id = $model->denta_id;
if (!($flag = $modelDentalist->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['index']);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('update', [
'model' => $model,
'modelsDentalist' => (empty($modelsDentalist)) ? [new Dentalist] : $modelsDentalist
]);
}
}
_From.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\ArrayHelper;
use app\models\School;
use app\models\Schoolclass;
use app\models\Schoolterm;
use app\models\Year;
use app\models\Dentalist;
<div class="denta-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<div class="row">
<div class="alert alert-success" role="alert">
<div class="row">
<div class="col-md-2">
<?=
$form->field($model, 'school_id')->dropDownList(
ArrayHelper::map(School::find()->andWhere('school_type_id in(1,2) ')->all(), 'school_id', 'school_name')
, ['prompt' => 'เลือกรายการ...'])
?>
</div>
<div class="col-md-2">
<?=
$form->field($model, 'school_term_id')->dropDownList(
ArrayHelper::map(Schoolterm::find()->all(), 'school_term_id', 'school_term_name')
, ['prompt' => 'เลือกรายการ...'])
?>
</div>
<div class="col-md-2">
<?=
$form->field($model, 'year')->dropDownList(
ArrayHelper::map(Year::find()->all(), 'year', 'year')
, ['prompt' => 'เลือกรายการ...'])
?>
</div>
</div>
</div>
<div class="row">
<div class="panel panel-default">
<?php // <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> DentA list</h4></div> ?>
<div class="panel-body">
<?php
DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsDentalist[0],
'formId' => 'dynamic-form',
'formFields' => [
'school_class_id',
'student_total',
'deciduous_caries',
'permanent_no',
'permanent_caries',
'gingivitis',
'disorder',
],
]);
?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsDentalist as $i => $modelDentalist): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
<div class="panel-body">
<?php
//necessary for update action.
if (!$modelDentalist->isNewRecord) {
echo Html::activeHiddenInput($modelDentalist, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-2">
<?=
$form->field($modelDentalist, "[{$i}]school_class_id")->dropDownList(
ArrayHelper::map(Schoolclass::find()
->where("school_class_id IN(1,2,3)")
->all(), 'school_class_id', 'school_class_name')
, ['prompt' => 'เลือกรายการ...'])
?>
</div>
<div class="col-sm-2">
<?= $form->field($modelDentalist, "[{$i}]student_total")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-1">
<?= $form->field($modelDentalist, "[{$i}]deciduous_caries")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-2">
<?= $form->field($modelDentalist, "[{$i}]permanent_no")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-1">
<?= $form->field($modelDentalist, "[{$i}]permanent_caries")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-2">
<?= $form->field($modelDentalist, "[{$i}]gingivitis")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-2">
<?= $form->field($modelDentalist, "[{$i}]disorder")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', [ 'class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
JS;
$this->registerJs($script);
?>
</div>
Update.php
<?php
use yii\helpers\Html;
use app\models\DentaList;
/* #var $this yii\web\View */
/* #var $model app\models\Denta */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Denta',
]) . $model->denta_id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Dentas'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->denta_id, 'url' => ['view', 'id' => $model->denta_id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="denta-update">
<h1><?= Html::encode($this->title) ?></h1>
<?=
$this->render('_form', [
'model' => $model,
'modelsDentalist' => $modelsDentalist,
])
?>
</div>
I can't update. Error:Getting unknown property: app\models\Dentalist::id
i think you can edit below line in Controller:
$oldIDs = ArrayHelper::map($modelsDentalist, 'denta_id', 'denta_id');
$modelsDentalist = Model::createMultiple(Dentalist::classname(), $modelsDentalist);
Model::loadMultiple($modelsDentalist, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsDentalist, 'denta_id', 'denta_id')));
and also edit line in _form:
echo Html::activeHiddenInput($modelDentalist, "[{$i}]denta_id");
hello I'm try to insert file in database but don't working
file which I'm upload gives the value 0 in my coloumn lampiran in database
and not file in folder to store my upload
database
id|npp|tgl_pengajuan|ket|status|lampiran|lama|tgl_mulai|tgl_selesai | id_jenis
controller
class Cutidiluar extends CI_Controller {
var $limit=10;
var $offset=10;
var $gallery_path;
var $gallery_path_url;
public function __construct(){
parent::__construct();
$this->gallery_path = realpath(APPPATH . '../asset');
$this->gallery_path_url = base_url().'asset/';
} public function add()
{ if($this->session->userdata('LOGIN')=='TRUE')
{
$this->load->library('form_validation');
$this->load->model('Diluartahunan_Model');
//load uploading file library
$config['upload_path'] = './asset/';
$config['allowed_types'] = 'jpg|png|pdf|jpeg|word';
$this->load->library('upload',$config);
$this->upload->do_upload();
$this->upload->data();
$this->form_validation->set_rules('ket', 'ket');
$this->form_validation->set_rules('lama', 'lama');
$this->form_validation->set_rules('lampiran', 'lampiran');
if ($this->form_validation->run() == false) {
$data['nama'] = $this->Diluartahunan_Model->nama();
$data['view'] = 'Cutidiluar/add';
$data['judul']='';
$this->load->view('index',$data);
}else {
$this->load->model('Cutidiluar_Model');
$this->Cutidiluar_Model->add();
redirect('Cutidiluar');
} }}
Model
public function add() {
$npp = $this->session->userdata('NPP');
$id_jenis = $this->input->post('id_jenis');
$ket = $this->input->post('ket');
$lama = $this->input->post('lama');
$tgl_selesai= date('Y-m-d',strtotime($this->input->post('tgl_selesai')));
$tgl_mulai= date('Y-m-d', strtotime($this->input->post('tgl_mulai')));
$lampiran = $this->input->post('lampiran');
$data = array(
'npp'=> $npp,
'id_jenis'=> $id_jenis,
'tgl_pengajuan' => date('y-m-d'),
'ket' => $ket,
'status' => 'P',
'lampiran'=> $lampiran,
'lama'=> $lama,
'tgl_mulai'=> $tgl_mulai,
'tgl_selesai'=> $tgl_selesai,);
$this->db->insert('Cuti_diluar', $data);}
view
<link rel="stylesheet" href="<?php echo base_url();?>css/themes/jquery.ui.all.css" type="text/css" />
<script>
$(document).ready(function() {
$( ".datepicker" ).datepicker();
});
function save(){
$.ajax({
url:'<?php echo base_url(); ?>Cutidiluar/add/',
type:'POST',
data:$('#frmsave').serialize(),
success:function(data){
if(data!=''){
$( "#infodlg" ).html(data);
$( "#infodlg" ).dialog({ title:"Info...", draggable: false});
} else {
window.location="<?php echo base_url() ?>Cutidiluar";
} } }); }
function confirmdlg(){
$("#confirm").dialog({
resizable: false,
modal: true,
title:"Info...",
draggable: false,
width: 'auto',
height: 'auto',
buttons: {
"Ya": function(){
save();
$(this).dialog("close");
window.location="<?php echo base_url() ?>Cutidiluar";
},
"Tutup": function(){
$(this).dialog("close");
}
}
});
}
</script>
<div class="span6">
<div class="well grey">
<div class="well-header">
<h5>Tambah Cuti </h5>
</div>
<div class="well-content no-search">
<form id="frmsave" name="frmsave" class="form-validate" >
<form id="frmsave" name="frmsave" class="form-validate">
<h3>Detail </h3>
<div class="form_row">
<label class="field_name">Pilih cuti</label>
<div class="field">
<?php foreach ($nama->result() as $valnama) { ?>
<input type="radio" name="id_jenis" value="<?php echo $valnama->id_jenis; ?>"> <?php echo $valnama->nama ?></br></br> <?php } ?>
</div>
</div>
<div class="form_row">
<label class="field_name">Tanggal Pengambilan Cuti</label>
<div class="field">
<input placeholder="TANGGAL MULAI CUTI" class="datepicker" size="16" type="text" name="tgl_mulai" id="tgl_mulai" value="<?php echo set_value('tgl_mulai'); ?>" >
<input placeholder="TANGGAL SELESAI CUTI" class="datepicker" size="16" type="text" name="tgl_selesai" id="tgl_selesai" value="<?php echo set_value('tgl_selesai'); ?>" >
</div>
</div>
<div class="form_row">
<label class="field_name">lama</label>
<div class="field">
<input type="text" name="lama" class="input-large" value="<?php echo set_value('lama'); ?>" placeholder="masukan lama cuti">
</div>
</div>
<div class="form_row">
<label class="field_name">Lampiran</label>
<div class="field">
<input type="file" name="userfile">
</div>
</div>
<div class="form_row">
<label class="field_name">Keterangan (MAKS 50 KARAKTER)</label>
<div class="field">
<textarea placeholder="KETERANGAN CUTI" id="ket" name="ket" class="span12" cols="40" rows="5" value="<?php echo set_value('ket'); ?>"></textarea>
</div>
</div>
<div class="form_row">
<div class="field">
<a onclick="return confirmdlg()" class="blue btn">Submit</a>
Cancel
</div>
</div>
</form>
I have change my view and model
in view
<form id="frmsave" name="frmsave" class="form-validate" enctype="multipart/form-data" >
and this my model
public function add() {
$npp = $this->session->userdata('NPP');
$id_jenis = $this->input->post('id_jenis');
$ket = $this->input->post('ket');
$lama = $this->input->post('lama');
$tgl_selesai= date('Y-m-d', strtotime($this->input->post('tgl_selesai')));
$tgl_mulai= date('Y-m-d', strtotime($this->input->post('tgl_mulai')));
$lampiran = $_FILES['userfile']['name'];
$data = array(
'npp'=> $npp,
'id_jenis'=> $id_jenis,
'tgl_pengajuan' => date('y-m-d'),
'ket' => $ket,
'status' => 'P',
'lampiran'=> $lampiran,
'lama'=> $lama,
'tgl_mulai'=> $tgl_mulai,
'tgl_selesai'=> $tgl_selesai);
and result can't insert to my database
The upload process must be done after the validation, and use $this->upload->display_errors() to see what's wrong :
$this->form_validation->run() === TRUE) {
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$data['errors'] = $this->upload->display_errors(); // <-- HERE
$this->load->view('index', $data);
}
else{
$upload_data = $this->upload->data();
$this->load->model('Cutidiluar_Model');
$this->Cutidiluar_Model->add();
}