Search before creating a new record

Hi all.

A beginner’s question. I have a form where users can enter companies. To prevent double entries, I want users to run a search for a unique business number (called ACN in Australia). Only if the company doesn’t exist in the database users should be redirected to the “create new company” form. Otherwise the existing company will be associated automatically with the logged in user in a joint table (setRelationRecords).

What’s the best way to implement this? And should I create two separate actions?

Below the current code of the controller before implementing a search functionality.

Thanks for your help…

public function actionCreate()


		$model=new Company;

		// Uncomment the following line if AJAX validation is needed

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






                    // for every new company, create a new record in the tbl_company_has_tbl_user

                    // with user id of logged in user and company id of newly created company

                    // depends on plugin CSaveRelationsBehavior.php in protected/components, which is loaded in

                    // protected/config/main.php and protected/models/user.php

                    // tblUsers is the name of the relation in this model

                    // tbl_user_id is the field that is not directly linked with this model (tbl_company_id is set automatically)

                    // Yii::app()->user->id is the id of the current user

                    $model->setRelationRecords('users', array('user_id'=>Yii::app()->user->id,));


                            // redirect to previous page

                            // 1. in controller action of previous page, set Yii::app()->user->returnUrl=array('controller/action');

                            // 2. in current page, add $this->redirect(Yii::app()->user->returnUrl)

                            // has to be set in all actions (previous pages) that link to other actions with $this->redirect(Yii::app()->user->returnUrl)

                            // to override stored value in Session







You may want to use the find() function of CActiveRecord to search for existing records. If it returns a value then that is the time it will redirect to the create form. :)