Search

Oct 16, 2015

Yii: Action Search string by attributes in database table


// Action search User by username or email or firstName or lastName
public function actionSearchUser(){
    $txtUser = Yii::app()->request->getParam('searchUser');
    $txtUser = preg_replace('!\s+!', ' ', $txtUser);
    $searchArr = array();
    if (isset($txtUser) && trim($txtUser) !== "" ) {
        $txtUser = ltrim($txtUser, " ");
        $txtUser = rtrim($txtUser, " ");
        array_push($searchArr, $txtUser);
        foreach(explode(" ",$txtUser) as $item) array_push($searchArr, $item);
    }

    $result = array();
    if (count($searchArr) > 0) {
        foreach($searchArr as $txt) {
            $u = Users::model()->findByAttributes(array("username" =>$txt));
            if (is_null($u)) $u = Users::model()->findByAttributes(array("email" =>$txt));
            if (is_null($u)) $u = Users::model()->findByAttributes(array("firstName" =>$txt));
            if (is_null($u)) $u = Users::model()->findByAttributes(array("lastName" =>$txt));
            if (!is_null($u) && !in_array($u, $result)) {
                array_push($result, $u);
            }
        }
    }
    $this->render('result', array('result' => $result));
}

No comments:

Post a Comment