从yii的不同表中搜索

时间:2014-02-20 09:33:03

标签: javascript php mysql json yii

我是Yii的新手。我基本上有两个计算表。 表格:Mst_customers => model name = masterCustomers,TABLE:mst_nimsoft_host =>型号名称= NimsoftHost 。我在我的视图中有一个下拉列表,其中要求按客户名称搜索主机名。我按客户名称进行默​​认搜索。下面我有一个带有AJAX验证的文本字段。操作是当我输入三个字母时,它必须建议客户名称相似。如果我在下拉列表中选择按主机名搜索,如果我输入三个字母/数字,则必须在mst_nimsoft_host表中检查类似的主机名,我在这里给出了我的代码

我的控制器:

<?php

class NimsoftController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/ticket_console';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete','nimsoftCustomers','Search','Details','UploadCustomers','StaticCi','city2','Customers','CiLink','LoadCustType'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($id)
    {
        $model=new NimsoftHost;
                // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

                $cust_id=$id;

                $criteria = new CDbCriteria;
                $cust_name = MasterCustomers::model()->findByPk($cust_id);

                if(isset($_POST['NimsoftHost']))
        {

            $model->attributes=$_POST['NimsoftHost'];

                        $model->host_customer_id=$id;
                        if($model->save())
                        {
                            $this->redirect(array('view','id'=>$model->host_id));
                        }
        }

        $this->render('create',array(
            'model'=>$model,'cust_id'=>$cust_id,'cust_name'=>$cust_name->cust_name
        ));
    }

        public function actionLoadCustType(){


                $customer_id =  $_POST['NimsoftHost']['host_customer_id'];

                //$customer_id = 3;
                // customer type
                $custDetails =  masterCustomers::model()->findByPk($customer_id);
                $customer_type =  $custDetails->cust_type;

                // get customer service details
                $criteria = new CDbCriteria;
                $serviceDetails = masterCustomerServices::model()->findAllByAttributes(array('cust_id'=>$customer_id,'i_type'=>'im'));

                //$serviceArr = array(array('label'=>'Please Service','value'=>''));
                //$slaArr = array(array('label'=>'Please Select SLA','value'=>''));
                //$blankServices = array();
                //$srtypeArr = array(array('label'=>'Select SR Type','value'=>''));



                foreach($serviceDetails as $val){

                   // get sla name
                   $criteria = new CDbCriteria;
                   $sla = masterSla::model()->findByPk($val->sla_id);
                   $slaArr[] = array(
                    'label'   => $sla->sla_name,
                    'value' => $val->sla_id,
                    );


                   /*// get service type
                   $criteria = new CDbCriteria;
                   $services = masterServiceType::model()->findByPk($val->service_type_id);

                   $blankServices[] = $services->service_type_id;

                   $serviceArr[] = array(
                     'label' =>   $services->service_type_name,
                     'value' =>  $services->service_type_id,
                   );*/
                   //$serviceArr[$val->service_type_id] = $services->service_type_name;

                }

                // customer type
                $custTypeDetails = MasterCustomerType::model()->findByPk($customer_type);

               /* // get sr types
                $criteria = new CDbCriteria;
                $criteria->addCondition("i_type = 'im'", 'AND');
                $criteria->addInCondition('sr_service_type_id',$blankServices);
                $srArr = masterSrTypes::model()->findAll($criteria);

                foreach($srArr as $sr){
                    $srtypeArr[] = array(
                     'label' =>   $sr->sr_type_name,
                     'value' =>  $sr->sr_type_id,
                   );
                }*/


                echo json_encode(array('cust_type'=>$custTypeDetails->cust_type_name,
                                       'customerid'=>md5($customer_id),
                                       //'services'=>$serviceArr,
                                       //'srtypes'=>$srtypeArr,
                                       'slas'=>$slaArr,
                                       'sfdc'=>$custDetails->cust_sfdc_id,
                                       'accountid'=>$custDetails->cust_account_id));

        }

        public function actionDetails($id)
        {
            $this->layout = 'iframe';
            $custid=$id;
            if(isset($custid) && $custid != ''){

                $criteria = new CDbCriteria;
                $criteria->condition = "md5(cust_id) = '$custid'";
                $details = masterCustomers::model()->findAll($criteria);

                // get service & sla Details
                $criteria = new CDbCriteria;
                $criteria->condition = "md5(cust_id) = '$custid'";
                $sdetails = masterCustomerServices::model()->findAll($criteria);

                //get host details
                $criteria = new CDbCriteria;
                $criteria->condition = "md5(host_customer_id) = '$custid'";
                $hostdetails = NimsoftHost::model()->findAll($criteria);

                // get contact details
                $criteria = new CDbCriteria;
                $criteria->condition = "md5(cust_id) = '$custid'";
                $criteria->with = array('contactCategory');
                $contactDetails = masterCustomersContacts::model()->findAll($criteria);


                $this->render('details',array('customer'=>$details,'service'=>$sdetails,'contact'=>$contactDetails,'host'=>$hostdetails));

            }


        }




        public function actionCiLink($action=''){
             $this->layout = 'iframe';
             if(isset($action) && isset($_REQUEST['id'])){
                $id = $_REQUEST['id'];
                 $cis = Yii::app()->user->getState("ci_relations");
                 $temp = array();
                 if(!empty($cis)){
                     foreach($cis as $val){
                         if($id != $val){
                             $temp[] = $val;
                         }
                     }
                     Yii::app()->user->setState("ci_relations",$temp);
                 }
                echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
                exit;
             }

             if(isset($_REQUEST['checkCI'])){

                $ci = $_REQUEST['checkCI'];
                if(Yii::app()->user->hasState("ci_relations")){
                          $existing = Yii::app()->user->getState("ci_relations");
                            foreach($ci as $new){
                                $existing[] = $new;
                            }
                         Yii::app()->user->setState("ci_relations",  array_unique($existing));
                }else{
                    Yii::app()->user->setState("ci_relations",$ci);
                }

                echo '
                                <div style="font-size:12px;font-family:Arial;color:#CCC;">CI Relation added successfully.</div>
                                <script>
                                    var jQuery = parent.jQuery;
                                    setTimeout(function () {
                                          try {
                                             jQuery("#ci_items", window.parent.document).empty().html("please wait loading...");
                                             jQuery("#ci_items", window.parent.document).empty().load("'.$this->createUrl('itsmIncidents/staticCi').'");
                                             parent.window.hs.getExpander().close();
                                          } catch (e) {}
                                       }, 500);
                                </script>                            
                            ';
                    exit;
             }

             $model = new CmdbMaster('customsearch');
             $model->unsetAttributes(); // clear any default values

                if(Yii::app()->request->isAjaxRequest){
                     $inc = $_REQUEST['itsmIncidents']['inc_number'];
                     if (isset($_GET['CmdbMaster'])) {
                         $model->attributes = $_GET['CmdbMaster'];
                     }

                     $this->renderPartial('_ci_form_grid_json', array(
                         'model' => $model,
                         'inc'=> $inc,
                         'pages' => 10
                     ));
                     exit;
                }

             $this->render('_static_ci_form');
        }

        public function actionStaticCi(){
            echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
        }

        /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['NimsoftHost']))
        {
            $model->attributes=$_POST['NimsoftHost'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->host_id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {

            $user = Yii::app()->db->createCommand()
    ->select('cust_name')
    ->from('mst_customers')
    ->queryAll();

       $dataProvider=new CActiveDataProvider('NimsoftHost');
            $model = new NimsoftHost();
            $this->render('sample',array(
            'dataProvider'=>$dataProvider,
                   'user' => $user,
                    'model'=>$model,


        ));



    }

        public function actionCustomers(){
           //header('content-type: application/json; charset=utf-8');
           $select= $_GET['select'];
            $str = $_GET['q'];
           if($select=='Customer_name')
           {
            $criteria = new CDbCriteria();
           $criteria->condition = "( cust_name like '%$str%')";
       $models = masterCustomers::model()->findall($criteria);
           }
           else
           {
            $criteria = new CDbCriteria();
           $criteria->condition = "( host_name like '%$str%')";
       $models = NimsoftHost::model()->findall($criteria);
           }
            $result = array();
            foreach ($models AS $groups) 
                {
                if($groups->cust_account_id != ''){
                    $acc = ' ( '.$groups->cust_account_id.' ) ';
                }
                $result['details'][] = array(
                    'id'   => $groups->cust_id,
                    'name' => $groups->cust_name.$acc,
                );
            }
            echo $_GET['callback'] . "(";
            echo CJSON::encode($result);
            echo ")";


        }




 public function actionUploadCustomers()
                 {
            $this->layout = 'iframe';
            $model = new NimsoftHost;
            if(isset($_POST['NimsoftHost'])){

                $sfile = CUploadedFile::getInstance($model,'upload_file');
                $path = $sfile->tempName;
                $handle = fopen($path,"r");

                if ($handle) {


                $flag = true;
                while(($line = fgetcsv($handle, 1000, ",")) != FALSE) {
                     if($flag) { $flag = false; continue; } // ignore first line


                     $model = new NimsoftHost;
                     $model->host_name = $hostname = trim($line[0]);
                     $model->host_serviceid = $host_serviceid = $line[1];
                     $model->host_customer_id= $host_customer_id = $line[2];
                     $user = Yii::app()->db->createCommand()
    ->select('cust_id')
    ->from('mst_customers')
    ->where('cust_name=:cust_name', array(':cust_name'=>$model->host_customer_id))
    ->queryRow();

                     $model->host_customer_id=$user['cust_id'];
                    if($model->validate() && $model->host_name != ''){
                         $model->save();
                         echo "Uploaded successfully";

                     }
                    else {
                        echo "ALREADY PRESENT";
                    }
                  }        
              }
              fclose($handle);

              exit;

            }

            $this->render('_upload_file',array('model'=>$model));
        }   

       /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new NimsoftHost('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['NimsoftHost']))
            $model->attributes=$_GET['NimsoftHost'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

        public function actionSearch($id){

            echo $cust_id=$id;
            die();
            $criteria = new CDbCriteria();
           $criteria->condition = "md5(host_customer_id) = '$cust_id'";
          $details = NimsoftHost::model()->find($criteria);

          /*if($details)
          {
              $criteria = new CDbCriteria();
           $criteria->condition = "md5(cust_id) = '$id'";
          $details = MasterCustomers::model()->find($criteria);
          $details=$details->cust_id;
          }*/
           $dataProvider=new CActiveDataProvider('NimsoftHost',array(
         'criteria'   => $criteria,));
            $model = new NimsoftHost();
            $this->render('index',array(
            'dataProvider'=>$dataProvider,'details'=>$details));




            /*$this->layout = 'ticket_console';

            $model = new itsmIncidents('search');
            $model->unsetAttributes();

            // Groups details
            $criteria = new CDbCriteria;
            $arrGrp = masterGroups::model()->findall($criteria);

            $arr = array();

            foreach($arrGrp as $e)
            {
                    $arr[$e->group_id]=$e->group_name;
            }

            $arrGrp=$arr;

            // severity types details
            $criteria = new CDbCriteria;
            $arrSvr = masterSeverityType::model()->findall($criteria);

            $arr = array();

            $arr['']='Select Severity';
            foreach($arrSvr as $e)
            {
                    $arr[$e->severity_type_id]=$e->severity_type_name;
            }

            $arrSvr=$arr;

            if(isset($_GET['itsmIncidents']))
            $model->attributes=$_GET['itsmIncidents'];


            if(Yii::app()->request->isAjaxRequest){
                $this->renderPartial('_my_ticket_grid_json',array('dataProvider'=>$model->search()));
            }else{
               $this->render('_mysearch',array(
                        'model'=>$model,
                        'assgroup'=>$arrGrp,
                        'sevArr'=>$arrSvr,
                ));
            }*/
        }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return NimsoftHost the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=NimsoftHost::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param NimsoftHost $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='nimsoft-host-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

我的观点:

<div id="content">
<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'nimsoft-host-form',
    //'enableAjaxValidation'=>true,
        'enableClientValidation' => true,
        'clientOptions' => array(
            'validateOnSubmit' => true,
            'validateOnChange' => true, // allow client validation for every field
         ), 
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>



<div style="float:left;padding-left:20px;">
<select name="search_by" size="1" onchange="javascript:onchange_action()" >
  <option value="Customer_name" selected>Customer Name</option>
  <option value="Host_name" >Host Name</option>
</select>    

                    <?php echo $form->labelEx($model,'host_customer_id'); ?>
                    <?php 
                    $variable=$_POST['search_by'];
                    echo $form->textField($model,'host_customer_id',array('style'=>'width:420px;'));
                    $this->widget('ext.select2.ESelect2', array(
                        'selector' => '#NimsoftHost_host_customer_id',
                        'options' => array(
                            'allowClear'=>false,
                            'placeholder' => 'Search Customers',
                            'minimumInputLength' => 3,
                            'quietMillis'=>100,
                            'ajax' => array(
                                'url' => Yii::app()->createUrl('Nimsoft/customers/'),
                                'dataType' => 'jsonp',
                                'data' => 'js: function('.$variable.',term,page) {
                                        return {
                                            select:'.$variable.'
                                            q: term, 
                                            //ctype: $("#itsmIncidents_cloudcustomer input:radio:checked").val(),
                                            page_limit: 10,
                                        };
                                    }',
                                'results' => 'js: function(data,page){
                                    return {results: data.details};
                                }',
                            ),

                             'formatResult'  => 'js:function(data){
                                return data.name;
                              }',
                            'formatSelection' => 'js: function(data) {
                                return data.name;
                            }',

                        ),
                    ));
                    ?>

                    <div style="float:right">
                            <?php 
                        echo CHtml::link('Manage Hosts', array('/Nimsoft/Search'), array(
                        //'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size",height:500, align: "center" } )',
                            'class'=>'btn btn-block btn-success',
                            'style'=>'width:150px;display:none;',
                            'id'=>'search_details_pop',
                         ));
                        ?>                       
                     </div>
                 </div>


</div>

<script>
function onchange_action()
{
    var e=document.getElementsByName("search_by")[0];
    alert("the value of the option here is "+e.value);
}
$("#NimsoftHost_host_customer_id").on("change", function(e) { 
         <?php echo CHtml::ajax(array(
            'url'=>array('Nimsoft/loadCustType'),
            'data'=> "js:{'NimsoftHost[host_customer_id]':e.val}",
            'type'=>'post',
            'dataType'=>'json',
            'success'=>"function(data)
            {
            // search customer host details
                $('#search_details_pop').css('display','block');
                $('#search_details_pop').attr('href', 'Nimsoft/search/id/'+data.customerid);

            } ",
        ))?>;
     })
</script>

<?php $this->endWidget();?>

我无法执行上述要求。请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这是您问题答案的link

我认为您可以使用自动填充功能。

在链接中,答案将显示给您的方式。有一个actionAutoComplete函数。编辑它,

// if $term first 3 character is numeric
$query = NimsoftHost::model()->findallbyattributes( array('somecolumn'=>$term));
// else 
$query = masterCustomers::model()->findallbyattributes( array('somecolumn'=>$term));

$list = array();        
foreach($query as $q){
    $data['value']= $q['id'];
    $data['label']= $q['name'];

    $list[]= $data;
    unset($data);
}

echo json_encode($list);