multi-row editing with unique fields

multi-row editing with unique fields

gixxy22gixxy22 Posts: 15Questions: 7Answers: 1

Hi Allan,

having a little problem with multi-row editing when there is a unique field in the table.

I get the error:
An SQL error occurred: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'deals_asdasd' for key 'uniqueName'

I have a unique field that is auto-assigned on a "preEdit"/"preCreate" event which basically joining 2 fields together, and there is a unique key on that column in the database.

->on('preEdit', function ($editor, $id, &$values) {
                $sectionName = $this->_getSectionNameFromId($values['fields']['section']);
                $editor->field('fields.uniqueName')->setValue($sectionName . '_' . $values['fields']['fieldName']);
            })

It doesnt happen when updating single rows, only multi-row editing.

Is there anything I am doing wrong, or any way i can fix this?

many thanks

mike

Answers

  • gixxy22gixxy22 Posts: 15Questions: 7Answers: 1

    I should probably point out that I am not trying to edit either 2 fields that define the unique value, i am attempting to simply change a boolean field on 2 or more rows.

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    Ah - this is something I actually ran into myself relatively recently. What is happening is that preEdit is run for all rows, before any of them are actually inserted into the database! setValue is common to all rows being edited - thus the issue you are having.

    A nice way to address this would be for setValue to be multi-row aware, but I'm afraid it isn't at the moment. That said, one option here is to do:

    ->on('preEdit', function ($editor, $id, &$values) {
      $sectionName = $this->_getSectionNameFromId($values['fields']['section']);
      $val = $sectionName . '_' . $values['fields']['fieldName'];
    
      $values['fields']['uniqueName'] = $val;
    })
    

    It is also possible to use the validatedCreate event to perform a similar action. I've not fully documented that yet - initially I was unsure if it was going to be retained - but it is, so no worries there should you use it.

    I reckon the preEdit one above should do the job nicely though.

    Regards,
    Allan

Sign In or Register to comment.