Drupal field_settings_form
我在 Drupal 中创建了自己的字段作为地址。它显示诸如街道、号码、邮政编码等信息……到目前为止一切顺利。但由于某种原因,所有字段都是必需的。尽管在 UI 或 Array 中需要进行设置。
所以我想编辑它的field_settings_form。我在 Drupal 核心代码中找到了一个示例,但它对我没有多大帮助。 field_settings 的目标是使字段可见或不可见以及必需或不需要。所以我想出了这段代码(我从 user_reference.module
得到它),
function mymodule_field_settings_form($field, $instance, $has_data) {
$settings = array_keys($field['settings']);
$form = array();
$form['required_fields'] = array(
'#type' => 'checkboxes',
'#title' => t('Required fields'),
'#default_value' => is_array($settings['required_fields'])
? array('required')
: array(),
'#options' => $settings,
);
return $form;
}
但我被困在这里了。有人在这方面有一些经验吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过大量研究和更多的尝试和错误后,我自己发现了这一点。
首先,我需要填写“表单设置”页面,以便我们可以检查该页面是否可见/必需。
在另一个函数中,我声明了这一点。
$element
调用一个返回所有可用元素的函数。它与上面函数中的$options
具有相同的值。如果'required_field'
打开,我们将其设置为必填,如果'visible_field'
未打开,我们取消设置它!我希望这对您有帮助!
After a lot of research and even more trial and error, I found this myself.
First, I need to fill the "Form Settings" page, so we can check whether or not the page should be visible/required.
And in anther function, I stated this.
$element
calls a function which returns all the elements available. It carries the same values as$options
in the function above. If the'required_field'
is on, we make it required, if the'visible_field'
isn't on, we unset it!I hope this helps you!
问题在于,此上下文中的“字段”是整个表单元素的集合,而不是每个单独的表单元素。当需要“字段”时,没有机制可以指定其中是否需要特定的表单元素。
我还没有找到令人满意的解决方案(我现在已经遇到过好几次了),我能做的最好的事情就是使该字段成为不需要的,然后使用
hook_field_validate
做我的那里有“必需”验证。这并不理想,但它有效:The problem is that the 'field' in this context is the collection of form elements as a whole, not each individual form element. When a 'field' is required there's no mechanism for specifying particular form elements within that should be required or not.
I haven't found a satisfactory solution to this yet (I've come up against it several times now), the best I've been able to do is to make the field not required and then hook into validation with
hook_field_validate
and do my 'required' validation there. It's not ideal but it works: