首页 > 解决方案 > Button in every row in dynamic form yii2

问题描述

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. enter image description here

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. enter image description here

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.

标签: yii2

解决方案


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


推荐阅读