简体   繁体   中英

Getting null value when trying to get autofull textbox through javascript in Yii2

I'm trying to populate a textbox when a dropdown filed is filled with data. But I'm getting null in result.When I'm passing the 'id' it's returning value but when I'm passing a name it's returning null

Controller

public function actionGetForProduction($catid)
    {
        $bottle = Productnames::findOne($catid);
        echo Json::encode($bottle);
    }

Javascript code in _form

<?php
$script = <<< JS
$('#catid').change(function(){   
    var catid = $(this).val();

     $.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){
        alert(data);

    });
});
JS;
$this->registerJs($script);
?>

screenshot of the error 这里

if you pass parameter to findOne() as string by default it's a primary key field. In your case you have to pass as array like findOne(['catid'=>$catid])

But if you want your controller to accept either id or name then try this:

public function actionGetForProduction()
        {
            if($id=Yii::$app->request->get('id')){
                 $bottle = Productnames::findOne($id);
               }
            elseif($catid=Yii::$app->request->get('catid')){
                 $bottle=Productnames::findOne(['catid'=>$catid]);
               }
            echo Json::encode($bottle);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM