0

I've got a CakePHP save method that is saving multiple entries per one save request. I have no idea why -- my AppModel doesn't have any special functions, nor does my AppController. My Controller and Model are pretty basic. Here's what I have:

BalanceSheet Model

<?php
class BalanceSheet extends AppModel {
    var $belongsTo = array(
        'Simulation' => array(
            'foreignKey' => 'simulation_id',
        )
    );
}
?>

BalanceSheets Controller

<?php
class BalanceSheetsController extends AppController {
    function generate($simulation_id) {
        $data = array(
            'BalanceSheet' => array(
                'simulation_id' => $simulation_id,
                'year' => 2004
            )
        );
        $this->BalanceSheet->save($data);
    }
}
?>

Database Schema

CREATE TABLE IF NOT EXISTS `balance_sheets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `simulation_id` int(11) NOT NULL,
  `year` int(11) NOT NULL,
  `buildings_and_improvements` float NOT NULL DEFAULT '0',
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=72 ;

When my balance sheet table is empty, and I navigate to balance_sheets/generate/10, this is the result:

SQL rows

What. What the heck? What's going on there? How can I get it to just save once?

EDIT

Turns out my controller's being called multiple times (I'm not sure why). I'll keep stepping through the debugger to find out what's going on.

Ian Hunter
  • 9,466
  • 12
  • 61
  • 77

1 Answers1

0

Ahhh...figured it out. It was a stylesheet declaration someone had put in the code with an incorrect relative path -- it was passing in "css" as the simulation ID, which is why the duplicate was being inserted as 0!

This was what helped me deduce it (https://stackoverflow.com/a/353493/390977):

Check your layout for non-existent links, for example a misconfigured link to favicon.ico will cause the controller action to be triggered for a second time. Make sure favicon.ico points towards the webroot rather than the local directory, or else requests will be generated for /controller/action/favicon.ico rather than /favicon.ico - and thus trigger your action.

Community
  • 1
  • 1
Ian Hunter
  • 9,466
  • 12
  • 61
  • 77