Git Product home page Git Product logo

meteor-autoform-typeahead's Introduction

comerc:autoform-typeahead

An add-on Meteor package for aldeed:autoform. Provides a single custom input type, "typeahead", which renders an input using the typeahead plugin.

Prerequisites

The plugin library must be installed separately.

In a Meteor app directory, enter:

$ meteor add comerc:bs-typeahead
$ meteor add aldeed:autoform

Installation

In a Meteor app directory, enter:

$ meteor add comerc:autoform-typeahead

Usage

Specify "typeahead" for the type attribute of any input. This can be done in a number of ways:

In the schema, which will then work with a quickForm or afQuickFields:

{
  tags: {
    type: String,
    autoform: {
      type: "typeahead",
      afFieldInput: {
        typeaheadOptions: {},
        typeaheadDatasets: {}
      }
    }
  }
}

Or on the afFieldInput component or any component that passes along attributes to afFieldInput:

{{> afQuickField name="tags" type="typeahead"}}

{{> afFormGroup name="tags" type="typeahead"}}

{{> afFieldInput name="tags" type="typeahead"}}

To provide typeahead options, set a typeaheadOptions attribute equal to a helper that returns the options object. Most of the data- attributes that the plugin recognizes should also work.

Basic Usage

You may use autoform.options (instead of typeaheadDatasets) like this example:

{
  tags: {
    type: String,
    autoform: {
      type: "typeahead",
      options: {
        'value1': 'label1',
        'value2': 'label2'
      }
    }
  }
}

Demo

Live

Contributing

Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.

meteor-autoform-typeahead's People

Contributors

comerc avatar marekhattas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

meteor-autoform-typeahead's Issues

Must reload page to let typeahead see newly added values

I try to add this nice plugin to my app. Works well, except one thing - I must reload page to let typeahead see newly added values. Values in my app are taken from collection using this function:

Template.registerHelper("opts", function () {
    return Places.find({}, {
        fields: {
            location: true
        }
    }).map(function (it) {
        return {value: it.location};
    })
});

And as helper they go here:

{{> afQuickField name="location" label="Location" type="typeahead" options=opts}}

Maybe there is any way to fix that?
Thanks!

How to capture typeahead:select event & data?

I would like to capture the event of typeahead:select, how to do it?

And also how to capture the data while typeahead:select?

tried 'typeahead:select .twitter-typeahead' but nothing happen. Please kindly advise. Thanks.

Output limitation

