Editing a record results in an Integrity Constraint Violation

Editing a record results in an Integrity Constraint Violation

camerondeckercamerondecker Posts: 7Questions: 2Answers: 1

It would seem that the edit action is just trying to insert a new record rather than doing an update, but I can't tell where the miscommunication is happening. When I click "Update", it gives this error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY', where "3" is the existing ID for the record I'm trying to update.

Here's the JS code:

var authorEdit = new $.fn.dataTable.Editor( {
        ajax: { type: 'POST', url:  'php/author-rest.php'},
        table: "#authors",
        idSrc: "id",
        fields: [ { label: "ID:",name: "Author_ID",type: "readonly"}, 
                  { label: "Author Name:",name: "Author_Name"}, 
                  { label: "Primary Language:",name: "Primary_Lang" }, 
                  { label: "Birth Date:",name: "Birth_Date"}
                ]
    });
           
$("#authors").DataTable({ 
     dom: "Bfrtip",
     ajax: { "url": "php/search.php", "type": "POST", data: { className: "Author"}},
     bLengthChange: false,
     columns: [
         { data: "Author_ID" },
         { data: "Author_Name" },
         { data: "Primary_Lang" },
         { data: "Birth_Date" }
     ],
     select: true,
     buttons: [
        { extend: "create", editor: authorEdit },
        { extend: "edit",   editor: authorEdit },
        { extend: "remove", editor: authorEdit }
    ]

 });

And the PHP code for "author-rest.php":

<?php
include( "../editor/php/DataTables.php" );

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
        DataTables\Editor\Upload,
    DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
$editor = Editor::inst( $db, 'Author','Author_ID')
    ->fields(
        Field::inst( 'Author_ID' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'Author_Name' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'Primary_Lang' ),
        Field::inst( 'Birth_Date' )
    );

$editor
    ->process($_POST)
    ->json();

Any help would be greatly appreciated!

Cameron

Replies

  • camerondeckercamerondecker Posts: 7Questions: 2Answers: 1

    I figured it out! My idSrc needs to match that of the primary key of my record, or it doesn't pass the ID in the AJAX call and it assumes its a new record.

This discussion has been closed.