Automatic value in order column of new record

Automatic value in order column of new record

milapmilap Posts: 40Questions: 13Answers: 2
edited June 2021 in RowReorder

Hello,
I am using editor v 2.0.4 and I am looking for best method to restrict users to enter value by them self in order related field of editor form.
I want to create process that is automatic, so the new record will be always "max value + 1"

I have two quick ideas:

1st is to use postCreate and execute custom SQL that is including result from code below and update newly created record:
SELECT IFNULL(MAX(readingOrder)+1, 1) FROM test
But still user needs to enter sth in the filed because RowReorder plugin needs that...
Without that data I am getting
An SQL error occurred: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'readingOrder' at row 1
Maybe setting some default will skip that, but then I need to hide that filed because data will be generic and it will confuse users...

2nd is to use Field Defaults but since it is on JS side, data will be loaded (ajax call? of mentioned select) probably right after the editor window will popup so if 2 users is going to open edit window in the same time, they can finish with same order values
https://editor.datatables.net/examples/simple/fieldDefaults.html

Is there any other more fancy method?

TBH since You have integrated rows order recalculation while deleting some element (except last one) I am surprised that such behavior is not default ;)

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,972Questions: 1Answers: 10,160 Site admin
    Answer ✓

    The first option is the one I would use myself, for exactly the multi-user reason you describe on the second option.

    You have integrated rows order recalculation while deleting some element (except last one) I am surprised that such behavior is not default

    To be honest, I hadn't thought of it! Here is how it can be done:

        ->on( 'preCreate', function ( $editor, $values ) {
            if (! $values['readingOrder']) {
                // If no value submitted, then use the max+1 as the new value
                $next = $editor->db()->sql('select IFNULL(MAX(readingOrder)+1, 1) as next FROM audiobooks')->fetch();
                $editor->field('readingOrder')->setValue($next['next']);
            }
            else {
                // On create update all the other records to make room for our new one
                $editor->db()
                    ->query( 'update', 'audiobooks' )
                    ->set( 'readingOrder', 'readingOrder+1', false )
                    ->where( 'readingOrder', $values['readingOrder'], '>=' )
                    ->exec();
            }
        } )
    

    Allan

  • milapmilap Posts: 40Questions: 13Answers: 2

    Thank You Allan!! It works like a charm! :smiley:

Sign In or Register to comment.