Yii ~ CJuiAutoComplete very complete !

Ecco qui un esempio completamente funzionante di una input text dei comuni italiani, con effetto autocompletamento!

Questo risultato è stato possibile anche grazie a diopralinato per la sua maxy query che genera un discreto database di tutti i comuni italiani, e un grazie và anche a Giuseppe per la sua ottima intro sull’argomento.

Allora partiamo, iniziando a creare le nostre 3 tabelle con PhpMyAdmin (o con cosa preferite) lanciando la query proposta da diopralinato dopodichè passiamo al framework Yii (e riprendendo quello detto da giuseppe qui) ho creato questa struttura:

in protected/controllers/ andiamo a creare un nuovo file ….ntrollers/ComuniItaliaController.php:

<?php class ComuniItaliaController 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='main';

/**
* 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','autocomplete'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','autocomplete'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','autocomplete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * Autocomplete (action)
	 */
	public function actionAutocomplete()
	{
		$results = array();
		$res =array();

		if (isset($_GET['term'])) {
			// http://www.yiiframework.com/doc/guide/database.dao
			$qtxt ="SELECT comuni.id as cid, comuni.nome AS cnome, province.nome AS pnome FROM comuni INNER JOIN province
			ON comuni.id_provincia=province.id
			WHERE comuni.nome LIKE :comune";

			$command =Yii::app()->db->createCommand($qtxt);
			$command->bindValue(":comune", $_GET['term'].'%', PDO::PARAM_STR);
			$res =$command->queryAll();

			foreach($res as $p)
			{
				$results[] = array(
								'label'=>$p['cnome'],
								'value'=>$p['cnome'],
								'id'=>$p['cid'],
							);

			}

		}
		echo CJSON::encode($results);
		Yii::app()->end();
	}

}

poi nel form di immissione (…/views/nome-model/_form.php) andremo a scrivere la nostra input automplete:


<?php
 /**
 * Comune di Residenza
 */

/** Se si tratta di un nuovo inserimento $comune è vuoto altrimenti,
*   se un update carico il valore testuale del comune nella input
*  (assegnandolo come $value a CJuiAutoComplete)

if (!$model->isNewRecord) // in caso di UPDATE carico il comune->nome
 {
 $comune=Comuni::model()->findByPk($model->residenza)->nome;
 }else{
 $comune='';
 }

/* questo controllo nascosto riceverà l'id del comune scelto non il nome*/
 echo $form->hiddenField($model,'residenza',array('id'=>'hidden_residenza_comune_id'));
 echo $form->labelEx($model,'residenza');

 $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
 'id'=>'ac_comuni',
 'name'=>'ac_comuni',
 'value'=>$comune,
 // passo a source quello che produce la action scritta sopra
 'source'=>$this->createUrl('comuniitalia/autocomplete'),
 // additional javascript options for the autocomplete plugin
 'options'=>array(
 'showAnim'=>'fold',
// sull'evento onSelect del controllo passo l'id alla inputhidden di sopra...
 'select' => 'js:function(event, ui){ $("#hidden_residenza_comune_id").val(ui.item.id);}',
 ),
 ));
 ?>

Tags: , , , ,

15 Responses to “Yii ~ CJuiAutoComplete very complete !”

  1. Tyson F. Gautreaux 23 gennaio 2012 at 08:46 #

    nice job you’ve done. Good content and i enjoy spending 15 minutes a day watchin all the new posts. Great job, tnx !!

    • Mitchell 28 gennaio 2012 at 20:01 #

      Fell out of bed feeilng down. This has brightened my day!

      • Vernie 26 maggio 2012 at 05:06 #

        One more thingif u want to cnahge format of date u can put this code for model filepublic function afterFind(){$this->order_date = strtotime($this->order_date);$this->order_date = date( m/d/Y’, $this->order_date);$this->created_at = strtotime($this->created_at);$this->created_at = date( m/d/Y’, $this->created_at);parent::afterFind ();}

  2. Neck pain relief 25 gennaio 2012 at 22:58 #

    Good post. I be taught something more difficult on totally different blogs everyday. It is going to always be stimulating to read content material from different writers and observe slightly something from their store. I’d prefer to use some with the content material on my blog whether you don’t mind. Natually I’ll provide you with a hyperlink on your internet blog. Thanks for sharing.

    • Tay 26 maggio 2012 at 03:24 #

      goo.gl does have an API, but it only supports JSON calls, not plain text like most of the other URL shtrneoers. I will be adding goo.gl to the next major release of the plugin though, all the URL shortener stuff will be built into the leenk.me plugin User Interface.Lew

  3. Lauren Scurry 2 aprile 2012 at 15:36 #

    Many thanks for submitting this. Briefquery, if you don’t object. Where did you purchase your web-site theme? I’m putting up a blog and like yours.

    • admin 2 aprile 2012 at 17:17 #

      Hi Lauren this is Biznizz theme, search with google :) has been so long I forget…

    • Jacie 26 maggio 2012 at 09:54 #

      Until I found this I thought I’d have to spend the day iinsde.

  4. l-theanine 23 aprile 2012 at 22:55 #

    This blog has inspired me to continue focusing on my own blog

  5. Dave Shappel 23 giugno 2012 at 14:47 #

    would you rent ad space (for a banner ad) for my site?

    • admin 24 giugno 2012 at 09:16 #

      what website is it?

  6. famous bail bond arcadia ca 6 luglio 2012 at 05:06 #

    Found your blog from Google, thank you for the great read.

  7. Gabriel Levering 13 novembre 2012 at 01:14 #

    Cooler Post :-) Wo ist der Facebook Button?

  8. url shortner 16 giugno 2013 at 23:33 #

    Its such as you read my thoughts! You seem to know a lot approximately this, like you wrote the e-book in it or something. I think that you could do with some percent to power the message home a bit, however instead of that, this is magnificent blog. A great read. I will certainly be back.

  9. music online free no download 5 marzo 2014 at 17:00 #

    This design is steller! You certainly know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my
    own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had
    to say, and more than that, how you presented
    it. Too cool!

Leave a Reply