【发布时间】:2020-04-16 09:45:46
【问题描述】:
我有一个插件页面,我在其中添加了一些自定义字段,以便创建一个由动态字段组成的表单。
在我的插件页面上,我有一个带有 field_name 和 type_of_field 的选项组。
如果用户选择“选择”作为字段类型,我想动态添加另一组文本字段来构成选择选项。
//definition of the fields
public function setSettings()
{
$args = array(
array(
'option_group' => 'nsp_form_option_group',
'option_name' => 'nps_form_option',
'callback' => array( $this->form_callbacks, 'formSanitize' )
)
);
$this->settings->setSettings( $args );
}
public function setSections()
{
$args = array(
array(
'id' => 'nsp_form_section',
'title' => 'Form Manager',
'callback' => array( $this->form_callbacks, 'formSectionManager' ),
'page' => 'nsp_form_manager'
)
);
$this->settings->setSections( $args );
}
// define the fields for creating a form field
// name
// type
// required
public function setFields()
{
$args = array(
array(
'id' => 'field_name',
'title' => 'Field Name',
'callback' => array( $this->form_callbacks, 'textField' ),
'page' => 'nsp_form_manager',
'section' => 'nsp_form_section',
'args' => array(
'option_name' => 'nsp_form_option',
'label_for' => 'field_name',
'placeholder' => 'eg. Profession'
)
),
array(
'id' => 'type_of_field',
'title' => 'Type of Field',
'callback' => array( $this->form_callbacks, 'selectField' ),
'page' => 'nsp_form_manager',
'section' => 'nsp_form_section',
'args' => array(
'option_name' => 'nsp_form_option',
'label_for' => 'type_of_field',
'options' => array(
'textfield' => 'Text',
'checkbox' => 'Checkbox',
'radio' => 'Radio buttons',
'select' => 'Select',
'textarea' => 'Textarea'
)
)
),
array(
'id' => 'required',
'title' => 'Required',
'callback' => array( $this->form_callbacks, 'checkboxField' ),
'page' => 'nsp_form_manager',
'section' => 'nsp_form_section',
'args' => array(
'option_name' => 'nsp_form_option',
'label_for' => 'required',
'class' => 'ui-toggle'
)
)
);
$this->settings->setFields( $args );
}
//creation of fields
public function registerCustomFields()
{
// register setting
foreach ( $this->settings as $setting ) {
register_setting( $setting["option_group"], $setting["option_name"], ( isset( $setting["callback"] ) ? $setting["callback"] : '' ) );
}
// add settings section
foreach ( $this->sections as $section ) {
add_settings_section( $section["id"], $section["title"], ( isset( $section["callback"] ) ? $section["callback"] : '' ), $section["page"] );
}
// add settings field
foreach ( $this->fields as $field ) {
add_settings_field( $field["id"], $field["title"], ( isset( $field["callback"] ) ? $field["callback"] : '' ), $field["page"], $field["section"], ( isset( $field["args"] ) ? $field["args"] : '' ) );
}
}
// template
<div class="wrap">
<h1>Form Fields Manager</h1>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'nsp_form_option_group' );
do_settings_sections( 'nsp_form_manager' );
submit_button();
?>
</form>
</div>
我正在考虑做一个 ajax 请求“onchange”并在 php 中创建新字段,但是我将如何更新模板以显示/隐藏字段?
或者其他方法?
【问题讨论】: