MySQL tinyint(1) as PHP boolean

I’ve logged this as a bug already (2572), but if you want your MySQL tinyint(1) columns to be treated as a boolean and therefore generate a checkbox instead of a textfield, you can edit framework/db/schema/mysql/CMysqlColumnSchema.php and replace the extractType() method with this:




	/**

	 * Extracts the PHP type from DB type.

	 * @param string $dbType DB type

	 */

	protected function extractType($dbType)

	{

		if(strncmp($dbType,'enum',4)===0)

			$this->type='string';

		else if(strpos($dbType,'float')!==false || strpos($dbType,'double')!==false)

			$this->type='double';

		else if(strpos($dbType,'tinyint(1)')!==false)

			$this->type='boolean';

		else if(strpos($dbType,'int')===0 && strpos($dbType,'unsigned')===false || preg_match('/(bit|tinyint|smallint|mediumint)/',$dbType))

			$this->type='integer';

		else

			$this->type='string';

	}



Hope this helps!

Thanks …was wondering to to solve it ~

Thanks! This is a great help. I was really surprised when I found that yii didn’t provide support for MySQL booleans/checkbox generation out of the box.

I know there’s some been debate about whether TINYINT(1) should be treated as a boolean since it can actually hold numeric values of -127 to 127. The correct data type for boolean in MySQL (5.0.5 and above) is BIT(1), which can only hold 2 values: 1 and 0.

This means that you can use the following code to support this, and STILL keep using TINYINT(1) for very small numeric values.




        /**

	 * Extracts the PHP type from DB type.

	 * @param string $dbType DB type

	 */

	protected function extractType($dbType)

	{

		if(strncmp($dbType,'enum',4)===0)

			$this->type='string';

		elseif(strpos($dbType,'float')!==false || strpos($dbType,'double')!==false)

			$this->type='double';

		elseif(strpos($dbType,'bit(1)')!==false)

			$this->type='boolean';

		elseif(strpos($dbType,'int')===0 && strpos($dbType,'unsigned')===false || preg_match('/(bit|tinyint|smallint|mediumint)/',$dbType))

			$this->type='integer';

		else

			$this->type='string';

	}



To make the default values for bit fields work you’ll also need the following change to the framework:

(sorry too new to post links)