Yii2-如何在设置中设置选中和保存复选框?

hl0ma9xz  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(224)

大家好,我有复选框的问题,我必须设置默认情况下被选中,其他人编程这一点,我是新的这段代码,所以如果有人知道如何解决这个问题,我将不胜感激。
下面是我的代码:

use app\settings\SettingsModel;
use app\helpers\Html;
use yii\helpers\ArrayHelper;
use youdate\widgets\ActiveForm;
use trntv\aceeditor\AceEditor;

/** @var $elements array */
/** @var $title string */
/** @var $subTitle string */
/** @var $model SettingsModel */

$message = \Yii::$app->session->getFlash('settings');
?>

<div class="card">
    <div class="card-header">
        <h3 class="card-title"><?= Html::encode($title) ?></h3>
    </div>
    <?php $form = ActiveForm::begin() ?>
    <div class="card-body">
        <?= $this->render('/_alert') ?>

        <?php if (isset($subTitle)): ?>
            <h4 class="mb-5"><?= Html::encode($subTitle) ?></h4>
        <?php endif; ?>

        <?php foreach ($elements as $alias => $element) {
            if (is_callable($element['type'])) {
                echo $element['type']($model, $alias);
            } else {
                switch ($element['type']) {
                    case 'dropdown':
                        echo $form->field($model, $alias)
                            ->dropDownList(is_callable($element['options']) ? $element['options']() : $element['options'], [
                                'prompt' => Yii::t('youdate', '-- Select --'),
                            ])
                            ->hint($element['help']);
                        break;
                    case 'checkboxList':
                        echo $form->field($model, $alias)->checkboxList($element['options'])->hint($element['help']);
                        break;
                    case 'checkbox':
                        echo $form->field($model, $alias)->checkbox(isset($element['options']) ?: [])->hint($element['help']);
                        break;
                    case 'code':
                        echo $form->field($model, $alias)->widget(AceEditor::class, ArrayHelper::merge(isset($element['options']) ? $element['options'] : [], [
                            'mode' => 'php',
                            'containerOptions' => [
                                'style' => 'width: 100%; min-height: 200px'
                            ]
                        ]))->hint($element['help']);;
                        break;
                    default:
                    case 'text':
                        echo $form->field($model, $alias)->hint($element['help']);;
                }
            }
        } ?>
    </div>
    <div class="card-footer d-flex justify-content-end">
        <?= Html::submitButton(Yii::t('youdate', 'Save'), ['class' => 'btn btn-primary']) ?>
    </div>
    <?php $form->end() ?>
</div>```

我试着用这样的东西:

```$model->$alias= true;
echo $form->field($model, $alias)->checkbox(isset($element['options']) ?: [])->hint($element['help']);```

我实现了设置复选框默认选中,但我认为信息必须存储在后台会话中生效,所以只有当我点击提交按钮时才能工作,但我想存储它而不点击按钮。
所以我将分享一些代码下面,这是包含在这个文件。SettingsAction代码:

```<?php

namespace app\settings;

use app\traits\RequestResponseTrait;
use app\traits\SessionTrait;

/**
 * @package app\settings
 */
class SettingsAction extends \yii\base\Action
{
    use RequestResponseTrait, SessionTrait;

    /**
     * @var string
     */
    public $category;
    /**
     * @var string
     */
    public $viewFile;
    /**
     * @var array|callable
     */
    public $viewParams = [];
    /**
     * @var array
     */
    public $items;
    /**
     * @var string
     */
    public $title;

    /**
     * @return string
     * @throws \Exception
     */
    public function run()
    {
        $settingsManager = new SettingsManager($this->category, $this->items);
        $settingsModel = SettingsModel::createModel($this->items);
        $settingsModel->setAttributes($settingsManager->getSetting($settingsModel->getAttributes()));

        if ($settingsModel->load($this->request->post()) && $settingsModel->validate()) {
            $settingsManager->setSetting($settingsModel->getAttributes());
            $this->session->setFlash('settings', 'Settings have been saved');
            return $this->controller->refresh();
        }

        $viewParams = is_callable($this->viewParams) ? call_user_func($this->viewParams) : $this->viewParams;
        $viewParams = array_merge($viewParams, [
            'settingsManager' => $settingsManager,
            'settingsModel' => $settingsModel,
            'items' => $this->items,
            'title' => $this->title,
        ]);

        return $this->controller->render($this->viewFile, $viewParams);
    }
}```

下面是ActiveField的代码:

```<?php

namespace youdate\widgets;

use app\helpers\Html;

/**
 * @package youdate\widgets
 */
class ActiveField extends \yii\widgets\ActiveField
{
    /**
     * @var array
     */
    public $labelOptions = ['class' => 'form-label'];

    /**
     * @param array $options
     * @param bool $enclosedByLabel
     * @return \yii\widgets\ActiveField|ActiveField
     */
    public function checkbox($options = [], $enclosedByLabel = false)
    {
        $options['class'] = 'custom-control-input';

        if (!isset($options['uncheck'])) {
            $this->parts['{uncheck}'] = Html::hiddenInput(Html::getInputName($this->model,$this->attribute), 1);
            $options['uncheck'] = false;
        } else {
            $this->parts['{uncheck}'] = 'true';
        }

        $this->template = '
            {uncheck}
            <label class="custom-control custom-checkbox">
                {input}
                <span class="custom-control-label">{labelText}</span>
            </label>';

        $this->parts['{name}'] = $this->attribute;
        $this->parts['{labelText}'] = $this->model->getAttributeLabel($this->attribute);

        if (isset($options['value'])) {
            $this->parts['{value}'] = $options['value'];
        } else {
            $this->parts['{value}'] = $this->model->{$this->attribute};
        }

        return parent::checkbox($options, $enclosedByLabel);
    }

    /**
     * @param array $options
     * @param bool $enclosedByLabel
     * @return ActiveField
     */
    public function radio($options = [], $enclosedByLabel = true)
    {
        $this->labelOptions['class'] = 'custom-control custom-radio';
        $this->parts['{customInput}'] = Html::activeRadio($this->model, $this->attribute, [
            'class' => 'custom-control-input',
            'label' => false,
        ]);
        $this->radioTemplate = "<label class=\"custom-control custom-radio\">{customInput}<div class=\"custom-control-label\">{labelTitle}\n</div></label>\n{error}\n{hint}";

        return parent::radio($options, $enclosedByLabel);
    }

    /**
     * @param null $label
     * @param array $options
     * @return \yii\widgets\ActiveField
     */
    public function label($label = null, $options = [])
    {
        if ($label !== null) {
            $this->parts['{labelText}'] = $label;
        }
        return parent::label($label, $options);
    }
}```

还有很多文件是通过复选框和设置表单连接的,但我认为这些是最重要的

arknldoa

arknldoa1#

按照你的代码:

  • )->checkbox(isset($element['options']) ?: [])选项通过$element['options'],其中一个数组元素可以是'checked' => 1
  • 也可以硬编码)->checkbox(['checked' => 1])
  • 即使是基于条件,比如说,你的字段的名称,你可以合并$element['options']和你的硬编码['checked' => 1],检查将被覆盖。
  • 一个选项也在case 'checkbox':块内,设置$model->$alias = true

相关问题