如何向Select2 Widget添加占位符 - Yii2

时间:2018-05-15 14:28:57

标签: yii2 jquery-select2 dropdown

我正在使用yii2页面,它给我添加占位符或提示选择2小工具的问题。这是我的代码:

<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\datecontrol\DateControl;
use yii\helpers\ArrayHelper;

/**
 * @var yii\web\View $this
 * @var app\models\FinancialAccounts $model
 * @var yii\widgets\ActiveForm $form
 */
?>

<div class="financial-accounts-form">

    <?php $form = ActiveForm::begin(['type' => ActiveForm::TYPE_VERTICAL]); echo Form::widget([

        'model' => $model,
        'form' => $form,
        'columns' => 1,
        'attributes' => [

            'type_id' => ['type' => Form::INPUT_WIDGET, 'widgetClass'=>'\kartik\widgets\Select2', 'options' => ['data'=>ArrayHelper::map(app\models\FinancialAccountType::find()->all(), 'type_id', 'name')]],

            'account_name' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => 'Enter Account Name...', 'maxlength' => 100]],

            'account_code' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => 'Enter Account Code...', 'maxlength' => 10]],

            'parent_id' => ['type' => Form::INPUT_WIDGET, 'widgetClass'=>'\kartik\widgets\Select2', 'options' => ['data'=>ArrayHelper::map(app\models\FinancialAccounts::find()->all(), 'account_id', 'account_name'), 'placeholder' => 'Select a Parent Account...']],

            'description' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => 'Enter Description...', 'maxlength' => 250]],

        ],

    ]);

    echo Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
        ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
    );
    ActiveForm::end(); ?>

</div>

问题在于parent_id属性,因为我无法像大多数教程推荐的那样添加占位符作为选项。每次我尝试,我都会收到错误:

Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: kartik\widgets\Select2::placeholder

有谁知道如何解决这个问题?我的主要问题是,在提交数据时我不能将此选项留空,这是可能性之一。它迫使我提交一个选定的项目。

1 个答案:

答案 0 :(得分:2)

您需要注意的是,如果您仔细按照documentation中的示例操作,占位符需要包含在选项数组中。

import {Button, Tabs} from 'antd';
import * as React from "react";
import {ReactElement} from "react";
import {IBaseComponentProps} from "../BaseComponent/BaseComponent";

const operations = <Button type={"primary"}>Extra Action</Button>;

export interface ITabContent {
  title: string,
  content: ReactElement<any>
}

interface ITabProps extends IBaseComponentProps {
  tabs: ITabContent[]
}

export const Tab: React.SFC<ITabProps> = props => {
  const tabs: any = [];
  props.tabs.forEach((tab: ITabContent, index: number) => {
    tabs.push(<Tabs.TabPane tab={tab.title} key={index}>{tab.content}   </Tabs.TabPane>)
  });
  return (
      <Tabs tabBarExtraContent={operations}>
        {...tabs}
      </Tabs>
  );
};