busqueda en vista admin

En mi clase modelo yo tengo el metodo search, pero el problema es que por ejemplo $this->idnivel es un atributo numerico y si yo hago la busqueda con un texto cualquiera me da error el yii, yo trate de solucionarlo con esto


if(!is_numeric($this->nivel) && $this->nivel!="")

          $this->nivel=-1;

para que me hiciera la busqueda con -1 y me dijera que no se encontraron resultados, pero en el textfield del grid se queda el -1 en vez del texto con que hice la busqueda, alguna idea de como pueda solucionar esto de una forma mejor.


public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('idnivel',$this->idnivel,true);

		$criteria->compare('nivel',$this->nivel);

		$criteria->compare('idpatologia',$this->idpatologia);


		return new CActiveDataProvider(get_class($this), array('criteria'=>$criteria,'pagination'=>array('pageSize'=>10)));

	}

Que tipo de error te tira el framework?

Si es un error de validación el problema esta en las reglas de validación del modelo

rules()

Si es otro error por favor has el esfuerzo de explicarlo bien para ayudarte viejo.

Saludos

este es el error que me da

Error 500: <h1>CDbException</h1>

<p>CDbCommand falló al ejecutar la sentencia SQL: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: la sintaxis de entrada no es válida para el tipo numeric: «lolo». The SQL statement executed was: SELECT COUNT(*) FROM “dat_gradilla” “t” WHERE numero=:ycp0 (C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\db\CDbCommand.php:516)</p><pre>#0 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\db\CDbCommand.php(411): CDbCommand->queryInternal(‘fetchColumn’, 0, Array)

#1 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\db\ar\CActiveRecord.php(1540): CDbCommand->queryScalar()

#2 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CActiveDataProvider.php(176): CActiveRecord->count(Object(CDbCriteria))

#3 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CDataProvider.php(184): CActiveDataProvider->calculateTotalItemCount()

#4 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CActiveDataProvider.php(126): CDataProvider->getTotalItemCount()

#5 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CDataProvider.php(128): CActiveDataProvider->fetchData()

#6 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\zii\widgets\CBaseListView.php(105): CDataProvider->getData()

#7 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\zii\widgets\grid\CGridView.php(264): CBaseListView->init()

#8 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CBaseController.php(140): CGridView->init()

#9 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CBaseController.php(165): CBaseController->createWidget(‘zii.widgets.gri…’, Array)

#10 C:\wamp\www\ataxia\trunk\protected\views\datGradilla\admin.php(65): CBaseController->widget(‘zii.widgets.gri…’, Array)

#11 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CBaseController.php(119): require(‘C:\wamp\www\ata…’)

#12 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CBaseController.php(88): CBaseController->renderInternal(‘C:\wamp\www\ata…’, Array, true)

#13 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(866): CBaseController->renderFile(‘C:\wamp\www\ata…’, Array, true)

#14 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(779): CController->renderPartial(‘admin’, Array, true)

#15 C:\wamp\www\ataxia\trunk\protected\controllers\DatGradillaController.php(265): CController->render(‘admin’, Array)

#16 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\actions\CInlineAction.php(50): DatGradillaController->actionAdmin()

#17 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(300): CInlineAction->runWithParams(Array)

#18 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\filters\CFilterChain.php(134): CController->runAction(Object(CInlineAction))

#19 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\filters\CFilter.php(41): CFilterChain->run()

#20 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(1144): CFilter->filter(Object(CFilterChain))

#21 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\filters\CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))

#22 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\filters\CFilterChain.php(131): CInlineFilter->filter(Object(CFilterChain))

#23 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(283): CFilterChain->run()

#24 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)

#25 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CWebApplication.php(277): CController->run(‘Admin’)

#26 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\web\CWebApplication.php(136): CWebApplication->runController(‘DatGradilla/Adm…’)

#27 C:\wamp\www\ataxia\trunk\yii\yii-1.1.8\framework\base\CApplication.php(158): CWebApplication->processRequest()

#28 C:\wamp\www\ataxia\trunk\index.php(13): CApplication->run()

#29 {main}</pre>

Pienso que el problema esta en tu controlador.

También para que no se consideren estrictamente los tipos de datos todas las búsquedas en tu modelo deberían ser parciales. es decir

$criteria->compare(‘idnivel’,$this->idnivel,true);

$criteria->compare(‘nivel’,$this->nivel,true);

$criteria->compare(‘idpatologia’,$this->idpatologia,true);

Si aun no has solucionado el problema , postea tu controlador, para ver que se puede hacer.

No creo que se problema de la controladora, no obstante lo solucione como mismo postie al principio, pero con un cambio


$nivel =  $this->nivel;

		if(!is_numeric($this->nivel) && $this->nivel!="")

          $nivel=-1;

		$criteria->compare('nivel',$nivel);

lo que utilizo una variable en el compare y asi no modifico el valor de $this->nivel y no me sale el -1 sino el valor con el que busco.


<?php


