忍び歩く男 - SLYWALKER

大阪のこっそりPHPer

2 way Validating a HABTM relationship

方法1 Model Tagに書く

参考: How to validate HABTM data… « nuts and bolts of cakephp

Model Tag
<?php
class Tag extends AppModel {
	public $name = 'Tag';
	public $validate = array(
		'Tag' => array('rule' => array('multiple', array('min' => 1, 'max' => 3))),
	);

	public $hasAndBelongsToMany = array('Post');
}
?>
Controller Posts
<?php
class PostsController extends AppController {
	function add() {

		if(!empty($this->data)) {
			$this->Profile->create();
			$this->Post->Tag->set($this->data);
			if($this->Post->Tag->validates() && $this->Post->save($this->data)) {
				//succsess
			}
		}

		$this->set('tags', $this->Post->Tag->find('list', array('fields'=>array('id', 'tag'))));
	}
}
?>
View Posts add
<?php
echo $form->create('Post', array('action'=>'add'));
echo $form->inputs(array(
	'title',
	'post',
	'Tag' => array('multiple'=>'checkbox'),
);
echo $form->end('Submit');
?>

方法2 Model Postに書く

Model Tag
<?php
class Post extends AppModel {
	public $name = 'Post';
	public $validate = array(
		'Tag' => array('rule' => array('multiple', array('min' => 1, 'max' => 3))),
	);

	public $hasAndBelongsToMany = array('Tag');
	
	function beforeValidate() {
		$this->data['Tag']['Tag'] = $this->data['Post']['Tag'];
		return true;
	}
}
?>
Controller Posts
<?php
class PostsController extends AppController {
	function add() {

		if(!empty($this->data)) {
			$this->Profile->create();
			if($this->Post->save($this->data)) {
				//succsess
			}
		}

		$this->set('tags', $this->Post->Tag->find('list', array('fields'=>array('id', 'tag'))));
	}
}
?>
View Posts add
<?php
echo $form->create('Post', array('action'=>'add'));
echo $form->inputs(array(
	'title',
	'post',
	'Post.Tag' => array('multiple'=>'checkbox'),
);
echo $form->end('Submit');
?>