Yii Framework Forum: Check user input - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Check user input Rate Topic: -----

#1 User is offline   dahuzizyd 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 19
  • Joined: 21-June 11

Posted 16 July 2012 - 06:46 AM

Hi All:
I have a normal question here.
In models ,we could use the function 'rules' to check user input ,
Such as this:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('book_name, count', 'required'),
);
}

In my application ,I want to check it by a database value.
For example:

Database : Table name is 'books',an book's count is 5. Now ,an customer buy it for 6,
All I want to do is when customer input 6, application will response a message ,tell him the book count is insufficient.

My native language is not english.I try my best to wrote this.

Thanks for help!
0

#2 User is offline   MadAnd 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 107
  • Joined: 16-June 11
  • Location:Ukraine

Posted 16 July 2012 - 07:12 AM

Hi,

you could write a custom validator, which will check the received qty value against the db:

	public function rules() {
		return array(
			...
			array('quantity', 'quantityValidator'),
			...	
		);
	}
	
	public function quantityValidator($attribute,$params) {
		$availableCount = Yii::app()->db->createCommand()
			->select($attribute)
			->from('books')
			->where('id = :id', array(':id'=>$this->id))
			->queryScalar();
		
		if ( $this->$attribute > $availableCount ) {
			$this->addError('count', 'Your error message here');
		}
	}

0

#3 User is offline   dahuzizyd 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 19
  • Joined: 21-June 11

Posted 16 July 2012 - 10:50 PM

View PostMadAnd, on 16 July 2012 - 07:12 AM, said:

Hi,

you could write a custom validator, which will check the received qty value against the db:

	public function rules() {
		return array(
			...
			array('quantity', 'quantityValidator'),
			...	
		);
	}
	
	public function quantityValidator($attribute,$params) {
		$availableCount = Yii::app()->db->createCommand()
			->select($attribute)
			->from('books')
			->where('id = :id', array(':id'=>$this->id))
			->queryScalar();
		
		if ( $this->$attribute > $availableCount ) {
			$this->addError('count', 'Your error message here');
		}
	}


This solution resolved my problem!
Thanks for your help!
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users