How to do Everything in CakePHP 2.x

Writing Test Case for AuthComponent's login() Function with CakePHP's Mocking

$this->controller = $this->generate('Users', array(
'components' => array('Auth' => array('login')) //Mock all Auth methods
));

//This will make sure that Auth->login() function returns true
$this->controller->Auth->expects($this->once())
->method('login') //The method login()
->will($this->returnValue(true)); //And will return something for meĀ 

Loading other models from AppModel

Use ClassRegistry::init(''anothermodel);


Irregular Naming Convention

Edit app/Config/bootstrap.php and add the following line:
Inflector::rules('plural', array('irregular' => array('staff' => 'staves')));

Expecting exception in CakePHP 2.x Test Case

$this->expectException();
$this->testAction('/controller/action');

Cakephp - Saving to Multiple Models from a Single Form

Controller: $this->Model->saveAll($this->request->data);

View:

echo $this->Form->input('<CURRENT MODEL>.<CURRENT MODEL FIELD>');
echo $this->Form->input('<MODEL A>.0.<MODEL A FIELD>');
echo $this->Form->input('<MODEL B>.0.<MODEL B FIELD>');

Problem Cakephp blank for certain controller actions only

Cause:

  • Extra characters after the php tag "?>"
  • Retrieved text is not in UTF-8

Solutions:

  • Do not close php tag for php only files
  • Remove the extra characters
  • use utf8_encode([text]) function to convert it before returning the data.