【问题标题】:Creating Required Fields for Website Forms (Simpleform)为网站表单创建必填字段(简单表单)
【发布时间】:2021-02-02 05:19:16
【问题描述】:

我需要在我的网站上为某些表单添加必填字段,以便更好地验证用户

我打算解决的问题:在网上查找时,我尝试在 views>devise>registrations>new.html.erb 中进行简单的 html 修复,并开始编辑以下代码:

<div class="flex-col md:flex md:flex-row">
      <div class="form-group mb-3 pr-0 md:pr-2">
       <%= f.label :first_name %>
       <%= f.text_field :first_name, autofocus: true, autocomplete: "given-name", class: "form-control"%>
      </div>

我已尝试实现以下功能: :required =&gt; :truerequired: truevalidates :first_name, presence =&gt; true 和其他类似的变体

我还尝试更改 simple_form.rb 文件: config.browser_validations = false= true 以启用对表单字段的验证。 我陷入困境的地方:这些更改都没有破坏本地主机,但也没有改变任何东西。无需输入名字即可执行每个新帐户的创建/注册。我不知道它是simpleform,html还是其他。 以下是我尝试关注的一些链接:

How to make a field required in Rails?

https://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html

Rails: Attribute required for collection in simple_form https://github.com/heartcombo/simple_form(自述文件)

HTML5 'required' validation in Ruby on Rails forms

编辑:User.rb 按要求:

class User < ApplicationRecord
  # acts_as_token_authenticatable

  rolify
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable,
         :trackable, :validatable, :rememberable, :confirmable, :async
  # :omniauthable, omniauth_providers: %i[facebook]
  mount_uploader :logo, AvatarUploader

  attr_accessor :skip_password_validation, :registered_as

  has_many :wishlists
  has_many :projects, dependent: :destroy

  # callbacks
  after_create :assign_role
  after_save :sync_to_active_campaign_contact

  #
  def already_wishlist?(project)
    Wishlist.where(user_id: id, project_id: project.id).exists?
  end

  #
  # def self.from_omniauth(auth)
  #   where(provider: auth.provider, uid: auth.uid).first
  #   # where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
  #   #   user.email = auth.info.email
  #   #   user.skip_password_validation = true
  #   #   # user.password = Devise.friendly_token[0,20]
  #   #   # user.name = auth.info.name   # assuming the user model has a name
  #   #   # user.image = auth.info.image # assuming the user model has an image
  #   #   # If you are using confirmable and the provider(s) you use validate emails,
  #   #   # uncomment the line below to skip the confirmation emails.
  #   #   # user.skip_confirmation!
  #   # end
  # end

  # after_create :send_admin_mail
  # def send_admin_mail
  # ###Send email stuff here
  # end

  #
  def sync_to_active_campaign_contact
    return if Rails.env.development?
    if (confirmed_at.nil? ? false : confirmed_at <= Time.zone.now)

      begin
        fields = {
          'email' => email
        }

        ac_tags = ActiveCampaign.show_tags
        contact_tags = []
        if has_role?(:buyer)
          ac_fields = ActiveCampaign.show_fields
          field_id = ac_fields[:fields].find { |field| field[:title].casecmp?('buyer type') }[:id]
          fields.merge!({ fieldValues: [{
                          field: field_id,
                          value: buyer_type
                        }] }, first_name: first_name, last_name: last_name)
          contact_tags << { contact: "id", tag: ac_tags[:tags].find { |tag| tag[:tag].casecmp?('buyer') }[:id] }
          contact_tags << { contact: "id", tag: ac_tags[:tags].find { |tag| tag[:tag].casecmp?(buyer_type) }[:id] }
        end
        # 1 user can have both roles, using else would crash the logic
        if has_role?(:developer)
          fields.merge!('orgname' => business_name)
          contact_tags << { contact: "id", tag: ac_tags[:tags].find { |tag| tag[:tag].casecmp?('developer') }[:id] }
        end

        ac_contact = ActiveCampaign.sync_contact(fields)
        ac_contact_id = ac_contact.dig(:contact, :id)

        contact_tags.each do |ct|
          contact_tag = ct.merge({ contact: ac_contact_id, tag: ct[:tag] })
          ActiveCampaign.create_contact_tag(contact_tag)
        end
      rescue StandardError
        logger.debug 'unable to sync with active campaign'
      end
    end
  end

  protected

  #
  def password_required?
    return false if skip_password_validation

    super
  end

  #
  def assign_role
    add_role registered_as
  end
end

编辑 2:我还需要从 f.select 选项中包含所需的选择,同时禁用默认的“选择一个”选项:

<div class="form-group mb-3">
            <%= f.label :buyer_type, "Which best describes you: " %>
            <%= f.select :buyer_type, ['Please Select','Option 1', 'Option 2', 'Option 3'], {}, { class: "form-control" } %>
          </div>

【问题讨论】:

  • required: true 选项应该没问题,生成的 HTML 是什么?
  • @eux 对不起,我对一般的编码很陌生 - 你具体需要看什么?
  • 没关系,我的意思是浏览器中first_name字段的最终HTML,类似于&lt;input type="text" id="first_name" name="first_name" required&gt;
  • 此验证属于User 模型(或任何对象为registerable)。 stackoverflow.com/questions/29772931/…
  • 好的,会的!感谢您的帮助以及您的所有帮助@engineersmnky

标签: ruby-on-rails


【解决方案1】:

感谢@engineersmnky 对此的回答:

对于f.text_field问题,添加:

validates :first_name, presence: true
validates :last_name, presence: true

user.rb 将我的名字和姓氏字段设为必填,而不是更改 html。

对于f.select的问题,只需调整html即可解决!

我已经看到了多个对人们有用的堆栈溢出修复,但对我有用的是这个:

<%= f.select :buyer_type, ['Please Select','Option 1', 'Option 2', 'Option 3'], {}, { class: "form-control" } %>

并将其更改为:

<%= f.select :buyer_type, ['Option 1', 'Option 2', 'Option 3'], {include_blank: "Please Select"}, { class: "form-control" , required: 'required'} %>

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多