admin icon indicating copy to clipboard operation
admin copied to clipboard

Customize Insert data

Open lmquang opened this issue 9 years ago • 2 comments

Hi @jinzhu ,

Can I customize behavior of inserting a model when receive PostForm from admin page ?

lmquang avatar Apr 08 '16 05:04 lmquang

Hi,

You can use a Setter when defining the field's Meta attribute. See the documentation. I have no idea how to use that though. See #60

depado avatar Mar 15 '17 12:03 depado

You use Setter from Meta as @Depado said. Here is a quick example

Setter: func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
	// Get resource as model
	player, ok := resource.(*models.Players)

	if !ok {
		context.AddError(fmt.Errorf("Cannot get player struct from resource at lastlogout meta.Setter"))
		return
	}

	// Get field value
	val, ok := metaValue.Value.([]string)

	// If value does not exists set zero value
	if !ok || len(val) <= 0 {
		return
	}

	// Get string value
	timeValue := val[0]

	// Parse string as time
	t, err := time.Parse("2006-01-02", timeValue)

	if err != nil {
		context.AddError(fmt.Errorf("Cannot parse lastlogout date value"))
		return
	}

	// Get unix timestamp
	player.Lastlogout = t.Unix()
},

This example gets a date field type (1900-02-01) and converts it to a unix timestamp and then its stored in database.

Raggaer avatar Sep 01 '17 17:09 Raggaer