Yii: Capitalise each word in a string and pass it to database

2.8k views Asked by At

I want to capitalise each word in a string

For eg: 'cars and bikes'

to 'Cars and Bikes'

without capitalising 'and','or','of' etc. and after that i want to send the modified string to the database. Please advise me how to do that in Yii 1.1 framework.

My model looks like this

<?php

/**
 * This is the model class for table "master".
 *
 * The followings are the available columns in table 'master':
 * @property integer $book_id
 * @property string $book_name
 * @property string $book_author
 * @property string $book_category
 * @property string $book_publisher
 * @property string $book_pyear
 * @property string $book_location
 * @property string $book_pages
 * @property integer $book_cost
 */
class Books extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'master';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('book_name, book_author, book_category, book_publisher, book_pyear, book_location, book_pages, book_cost', 'required'),
            array('book_cost', 'numerical', 'integerOnly'=>true),
            array('book_name', 'length', 'max'=>50,'min'=>5),
            array('book_author, book_category', 'length', 'max'=>20, 'min'=>3),
            array('book_publisher', 'length', 'max'=>40,'min'=>8),
            array('book_pyear', 'length', 'max'=>4),
            array('book_location', 'length', 'max'=>6),
            array('book_pages', 'length', 'max'=>8),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('book_id, book_name, book_author, book_category, book_publisher, book_pyear, book_location, book_pages, book_cost', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'book_id' => 'ID',
            'book_name' => 'Name',
            'book_author' => 'Author',
            'book_category' => 'Category',
            'book_publisher' => 'Publisher',
            'book_pyear' => 'Published Year',
            'book_location' => 'Location',
            'book_pages' => 'Pages',
            'book_cost' => 'Cost',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('book_id',$this->book_id);
        $criteria->compare('book_name',$this->book_name,true);
        $criteria->compare('book_author',$this->book_author,true);
        $criteria->compare('book_category',$this->book_category,true);
        $criteria->compare('book_publisher',$this->book_publisher,true);
        $criteria->compare('book_pyear',$this->book_pyear,true);
        $criteria->compare('book_location',$this->book_location,true);
        $criteria->compare('book_pages',$this->book_pages,true);
        $criteria->compare('book_cost',$this->book_cost);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Books the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

and controller look like this

<?php

class BooksController 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
            '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'),
                '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()
    {
        $model=new Books;

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

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

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

    }

    /**
     * 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['Books'])) {
            $model->attributes=$_POST['Books'];
            if ($model->save()) {
                $this->redirect(array('view','id'=>$model->book_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)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $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'));
            }
        } else {
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Books');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

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

        $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 $id the ID of the model to be loaded
     * @return Books the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=Books::model()->findByPk($id);
        if ($model===null) {
            throw new CHttpException(404,'The requested page does not exist.');
        }
        return $model;
    }

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

Kindly help me do this for the Book name and book author so that the input looks neat and uniform.

2

There are 2 answers

7
Hearaman On BEST ANSWER

Add bellow method in your controller.

        function doCapitalize($string)
        {
            $exclude = array('and','is','or');
            $words = explode(' ', $string);
            foreach ($words as $key => $word)
            {
                if (in_array($word, $exclude))
                {
                    continue;
                }
                $words[$key] = ucfirst($word);
            }
            $newString = implode(' ', $words);
            return $newString;
        }

Now, operate this method on the $_POST values before assigning them to the model attributes

I'm programing a sample sniplet to create a Book

        $createBook=array();
        foreach($_POST['Book'] as $key=>$val)
        {
            $createBook[$key]=$this->doCapitalize($val);
        }

Assign this new createBook array to your model attributes

        $model->attributes =$createBook;
1
Peon On

If you can make a list of all the words, that don't need to be changed, then I believe it would be the easiest to:

  1. explode the string;
  2. ucfirst all words, if they are not in the don't list;
  3. implode it back.


$dont_list = array( 'and', 'or', 'the' );

$string = 'cars and bikes';

$check = explode( ' ', $string );
$string = array();
foreach( $check as $word ) {
    if ( !in_array( $word, $dont_list ) ) {
        $string[] = ucfirst( $word );
    } else {
        $string[] = $word;
    }
}
$string = implode( ' ', $string );

echo $string;