Opened 7 years ago
Last modified 7 years ago
#44754 new defect (bug)
Error saving data from 'custom fields' of type select / checkbox (multiple) in Attachment Modal
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Future Release | Priority: | normal |
| Severity: | major | Version: | |
| Component: | Media | Keywords: | needs-patch |
| Focuses: | javascript | Cc: |
Description
It's my first ticket, and I have little idea of English, I apologize if I did wrong.
The method used to save the custom fields in the Attache modal, I think, is poorly implemented. The problem comes when you have a field of multiple type (select or checkbox). At the time of parsing the form, the jQuery serializeArray function is used. This returns an array of key / value objects with all the items in the form.
The moment you have a field of multiple type whose name value has '[]', if there are multiple values selected, they are overwritten with the selected item from the list of elements.
Error is located in the _.each of line 72 of the file:
https://core.trac.wordpress.org/browser/trunk/src/js/media/views/attachment-compat.js
65 save: function( event ) {
66 var data = {};
67
68 if ( event ) {
69 event.preventDefault();
70 }
71
72 _.each( **this.$el.serializeArray()**, function( pair ) {
73 data[ pair.name ] = pair.value;
74 });
75
76 this.controller.trigger( 'attachment:compat:waiting', ['waiting'] );
77 this.model.saveCompat( data ).always( _.bind( this.postSave, this ) );
78 },
The result of serializeArray () is
And the result after the _.each is:
As you can see, it deletes all the elements previous to the last one of the same key.
I think the best way to fix it is this:
65 save: function( event ) {
66 var data = {};
67
68 if ( event ) {
69 event.preventDefault();
70 }
71
72 _.each( this.$el.serializeArray(), function( pair ) {
73 if ( $.trim( pair.name ).length ) {
74 if ( typeof( data[ pair.name ] ) == 'object' ) {
75 data[ pair.name ].push( pair.value );
76 } else if ( pair.name.indexOf( '[]' ) > -1 ) {
77 data[ pair.name ] = new Array( pair.value );
78 } else {
79 data[ pair.name ] = pair.value;
80 }
81 }
82 });
83
84 this.controller.trigger( 'attachment:compat:waiting', ['waiting'] );
85 this.model.saveCompat( data ).always( _.bind( this.postSave, this ) );
86 },
By doing this, it would return the following data object:
I explained? I'm very sorry for my English ...
Fernando.



Hi @fobiaxx,
Welcome to Trac! Thanks for the detailed report and for providing a possible solution.