Skip to content

Commit e7b8fce

Browse files
author
Joe McCall
committed
Convert bound data when added to collections
Fixes #11235
1 parent c2b31c7 commit e7b8fce

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

grails-databinding/src/main/groovy/grails/databinding/SimpleDataBinder.groovy

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,8 @@ class SimpleDataBinder implements DataBinder {
344344
} else if(genericType.isEnum() && val instanceof CharSequence) {
345345
def enumValue = convertStringToEnum(genericType, val.toString())
346346
addElementToCollectionAt obj, propName, collectionInstance, index, enumValue
347+
} else {
348+
addElementToCollectionAt obj, propName, collectionInstance, index, convert(genericType, val)
347349
}
348350
} else {
349351
addElementToCollectionAt obj, propName, collectionInstance, index, val

grails-databinding/src/test/groovy/grails/databinding/SimpleDataBinderSpec.groovy

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
*/
1515
package grails.databinding
1616

17-
17+
import grails.databinding.converters.ValueConverter
1818
import grails.databinding.errors.BindingError
1919
import grails.databinding.events.DataBindingListenerAdapter
2020
import org.grails.databinding.converters.DateConversionHelper
@@ -574,6 +574,42 @@ class SimpleDataBinderSpec extends Specification {
574574
widget.listOfLongs == [4L]
575575
widget.listOfLongs.first().getClass() == Long
576576
}
577+
578+
@Issue('https://github.com/grails/grails-core/issues/11235')
579+
void 'Test binding to a list using custom value converters'() {
580+
given:
581+
def binder = new SimpleDataBinder()
582+
def comment = new Comment()
583+
584+
and:
585+
binder.registerConverter(new ValueConverter() {
586+
@Override
587+
boolean canConvert(Object value) {
588+
value instanceof String
589+
}
590+
591+
@Override
592+
Object convert(Object value) {
593+
new Attachment(filename: "$value")
594+
}
595+
596+
@Override
597+
Class<?> getTargetType() {
598+
return Attachment
599+
}
600+
})
601+
602+
when:
603+
binder.bind comment, [
604+
'attachments[0]': 'foo.txt',
605+
'attachments[1]': 'bar.txt'
606+
] as SimpleMapDataBindingSource
607+
608+
then:
609+
comment.attachments.size() == 2
610+
comment.attachments.find { it.filename == 'foo.txt' }
611+
comment.attachments.find { it.filename == 'bar.txt' }
612+
}
577613
}
578614

579615
class Factory {
@@ -642,3 +678,11 @@ class DateCollection {
642678
List<Date> dates
643679
}
644680

681+
class Comment {
682+
Set<Attachment> attachments
683+
}
684+
685+
class Attachment {
686+
String filename
687+
}
688+

0 commit comments

Comments
 (0)