Craft CMS – New record not inserted in DB

When creating a plugin with Craft CMS one often need to save a record into database, with data coming from a form.

The problem I faced was that the record was not saved, even if it validated and the save function return true.

Looking into mysql queries I saw that the query was an update one and not an insert, let’s see some code first :

Take this controller action for exemple, a very basic exemple without error management for demonstration purpose

public function actionSaveExemple() {
		$data = craft()->request->getPost('fields');
		// Only allow from the front-end.
		if (!craft()->request->isSiteRequest())
			throw new HttpException(404);

		// Grab the data posted data.
		$record = new ExemplePlugin_ExempleRecord();
		$record = $record->populateRecord($data);
			'entry' => $record
		// Save 
And the corresponding service, in charge of db relations :
public function saveExemple(ExemplePlugin_ExempleRecord $exemple) {
 if($exemple->validate()) {
 return true;
 return false;

As I said even if everything was executed without errors, the record did not show in the table.

Using the fact that the query was an update and not an insert, I looked and found that printing



would return false

As of now I do not now what cause this, but the fix is easy, just apply



And voilà, the record shows up in the table.


Author tkt

More posts by tkt

Leave a Reply