as: :hidden 不是 input_html_option,而是将输入映射到 Inputs::HiddenInput 类型的input style/type;它所做的只是将输入字段呈现为隐藏列表项。此外,您覆盖 input_html_options 的方式不正确:
# Let's say this is a line in your form input:
input_html: { value: 'Eat plants.' }
# Your code is changing `input_html_options` to be the same as if you'd
# included this in your form input declaration, which doesn't make sense:
input_html: {
value: 'Eat plants.',
input_html: { id: 'editor_field' },
as: :hidden
}
请查看有关您尝试覆盖的方法的文档和源代码:
如果您要覆盖现有 ID,则覆盖的 input_html_options 方法将是这样的:
# Don't recommend
def input_html_options
# Note: this is dangerous because the 'id' attribute should be unique
# and merging it here instead of passing it in the field's `input_html`
# hash forces every input of this type to have the same id
super.merge(id: 'editor_field')
end
假设您确实希望可靠地知道 ID,以便某些 JS 可以找到该元素并将其换出,您可以在声明表单输入时在 input_html 散列中指定它,或者更简洁地使用自动生成的 ID。 ID一般为下划线分隔的对象根键+属性名;所以如果你的表单对象是coffee: { name: 'Goblin Sludge', origin_country: 'Columbia' },我相信默认是f.input :name用id='coffee_name'渲染,f.input :origin_country用id='coffee_origin_country'渲染。您可以通过在呈现的表单上使用 devtools 检查器轻松找出这些内容。
您似乎真的希望覆盖to_html。你需要这样的东西:
# app/input/editor_js_input.rb
class EditorJsInput < Formtastic::Inputs::TextInput
def to_html
input_wrapping do
builder.hidden_field(method, input_html_options)
end
end
end
# Variation that creates a div
class EditorJsInput < Formtastic::Inputs::TextInput
def to_html
input_wrapping do
builder.content_tag(
:div,
'',
style: 'width: 100%; background: white;',
id: "#{input_html_options[:id]}_editor"
) << builder.hidden_field(method, input_html_options)
end
end
end
# Example of what this would generate:
# "<div style=\"width: 100%; background: white;\" id=\"coffee_name_editor\"></div><input maxlength=\"255\" id=\"coffee_name\" value=\"\" type=\"hidden\" name=\"coffee[name]\" />"
# PARTIAL
# This will render the div you have above:
div style: 'width: 100%; background: white;', id: 'editorjs'
# This (or a similar variant of form declaration) will render the form
active_admin_form_for resource do |f|
f.inputs do
f.input :name,
input_html: { value: f.object.name },
as: :editor_js
f.input :origin_country,
input_html: { value: f.object.origin_country },
as: :editor_js
end
end
这应该将f.object.name 的输入构建为类似于<input id="coffee_name" type="hidden" value="Goblin Sludge" name="coffee[name]">(请参阅FormBuilder#hidden_field
其他想法:
- 尝试使用Pry 之类的方法在这些方法中添加绑定,以便更好地了解它们的外观和工作方式。请注意,您需要重新启动服务器才能加载对自定义输入类中覆盖方法的更改。
- 阅读上面引用的文档和Formtastic README;有很多真正可以访问的信息可以在这里帮助你。您还可以从 ActiveAdmin 的文档 here(以及 activeadmin.info 中提供样式元素示例的其他页面)中学习如何呈现 div
- 评估是否需要实现Custom FormBuilder