复选框默认为选中,除非用户取消选中

时间:2012-12-06 20:46:56

标签: php forms wordpress

如何更改下面的php以便检查初始视图,但如果用户取消选中并提交表单,则每次访问表单时都会保持未选中状态(直到他们选择再次检查值) ?

class My_Recent_Posts_Widget extends WP_Widget {

 function form( $instance ) {

     /* form code here...*/

    <input 
     type="checkbox" 
     class="checkbox" 
     id="<?php echo $this->get_field_id("excerpt"); ?>" 
     name="<?php echo $this->get_field_name("excerpt"); ?>"<?php checked( (bool) $instance["excerpt"], true ); ?> 
    />

    /* form code here...*/

   }
}

UPDATE :在输入字段中放置checked =“checked”不是我想要的。原因是每次用户点击取消选中它,在提交后它总是会回来检查。用户取消选中该选项后,在后续访问表单时应保持未选中状态。但是,使用checked = checked可确保始终检查默认状态,无论用户之前是否取消选中此特定项目。

我只需要检查默认值,但是如果用户已经取消选中它,我需要将其粘贴,以便每次打开表单时都取消选中,直到他们选择自己检查一下。我相信答案在于数据库中$ instance [“excerpt”]项的状态。

4 个答案:

答案 0 :(得分:1)

只需输入:checked="checked"

在输入标记内。

答案 1 :(得分:1)

假设我们在这里谈论WordPress,您正在使用:

<?php checked( (bool) $instance["excerpt"], true ); ?> 

因此,将根据$instance["excerpt"]的值检查复选框。

您应该根据需要修改条件,但如果没有看到更多详细信息,这对我们来说很难。

编辑:如果值存储在$instance["excerpt"]中,则应确保数据库中新用户的默认值为选中的值(1,例如)。这样,只要用户不更改它,它就会被检查。

答案 2 :(得分:0)

只需设置选中的属性

即可
<input 
  type="checkbox" 
  class="checkbox" 
  checked="checked" 
  id="<?php echo $this->get_field_id("excerpt"); ?>"
  name="<?php echo $this->get_field_name("excerpt"); ?>"<?php checked( (bool) $instance["excerpt"], true ); ?>
/>

答案 3 :(得分:0)

查看Justin Tadlock的这篇文章:The complete guide to creating widgets in WordPress 2.8

在那里,您将看到在解析表单的参数时,您可以$defaults

function form( $instance ) {

    /* Set up some default widget settings. */
    $defaults = array( 
            'title'    => 'Example'
        ,   'name'     => 'John Doe'
        ,   'sex'      => 'male'
        ,   'show_sex' => true 
    );
    $instance = wp_parse_args( (array) $instance, $defaults );