Заставить Meteor Autoform отображать поле ввода только когда что-то выбрано из списка?

У меня есть поле выбора, которое спрашивает пользователя: «Как вы узнали о нас?»

Возможные варианты: Google, Yelp и Другое (укажите).

Как заставить Autoform отображать пустое поле ввода текста, когда выбран параметр «Другое», а также использовать Autoform для проверки содержимого этого поля ввода текста?

common.js:

Schema = {};
Schema.contact = new SimpleSchema({
    name: {
        type: String,
        label: "Your Name",
        max: 50
    },
    email: {
        type: String,
        regEx: SimpleSchema.RegEx.Email,
        label: "E-mail Address"
    },
    subject: {
        type: String,
        label: "Subject",
        max: 1000
    },
    message: {
        type: String,
        label: "Message",
        max: 1000
    },
    referral: {
        type: String,
        allowedValues: ['Google', 'Yelp', 'Other (Please Specify)']
    }
});

contact.js:

Template.Contact.helpers({
  contactFormSchema: function() {
    return Schema.contact;
  }
});

contact.html:

  {{#autoForm schema=contactFormSchema id="contactForm" type="method" meteormethod="sendEmail"}}
  <fieldset>
    <legend>Contact Us</legend>
    {{> afQuickField name="name"}}
    {{> afQuickField name="email"}}
    {{> afQuickField name="subject"}}
    {{> afQuickField name="message" rows=10}}
    {{> afQuickField name="referral" options="allowed"}}
    <div>
      <button type="submit" class="btn btn-primary">Submit</button>
      <button type="reset" class="btn btn-default">Reset</button>
    </div>
  </fieldset>
  {{/autoForm}}

Кроме того, в той части схемы, которая гласит:

referral: {
    type: String,
    allowedValues: ['Google', 'Yelp', 'Other (Please Specify)']
}

Если выбран вариант «Другое», я хочу иметь возможность сохранять строковое значение, которое пользователь вводит непосредственно в referral, и не создавать отдельную именованную запись только для этого ввода.

Любые идеи?

Очевидно, я бы предпочел сделать это «способом автоформовки», а не взламывать что-то вместе с jQuery или прослушивателем событий или чем-то еще.


person fuzzybabybunny    schedule 23.05.2015    source источник


Ответы (1)


Я разобрался. Определенно намного сложнее, чем я думал.

common.js

Schema = {};
Schema.contact = new SimpleSchema({
    name: {
        type: String,
        label: "Your Name",
        max: 50
    },
    email: {
        type: String,
        regEx: SimpleSchema.RegEx.Email,
        label: "E-mail Address"
    },
    subject: {
        type: String,
        label: "Subject",
        max: 1000
    },
    message: {
        type: String,
        label: "Message",
        max: 1000
    },
    referral: {
        type: String,
        allowedValues: ['Google', 'Yelp', 'Other (Please Specify)']
    },
    specificReferral: {
        type: String,
        label: 'Other',
        max: 1000,
        optional: true,
        custom: function(){
          // console.log(this.field('referral').value);
          var customCondition = this.field('referral').value === 'Other (Please Specify)';
          // console.log("this field value: ", this.field('referral').value);
          // console.log("custom condition: ", customCondition);
          if (customCondition && !this.isSet && (!this.operator || (this.value === null || this.value === ""))) {
            return "required";
          }
        }
    }
});

contact.html - ключ к использованию if блоков

          {{#autoForm schema=contactFormSchema id="contactForm" type="method" meteormethod="sendContactEmail"}}
          <fieldset>
            {{> afQuickField name="name"}}
            {{> afQuickField name="email"}}
            {{> afQuickField name="subject"}}
            {{> afQuickField name="message" rows=10}}
            {{> afQuickField name="referral" options="allowed"}}
                {{#if afFieldValueIs name="referral" value="Other (Please Specify)"}}
                    {{> afQuickField name="specificReferral"}}
                {{/if}}
            <div>
              <button type="submit" class="btn btn-primary">Submit</button>
              <button type="reset" class="btn btn-default">Reset</button>
            </div>
          </fieldset>
          {{/autoForm}}

methods.js - check(contents, Schema.contact); является обязательным.

sendContactEmail: function(contents){

    check(contents, Schema.contact);

    // console.log(contents);

    if (!contents.specificReferral){
        contents.specificReferral = '';
    };

    contents.message = contents.message.replace(/\r?\n/g, '<br />');

    return Meteor.Mandrill.send({
      to: '[email protected]',
      from: contents.email,
      subject: contents.subject,
      html: 'A new message has been sent by ' + contents.name + ' and they found us through: ' + contents.referral + ' ' + contents.specificReferral + '<br /><br />' + contents.message
    });

}

contact.js - ловушка обрабатывает обратные вызовы ошибки или успеха от метода meteor для отправки электронного письма - ему требуется идентификатор формы, которую вы генерируете с помощью автоформ.

Template.Contact.helpers({
  contactFormSchema: function() {
    return Schema.contact;
  }
});

Template.Contact.rendered = function(){
    AutoForm.hooks({
      contactForm: {
        onSuccess: function(operation, result, template) {
            // console.log('operation: ', operation);
            // console.log('result: ', result);
            // console.log('template: ', template);
          alert('Thank you for your inquiry! We will get back to you shortly.');
        },
        onError: function(operation, error, template) {
            alert('There was an error with your submission. Please try again.');
        }
      }
    });
};
person fuzzybabybunny    schedule 24.05.2015