Is there any way to limit the output (let's say to 5) ?
I have this code:
HTML
{{> afQuickField name=current.name class="form-control" type="typeahead"}}

CoffeeScript Simple shema

  ingredients:
    type: [Object]
    optional: true
  'ingredients.$.name':
    type: String
    label: 'ingredient'
    autoform:
      options: ->
        Ingredients.find({}).fetch().map((it) -> {label: it.name})

It works, but when I type, for example, 'a' in input field, it gives me too many results, I need to limit them to 5 or so.

Is there a demo app / example for this plugin?

I am trying to integrate this with autoform but I am not sure what would the function for the dataset look like. I tried to go through the typeahead documents and came across bloodhound engine. Is that relevant here and can we use that suggestion engine? If so, could someone please provide some more information.

Using meteor-autoform-typeahead with autoform-modals

Hi All,

I am trying to add typeahead functionality to my bootstrap modal, using data from a server side method.

HTML

{{#afModal formId="newtransactionform" class="btn btn-sm btn-primary valign_button hspace_button pull-right" collection="transaction" operation="insert" title="Add new transaction" buttonContent="Add" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9" omitFields="portfolio,portfolioowner,entered,enteredby" data-source="search"}}Add new <span aria-hidden="true" class="glyphicon glyphicon-plus"></span>{{/afModal}}

JS

Schema:

    ticker: {
        type: String,
        label: "Ticker",
        max: 200,
        autoform: {
            type: "typeahead",
            afFieldInput: {
                typeaheadOptions: {},
                typeaheadDatasets: {}
            }
        }
    },

Modified example from https://github.com/sergeyt/meteor-typeahead:

Meteor.methods({
        'eqsearch' (query, options) {
            options = options || {};
            // guard against client-side DOS: hard limit to 50
            if (options.limit) {
                options.limit = Math.min(50, Math.abs(options.limit));
            } else {
                options.limit = 50;
            }
            // TODO fix regexp to support multiple tokens
            var regex = new RegExp("^" + query);
            console.log(regex);
            console.log(eqprofile.find({'ticker': {$regex:  regex}}, options).fetch());
            return eqprofile.find({'ticker': {$regex:  regex}}, options).fetch();
        }
    });
    Template.portfoliodetail.helpers({
            'search': function(query, sync, callback) {
            Meteor.call('eqsearch', query, {}, function(err, res) {
            if (err) {
            console.log(err);
            return;
            }
            callback(res.map(function(v){ return {value: v.ticker}; }));
      });
    }
    });

To access the data from the helper i added data-source="search" in the html with no success, whenever a letter is typed in the field on the modal I get this error in my console:
"Uncaught TypeError: Cannot read property 'length' of undefined"

How do I go about having typeahead in my modal with serverside data? If somebody could spot the issue here or point me in the right direction that would be super.

Name is ignored in schema options

I have a field I want to use as a typeahead in my form schemas which is defined as follows:

selected: {
type: String,
label: 'User',
optional: false,
autoform: {
type: "typeahead",
options: function () {
return Users.find({name: {$ne:null}}).map(function (d) {
return {label: d.name, value: d._id};
});
},
}

However when the typeahead is rendered it uses only the value from the returned select options. Is there a way to allow the displayed value to be the label and what is actually submitted be the value? (Similar to a select).

Note: this options syntax is currently what is shown on the auto form 'demo' site for using this plugin

How can one provide typeahead datasouce?

The documentation does not actually specify how one would provide the datasource. I tried the following but I get error that the source is not given.

description: {
        type: String,
        min: 10,
        autoform: {
            type: "typeahead",
            afFieldInput: {
                typeaheadOptions: {},
                typeaheadDatasets: {
                  name: "users",
                  displayKey: "username",
                  source: Meteor.users.find().fetch().map(function(user){ return user.username; })
                }
            }
        }
    }

autoform 5.x Support

hi comerc

You package is currently not compatible with autoform > 4.0.

meteor add comerc:autoform-typeahead
=> Errors while adding packages:

While selecting package versions:
error: conflict: constraint aldeed:[email protected] is not satisfied by 5.1.0.

A pull request waiting for aprovel #2

Regards roman

Please publish on atmosphere

Hello,

Some of your latest commits are not published and fix important issues. Can you publish the master on atmosphere ?

Thx.
Bye

Array of string, removing one item - remove all

I have collection with array of string with typehead:

 models: {
    type: Array,
    optional: true,
    autoform: {
      label: 'Compatible phone model names',
    }
  },

  'models.$': {
    type: String,
    min: 4,
    autoform: {
      type: 'typeahead',
      label: 'Model',
      afFieldInput: {
        typeaheadDatasets: {
          source: function (query, process) {
            Meteor.call('phones-typehead', query, function(err, res) {
              var items = _.map(res || [], mkLabelValue);
              process(items);
            });
          }
        }
      }
    }
  },

All work fine, but when I remove one item (click minus on array autoform) all items removed!

For spy autoform I use

AutoForm.addHooks(null, {
  before: {
    update: function(doc) {
      console.log(doc);
    }
  }
});

And I found $unset.models = "" in console log;

versions:

egrep -i "autoform|comerc" versions
aldeed:[email protected]
comerc:[email protected]
comerc:[email protected]
comerc:[email protected]

My way

I decide to instantiate manually type head, here
I remove comerc:autoform-typeahead and keep only comerc:bs-typeahead:

// schema..
  models: {
    type: Array,
    optional: true,
    autoform: {
      label: 'Compatible phone model names',
    }
  },

  'models.$': {
    type: String,
    min: 4,
    autoform: {
      type: 'text',
      // mark this input as typehead, we use .typehead-here class in
      // Template.afInputText_bootstrap3.onRendered to instantiate typehead
      afFieldInput: {
        class: 'typehead-here'
      }
    }
  },
Template.afInputText_bootstrap3.onRendered(function () {

  var source = function (query, process) {
    Meteor.call('phones-typehead', query, function(err, res) {
      var items = _.map(res || [], function mkLabelValue(it) {
        return {label: it, value: it};
      });
      process(items);
    });
  };

  var options = {
    highlight: true
  };
  var datasets = {
    source: source
  };

  this.$('.typehead-here').typeahead(options, datasets);

});

// Fix null array items
// https://github.com/aldeed/meteor-autoform/issues/840
AutoForm.addHooks(null, {
  before: {
    update: function(doc) {
      _.each(doc.$set, function(value, setter) {

        if (_.isArray(value)) {
          var newValue = _.compact(value);
          doc.$set[setter] = newValue;
        }
      });
      return doc;
    }
  }
});

server method (I keep it here to make example more full)

Meteor.methods({
  'phones-typehead': getPhoneModelsList,
});

function getPhoneModelsList(query) {
  // allow only admin and manager to use this method
  if (! Acl.isManagerById(this.userId) &&
      ! Acl.isAdminById(this.userId)) {
    return [];
  }

  var re = new RegExp(query, 'i');

  // Aggregate using `meteorhacks:aggregate`. 
  // Collection is small so it fast.
  var models = Products.aggregate([
    {$match: {'models.name': re }},    // Match query
    {$unwind: '$models'},       // Unwind array
    {                           // Group for uniqueness
      '$group': {
        _id      : '$models.name',
      }
    },
    {$project: {                // Add slug field for sorting
      models: 1,
      'slug': { '$toLower': '$_id' }
    }},
    {$limit: 10},               // Limit 10
    {$sort: {slug :1}},         // Sorting
    {$project: { _id: 1}}       // Only we need only one field
  ]);

  return _.pluck(models, '_id');
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.