[solved] Autoform & Moment.js - how to make them work together?


#1

Situation

I’m using autoform for my forms.

My schema for a date-field looks like this:

mydate: {
  type: Date,
  label: "My Date",
  optional: false
},

Pretty simple.

Problem

When I output the date I’ll get a full date-string like this:

Fri Jan 22 2016 01:00:00 GMT+0100 (CET).

But what I need is only a DD/MM/YYY format.

I’ve read that the easiest way to achieve this is by using the moment.js library.

Okay, but how do I combine autoform and moment.js?
Where do I place something like moment.utc(myDate).format("LL") (from the autoform docs) in my code.
In the schema? Somewhere else?

Thanks a lot for any kind of help!


#2

Think it twice, AutoForm convert schema ‘type Date’ to Html input type Date and this is rendered with a dropdown datepicker.

If you want show stored Date format more friendly, this could be help:

var item = MyCollection.findOne(foo_selector);
var mydate = item && moment(item.mydate).calendar();

#3

Thanks. Worked great.
For completions sake, heres my code:

Template.myTemplate.helpers({
	mydate: function() {
		var currentDocument = myCollection.findOne(this._id);
		var modifiedDate = currentDocument && moment(currentDocument.mydate).format('LL');

		return modifiedDate;
	}
});

Thanks!


#4

Glad it help!

A tiny suggestion. You can get ride of modifiedDate and return ‘currentDocument && …’.
Is more functional, point free.

Bye.


#5

Ah, right! Thanks a lot :slight_smile:


#6

Also you can create your own autoform template for given custom type.
Which can transform it and still work with saving etc.


#7

Hi @nilsdannemann,
This thread seems quite old but I would like to ask where do you put your helpers in your template?

Are you using afQuickfield?

{{> afQuickField name="date" value={{helpers}} }} // this seems not working

or you created a custom type and template?

Thanks!


#8

Hi @ajaxsoap,

sorry for the super late reply. Life went crazy over here.

This is how I have implemented this:

The Helper:

Template.product_formfield_output_wof.helpers({
	wof: function() {
		var currentProduct = Products.findOne(this._id);
		var modifiedDate = currentProduct && moment(currentProduct.wof).format('LL');

		return modifiedDate;
	}
});

The Template:

<template name="product_formfield_output_wof">
	<div class="item">
		<i class="right triangle icon"></i>
		<div class="content">
			<div class="header">WOF</div>
			<div class="description">{{wof}}</div>
		</div>
	</div>
</template>

So I’m not using afQuickFied.

Hope that helps.


#9

I see that you don’t use autoform field to generate the input?

I think i know what to do now.

Thanks @nilsdannemann!