class DatNivelController 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/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}


	/**

	 * 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','comprobarNivel'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'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($url)

	{

		$model=new DatNivelModel;

		//$this->performAjaxValidation($model);

		

		if( isset($_GET['cerrar']) )// si se seleccionó la opción cerrar

			$this->redirect(array($url));

		else

		if(isset($_POST['DatNivelModel']))

		{

			$arregloNivel = $_POST['name'];

			$cantidad = count($arregloNivel);

			$position = 0;

			

			$temp = $_POST['DatNivelModel']['idpatologia'];

			$model->idpatologia = $temp;

			

			while(($cantidad) > 0){

			    if ($arregloNivel[$position] != null){

					$model=new DatNivelModel();

					$model->nivel = $arregloNivel[$position];

					$model->idpatologia = $temp;

					

					$model->save();

			    }

				$cantidad--;

				$position++;

			}

			

			

			//Almacena un mensaje flash que estará disponible en la página de la vista

			Yii::app()->user->setFlash('success','create');

		    $this->redirect(array($url));//vuelve a la página que hizo la petición

		}

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

	}

	

	

	

	public function actionComprobarNivel(){

	

	  $nivel = $_POST['nivel'];

	  $idpatologia = $_POST['idpatologia'];

	  

	   $criteria=new CDbCriteria;

	   $msgError='Verifique, est&aacute; duplicando los niveles.';

	

	   $criteria->select = '*';

	   $criteria->condition = "idpatologia = '$idpatologia' AND nivel = '$nivel'";

	   

	   $arrNiveles = DatNivelModel::model()->findAll($criteria);

	   $cantN = count($arrNiveles);

	

	   if($cantN != 0)

	      echo(json_encode (array ('success' => true)));

       else

          echo(json_encode (array ('success' => false)));

	

	}


	/**

	 * 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,$url)

	{

		$model=$this->loadModel($id);

        $gradilla = new DatGradillaModel();

		if( isset($_GET['cerrar']) )

			$this->redirect(array($url));

		else

		if(isset($_POST['DatNivelModel']))

		{

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

			

			

			if( $model->save() ){//si salvó

					//Almacena un  mensaje flash que estará disponible en la página de la vista

					Yii::app()->user->setFlash('success','update');

					$this->redirect(array($url));

			}

		}

		

			$criteria = new CDbCriteria;

			$criteria->select = 'idgradilla';

			$criteria->condition = "idnivel = $id";

			

			$arrGradillas = DatGradillaModel::model()->findAll($criteria);

			$cantG = count($arrGradillas);

			

			$muestrasAsoc = 0;


			for($i=0; $i<$cantG;$i++)

			{

				$arrAtrib = $arrGradillas[$i];

				$idgradilla = $arrAtrib['idgradilla'];


				if($gradilla->tieneMuestra($idgradilla)){

				 $muestrasAsoc = 1;

				 break;				}

			}

			

		

			if($muestrasAsoc){				

				Yii::app()->user->setFlash('success','modificar');

				$this->redirect(array($url));			

			}

			else

		    $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)

	{

		if(Yii::app()->request->isPostRequest)

		{	

			$criteria = new CDbCriteria;

			$criteria->select = 'idgradilla';

			$criteria->condition = "idnivel = $id";

			

			$arrGradillas = DatGradillaModel::model()->findAll($criteria);

			$cantG = count($arrGradillas);

			

			$muestrasAsoc = false;


			for($i=0; $i<$cantG;$i++)

			{

				$arrAtrib = $arrGradillas[$i];

				$idgradilla = $arrAtrib['idgradilla'];

				

				$criteria = new CDbCriteria;

				$criteria->select = 'idmuestra';

				$criteria->condition = "idgradilla = $idgradilla AND idmuestra is not null";

				$arrMuestra = DatCeldagradillaModel::model()->findAll($criteria);

				

				$muestra = $arrMuestra[$i]['idmuestra'];

				

				//si 

				if(count($arrMuestra)>0){

				$muestrasAsoc = true;//tiene muestra

				break;

				}

			}

		/*	

			$criteria->select = 'idgradilla';

			$criteria->condition = "idnivel = $id";

			$arrG[0]['idgradilla'] = DatGradillaModel::model()->find($criteria);

			$idGRADILLA = $arrG[0]['idgradilla'];

		*/

			if($muestrasAsoc == true){				

				echo "No se puede eliminar, elemento asociado a una muestra.";				

			}

			else if($this->loadModel($id)->delete())

				echo "true";

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		    }

		    else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

			

			

			

			

			

			

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

	    $model=new DatNivelModel('search');

		$model->unsetAttributes();

		

		if(isset($_GET['DatNivelModel']))

			$model->attributes=$_GET['DatNivelModel'];

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


	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new DatNivelModel('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['DatNivelModel']))

			$model->attributes=$_GET['DatNivelModel'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}


	/**

	 * 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 the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=DatNivelModel::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='dat-nivel-model-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

}