Krajee

Editable

Thankful to Krajee! BUY A COFFEEor to get more out of us.
Easily set any displayed content as editable in Yii Framework 2.0. This is an enhanced editable widget for Yii 2.0 that allows easy editing of displayed data, using inputs, widgets and more with numerous configuration possibilities. The extension uses the enhanced yii2-popover-x extension by Krajee as a popover modal for editing. This extension does not use any external jQuery plugin like X-Editable, instead it uses its own lean and extensible jQuery editable plugin - that elaborately reuses functionality available within Yii Framework 2.0. The editable widget offers these advanced features:
  • Set any readable markup on your view, DetailView, or GridView to be editable. Refer the EditableColumn details in kartik\grid\GridView for using an editable column in your grid.

  • Provides two display formats for setting up your editable content .

    • Link: Convert the editable content as a clickable link for popover.

    • Button: Do not convert the editable content to a link, but rather display a button beside it for editing content.

  • Ability to render the content as a POPOVER or INLINE.

  • Advanced configurable inline templates for rendering complex content.

  • Uses Yii 2.0 ActiveForm for editing content. Hence all features of Yii ActiveForm, including model validation rules are available.

  • For editing the content, you can configure it to use any of the HTML inputs, or widgets available from kartik-v/yii2-widgets or other input widgets from https://github.com/kartik-v. In addition, you can also use HTML 5 inputs or any custom input widget to edit your content.

  • Entirely control the way the form content is displayed in the popover. By default, the widget displays the input to be edited. In addition, you can place more form fields or markup before and after this default input.

  • Uses AJAX based form submission to process quick editing of data and provide a seamless user experience.

  • Uses advanced features of the yii2-popover-x extension, to control display formats for your editable popover form. This uses the enhanced bootstrap-popover-x end the default editable field by adding more form fields for editing before or after the generated editable input.

  • Configure your own display value irrespective of the value stored internally.

  • Configurable css styles and labels for rendering editable content according to your application or theme.

  • Ability to render and reinitialize automatically the widget via Pjax.

View this complete web tip on how to setup your model, controller, and view with GridView Editable columns to manipulate records.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

Editable supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the Editable::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set Editable::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set Editable::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set Editable::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If Editable::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (Editable::bsVersion property) will override the Yii::$app->params['bsVersion']. If Editable::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, Editable::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-editable extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-editable via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-editable "dev-master"

or add:

"kartik-v/yii2-editable": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

The Editable widget supports all the parameters similar to the \yii\widgets\InputWidget widget. So you should be able to pass properties like model and attribute OR name and value. These properties will be used in rendering the input. In addition, the widget allows you to configure the following properties:
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • pjaxContainerId: string, the identifier for the PJAX widget container if the editable widget is to be rendered inside a PJAX container. This will ensure the PopoverX plugin is initialized correctly after a PJAX request is completed. If this is not set, no re-initialization will be done for pjax.

  • format: string, the display format for the editable. Accepts one of the following values:

    • Editable::FORMAT_LINK or 'link'

    • Editable::FORMAT_BUTTON or 'button'

    Defaults to Editable::FORMAT_LINK if you do not set it as Editable::FORMAT_BUTTON.

  • asPopover: boolean, whether to show the editable input as a popover. Defaults to true. If set to false, it will be rendered inline.

  • inlineSettings: array, the settings for the inline editable when asPopover is false. The following properties are recognized:

    • options: array, the HTML attributes for the div panel container that will enclose the inline content. By default the options will be set to ['class' => 'panel panel-default'].

    • closeButton: string, the markup for rendering the close button to close the inline panel. Note the markup must have the CSS class kv-editable-close to trigger the closure of the inline panel. The closeButton defaults to .

    • templateBefore: string, the template for inline content rendered before the input. Defaults to Editable::INLINE_BEFORE_1.

    • templateAfter: string, the template for inline content rendered after the input. Defaults to Editable::INLINE_AFTER_1.

    Inline Template Settings:

    The following tags in the template will be automatically replaced:

    • '{header}': the header generated via preHeader and header properties.

    • '{buttons}': the form action buttons (submit and reset).

    • '{loading}': the loading indicator.

    • '{close}': the close button to close the inline content as set in inlineSettings['closeButton'].

    The widget offers the following two prebuilt INLINE templates

    TypeTemplate NameMarkup
    Type 1 Editable::INLINE_BEFORE_1
    <div class="kv-editable-form-inline">
        <div class="mb-2">
            {loading}
        </div>
    
    Editable::INLINE_AFTER_1
        <div class="mb-2">
            {buttons}{close}
        </div>
    </div>
    
    Type 2 Editable::INLINE_BEFORE_2
    <div class="panel-heading">
        {close}
        {header}
    </div>
    <div class="panel-body">
    
    Editable::INLINE_AFTER_2
    </div>
    <div class="panel-footer">
        {loading}{buttons}
    </div>
    
  • editableButtonOptions: array, the HTML attributes for the editable button to be displayed when the format has been set to Editable::FORMAT_BUTTON. The following additional options are recognized:

    • label: string, the editable button label. This is not HTML encoded. This defaults to:

      • <i class="fas fa-pencil"></i> for Bootstrap.

      • <i class="fas fa-pencil-alt"></i> for Bootstrap 5.x / 4.x.

    • editableValueOptions: array, the HTML attributes for the editable value displayed.

    • containerOptions: array, the HTML attributes for the editable container.

    • type: string, the contextual type for the popover in which the editable form will be displayed. Refer the Popover widget settings documentation. Must be one of the PopoverX::TYPE constants. Defaults to PopoverX::TYPE_DEFAULT or 'default'.

    • size: string, the size of the popover in which the editable form will be displayed. Refer the Popover widget settings documentation. Must be one of the PopoverX::SIZE constants.

    • placement: string, the placement of the popover in which the editable form will be displayed. Refer the Popover widget settings documentation. Must be one of the PopoverX::PLACEMENT constants.

    • preHeader: string, the header content placed before the header text in the popover dialog. This defaults to:

      • <i class="fas fa-edit"></i> Edit for Bootstrap.

      • <i class="fas fa-edit"></i> Edit for Bootstrap 5.x / 4.x.

    • header: string, the header content displayed in the popover dialog. If not set, this will be auto generated based on the model attribute label or set to null.

    • footer: string, the footer content displayed in the popover dialog. The following special tags/variables will be parsed and replaced in the footer:

      • {buttons}: string, will be replaced with the submit and reset button. If this is set to null or an empty string, it will not be displayed.

    • displayValue: string, the value to be displayed. If not set, this will auto-generated from the attribute value (based on value property if available OR use the attribute value from model). If the attribute value is null, then this will display the value as set in valueIfNull.

    • displayValueConfig: array, the configuration to auto-calculate display value, based on the value of the editable input. This should be a single dimensional array whose keys must match the input value, and the array values must be the description to be displayed. For example, to display user friendly boolean values, you could configure this as [0 => 'Inactive', 1 => 'Active']. If this is set, it will override any value set in displayValue.

    • valueIfNull: string, the value to be displayed if the displayValue is null. Defaults to <em>(not set)</em>. This text is i18n enabled and will be translated based on available translation.

    • contentOptions: array,the HTML attributes for the container enclosing the main content and the editable form in the popover dialog.

    • formClass: string, the class name for the ActiveForm widget to be used. The class must extend from \yii\widgets\ActiveForm. This defaults to \kartik orm\ActiveForm

    • formOptions: array,the configuration options for the ActiveForm widget (for the classname selected in formClass).

      Important

      The formOptions['action'] will be used as the ajax URL to process the editable output. Refer the ajax processing section of this document to understand how to manage the editable data using an ajax response.
    • inputType: string, the input type to render for the editing the input in the editable form. If not provided, this defaults to Editable::INPUT_TEXT. All common input types are supported including widgets. This should be one of the following:

      Inputs

      • Editable::INPUT_HIDDEN or 'hiddenInput'

      • Editable::INPUT_TEXT or 'textInput'

      • Editable::INPUT_PASSWORD or 'passwordInput'

      • Editable::INPUT_TEXTAREA or 'textArea'

      • Editable::INPUT_CHECKBOX or 'checkbox'

      • Editable::INPUT_RADIO or 'radio'

      • Editable::INPUT_LIST_BOX or 'listBox'

      • Editable::INPUT_DROPDOWN_LIST or 'dropDownList'

      • Editable::INPUT_CHECKBOX_LIST or 'checkboxList'

      • Editable::INPUT_RADIO_LIST or 'radioList'

      • Editable::INPUT_HTML5_INPUT or 'input'

      • Editable::INPUT_FILE or 'fileInput'

      • Editable::INPUT_WIDGET or 'widget', use this for any custom widget class to be used

      Widgets

      • Editable::INPUT_DEPDROP or '\kartik\depdrop\DepDrop'

      • Editable::INPUT_SELECT2 or '\kartik\select2\Select2'

      • Editable::INPUT_TYPEAHEAD or '\kartik\widgets\Typeahead'

      • Editable::INPUT_SWITCH or '\kartik\widgets\Switch'

      • Editable::INPUT_SPIN or '\kartik ouchspin\TouchSpin'

      • Editable::INPUT_DATE or '\kartik\widgets\DatePicker'

      • Editable::INPUT_DATERANGE or '\kartik\widgets\DateRangePicker'

      • Editable::INPUT_TIME or '\kartik\widgets\TimePicker'

      • Editable::INPUT_DATETIME or '\kartik\widgets\DateTimePicker'

      • Editable::INPUT_RANGE or '\kartik ange\RangeInput'

      • Editable::INPUT_SORTABLE or '\kartik\sortable\SortableInput'

      • Editable::INPUT_COLOR or '\kartik\color\ColorInput'

      • Editable::INPUT_RATING or '\kartik\widgets\StarRating'

      • Editable::INPUT_FILEINPUT or '\kartik\widgets\FileInput'

      • Editable::INPUT_SLIDER or '\kartik\slider\Slider'

      • Editable::INPUT_MONEY or '\kartik\money\MaskMoney'

      • Editable::INPUT_CHECKBOX_X or '\kartik\checkbox\CheckboxX'

    • widgetClass: string, any custom widget class to use. Will only be used if the inputType is set to Editable::INPUT_WIDGET.

    • autoGuessInput: boolean, to auto guess and detect the base input when the inputType is not a HTML input and is either Editable::INPUT_WIDGET or one of the Krajee widgets. The input attributes are autodetected from Editable::options['options'] for Krajee Input Widgets and Editable::options['options']['options] for \kartik\datecontrol\DateControl widget.

      Important

      If you have a custom input widget, that does not store the options in one of the above, then you need to set the autoGuessInput property to false and manually add a CSS class kv-editable-input to your input field to make the editable work perfectly.
    • data: array, the input data items list if inputType is a dropdown type i.e. one of the following:

      • Editable::INPUT_DROPDOWN_LIST or 'dropDownList'

      • Editable::INPUT_LIST_BOX or 'listBox'

      • Editable::INPUT_CHECKBOX_LIST or 'checkboxList'

      • Editable::INPUT_RADIO_LIST or 'radioList'

    • options: array, the options for the input. If the inputType is one of the HTML inputs, this will capture the HTML attributes. If the inputType is set to Editable::INPUT_WIDGET or set to an input widget from Krajee with the \kartik\ namespace, then this will capture the widget options. For an inputType set as Editable::INPUT_WIDGET, the following additional property must be setup:

      • class: string, the class of the widget to be used.

    • inputFieldConfig: array, the ActiveField configuration, if you are using with model.

    • beforeInput: string | Closure, the content to be placed before the rendered input in the popover dialog. If not set as a string, this can be passed as a callback function of the following signature:

      function ($form, $widget) {
          echo $form->field($widget->model, 'attrib');
      }
      

      where:

      • form: mixed is the active form instance for the editable form.

      • widget: mixed is the current editable widget instance.

    • afterInput: string | Closure, the content to be placed after the rendered input. If not set as a string, this can be passed as a callback function of the following signature:

      function ($form, $widget) {
          echo $form->field($widget->model, 'attrib');
      }
      

      where:

      • form: mixed is the active form instance for the editable form.

      • widget: mixed is the current editable widget instance.

    • showButtons: boolean, whether you wish to automatically display the form submit and reset buttons. Defaults to true.

    • i18n: array, the internalization configuration for this extension. Defaults to:

      [
          'class' => 'yii\i18n\PhpMessageSource',
          'basePath' => '@kveditable/messages',
          'forceTranslation' => true
      ];
      
    • showButtonLabels: boolean, whether you want to show the button labels. Defaults to false.

    • buttonsTemplate: string, the template for rendering the buttons. Defaults to {reset}{submit}. The {reset} tag will be replaced with the reset button, while the {submit} tag will be replaced with the submit button.

    • submitButton: array, the HTML attributes for the form submit button. The following special properties are additionally recognized:

      • icon: string, the icon for the button. This defaults to:

        • <i class="glyphicon glyphicon-ok"></i> for Bootstrap 3.x.

        • <i class="fas fa-check"></i> Edit for Bootstrap 5.x / 4.x.

      • label: string, the label for the button. This is HTML encoded. Defaults to 'Apply' and is translated via yii i18n message files.

    • resetButton: array, the HTML attributes for the form reset button. The following special properties are additionally recognized:

      • icon: string, the icon for the button. This defaults to:

        • <i class="glyphicon glyphicon-ban-circle"></i> Cancel for Bootstrap.

        • <i class="fas fa-ban"></i> Cancel for Bootstrap 5.x / 4.x.

      • label: string, the label for the button. This is HTML encoded. Defaults to 'Reset' and is translated via yii i18n message files.

    • ajaxSettings: array any additional/advanced ajax configuration options to pass to the editable plugin. Refer jquery ajax documentation for details of options you can set here.

    • submitOnEnter: boolean whether to auto submit/save the form on pressing ENTER key. Defaults to true. You can set this to false for inputs like text area.

    • showAjaxErrors: boolean whether to display any ajax processing exceptions or errors. Defaults to true. If set to false, no exception errors will be displayed. The editableAjaxError event is anyway triggered when an ajax processing exception related error is encountered. Note that this property only applies to ajax processing exceptions. Any output messages sent via ajax response OR active form attribute validation errors will still be displayed.

    • encodeOutput: boolean whether to HTML encode the output via javascript after editable update. Defaults to true. Note that this is only applied, if you do not return an output value via your AJAX response action. If you return an output value via AJAX it will not be HTML encoded.

    • pluginEvents: array the Editable jQuery plugin events. You must define events in event-name=>event-function format. All events will be stacked in the sequence. The following events are supported:

      • editableChange: Fired on each editable input change. Returns the following parameters for use in callback:

        • val: the editable input element value

      • editableBeforeSubmit: Fired before submission of ajax form submission request. The following properties are available with the event.

        • jqXHR: the jqXHR object

      • editableSubmit: Fired on each submission/saving of editable form. Returns the value of the input for use in callback.

        • val: the editable input element value

        • form: the editable jquery form element

      • editableReset: Fired on each reset of editable form.

      • editableSuccess: Fired on successful ajax update of the editable input. Returns the value of the input for use in callback.

        • val: the editable input element value

        • form: the editable jquery form element

        • data: the ajax response data object

        • jqXHR: the jqXHR object

      • editableError: Fired on error during ajax update of the editable input. Returns the value of the input for use in callback.

        • val: the editable input element value

        • form: the editable jquery form element

        • data: the ajax response data object

      • editableAjaxError: Fired on ajax processing error during ajax update of the editable input. Returns the following three parameters:

        • jqXHR: the jqXHR object

        • status: the error text status

        • message: the error exception message thrown

      Examples of calling events:

      pluginEvents = [
          "editableChange"=>"function(event, val) { log('Changed Value ' + val); }",
          "editableSubmit"=>"function(event, val, form) { log('Submitted Value ' + val); }",
          "editableBeforeSubmit"=>"function(event, jqXHR) { log('Before submit triggered'); }",
          "editableSubmit"=>"function(event, val, form, jqXHR) { log('Submitted Value ' + val); }",
          "editableReset"=>"function(event) { log('Reset editable form'); }",
          "editableSuccess"=>"function(event, val, form, data) { log('Successful submission of value ' + val); }",
          "editableError"=>"function(event, val, form, data) { log('Error while submission of value ' + val); }",
          "editableAjaxError"=>"function(event, jqXHR, status, message) { log(message); }",
      ];
      

The extension relies on ajax processing for updating the editable value on the server. The extension automatically submits an ajax request for processing when the submit button is clicked in the editable dialog. The following properties are automatically set in the ajax response:

  • type: Defaults to formOptions['method'], which is set to post by default.

  • url: Defaults to formOptions['action'], which is set to the currently loaded url by default.

  • data: Defaults to $form.serialize() - which will basically give you a dump of the entire form in your $_REQUEST (post or get).

  • dataType: Defaults to json. You must return a JSON encoded array response containing the following:

    • output: The value to be updated in the display field. If this is empty or null, the extension will automatically use the value from the form field to update the displayed value.

    • message: The validation error message to be displayed. If this is not empty, the extension will automatically display a validation error for the attribute and abort updating the value.

    The extension automatically returns a variable named hasEditable in your $_REQUEST for your controller action to understand that the ajax response is from the Editable extension. You can check if this variable is set for you to process an ajax response.

Ajax Usage Example
/**
 * STEP 1: SETUP YOUR CONTROLLER ACTION
 */
public function actionEditableDemo() {
    $model = new Demo; // your model can be loaded here
    
    // Check if there is an Editable ajax request
    if (isset($_POST['hasEditable'])) {
        // use Yii's response format to encode output as JSON
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        // store old value of the attribute
        $oldValue = $model->name;
        
        // read your posted model attributes
        if ($model->load($_POST)) {
            // read or convert your posted information
            $value = $model->name;
            
            // validate if any errors
            if ($model->save()) {
                // return JSON encoded output in the below format on success with an empty `message`
                return ['output' => $value, 'message' => ''];
            } else {
                // alternatively you can return a validation error (by entering an error message in `message` key)
                return ['output' => $oldValue, 'message' => 'Incorrect Value! Please reenter.'];
            }
        }
        // else if nothing to do always return an empty JSON encoded output
        else {
            return ['output'=>'', 'message'=>''];
        }
    }
    
    // Else return to rendering a normal view
    return $this->render('view', ['model' => $model]);
}

/**
 * STEP 2: SETUP WIDGET IN VIEW
 * view.php
 */
use kartik\editable\Editable;

echo Editable::begin([
    'model'=>$model, 
    'attribute' => 'name',
    'size' => 'md',
    'format' => 'button',
    'editableValueOptions'=>['class'=>'card p-3']
]);

Important

  • You must return a JSON encoded response in the array format specified above with output and message values. This is important for the AJAX request to be processed and completed successfully.

  • The widget has a method getForm which allows you to retrieve the ActiveForm instance to render additional form fields and complex layouts. These fields would also be passed to your ajax response. Refer the last example in the usage section for understanding.



A simple editable content used without a model and the value defaulting to display value. Note that by default the input type is set to Editable::INPUT_TEXT and the editable format is displayed as a Editable::FORMAT_LINK. Note that when using Krajee Select2 widgets inside popovers - you must set the dropdownParent setting within select2Options['pluginOptions'] to a value of #<EDITABLE_ID>-popover, where <EDITABLE_ID> is your Editable widget id as set in Editable::options['id'].



(not set)
An editable content using the Editable::FORMAT_BUTTON as the editable format. Note that no value is set initially. It uses the Editable::INPUT_DROPDOWN_LIST as the input type for editing. Also displayed editable value can be styled.



An editable content using displayValueConfig to dynamically configure your displayed values and markup based on selected values.



A simple editable content with input type set to Editable::INPUT_TEXTAREA and having a different display value. The editable format is displayed as a Editable::FORMAT_LINK. Note that the submitOnEnter property is set to false so that the text area can capture new lines in input.



Advanced usage with a model attribute with an initial value, including model validation rules. The header is defaulted from the model attribute label. Also, style your editable widget with PopoverX type and size.. A displayValueConfig array is set to auto calculate the display value based on the value. Use the StarRating widget from Krajee for editing content and customize the style of your editable value displayed.



An advanced usage using a datepicker widget from kartik\widgets and additional content rendered after the input using a Closure callback.



A complex usage of the Editable widget that allows you to extend fields in the form before and after the input. Ajax response converts the displayed value from these fields as you need. Note that when using Krajee Select2 widgets inside popovers - you must set the dropdownParent setting within select2Options['pluginOptions'] to a value of #<EDITABLE_ID>-popover, where <EDITABLE_ID> is your Editable widget id as set in Editable::options['id'].



Extension of advanced Editable for usage with complex widgets like DepDrop using dependent data. Note that when using Krajee Select2 widgets inside popovers - you must set the dropdownParent setting within select2Options['pluginOptions'] to a value of #<EDITABLE_ID>-popover, where <EDITABLE_ID> is your Editable widget id as set in Editable::options['id'].
use kartik\editable\Editable;

// A simple editable content used without a model and the value defaulting to display value. 
// Note that by default the input type is set to `Editable::INPUT_TEXT` and the editable format 
// is displayed as a `Editable::FORMAT_LINK`.
echo '<label>Person Name</label><br>';
echo Editable::widget([
    'name'=>'person_name', 
    'asPopover' => true,
    'value' => 'Kartik Visweswaran',
    'header' => 'Name',
    'size'=>'md',
    'options' => ['class'=>'form-control', 'placeholder'=>'Enter person name...']
]);

// An editable content using the `Editable::FORMAT_BUTTON` as the editable format. Note that
// no value is set initially. It uses the `Editable::INPUT_DROPDOWN_LIST` as the input type 
// for editing. Also displayed editable value can be styled.
echo '<label>Province</label><br>';
echo Editable::widget([
    'name'=>'province', 
    'asPopover' => true,
    'header' => 'Province',
    'format' => Editable::FORMAT_BUTTON,
    'inputType' => Editable::INPUT_DROPDOWN_LIST,
    'data'=>$data, // any list of values
    'options' => ['class'=>'form-control', 'prompt'=>'Select province...'],
    'editableValueOptions'=>['class'=>'text-danger']
]);

// An editable content using `displayValueConfig` to dynamically configure your displayed values
// and markup based on selected values.
echo '<label>Status</label><br>' . 
Editable::widget([
    'name'=>'status', 
    'value' => 0,
    'asPopover' => true,
    'header' => 'Status',
    'inputType' => Editable::INPUT_DROPDOWN_LIST,
    'data' => [0 => 'pass', 1 => 'fail', 2 => 'waived', 3 => 'todo'],
    'options' => ['class'=>'form-control', 'prompt'=>'Select status...'],
    'displayValueConfig'=> [
        '0' => '<i class="fas fa-thumbs-up"></i> pass',
        '1' => '<i class="fas fa-thumbs-down"></i> fail',
        '2' => '<i class="fas fa-hourglass"></i> waived',
        '3' => '<i class="fas fa-flag"></i> todo',
    ],
]);

// A simple editable content with input type set to `Editable::INPUT_TEXTAREA` and having 
// a different display value. The editable format is displayed as a `Editable::FORMAT_LINK`.
// Note that the `submitOnEnter` property is set to `false` so that the text area can capture 
// new lines in input.
echo Editable::widget([
    'name'=>'notes', 
    'asPopover' => true,
    'displayValue' => 'more...',
    'inputType' => Editable::INPUT_TEXTAREA,
    'value' => "Raw denim you...",
    'header' => 'Notes',
    'submitOnEnter' => false,
    'size'=>'lg',
    'options' => ['class'=>'form-control', 'rows'=>5, 'placeholder'=>'Enter notes...']
]);

// Advanced usage with a model attribute with an initial value, including model validation rules. 
// The header is defaulted from the model attribute label. A `displayValueConfig` array is set to 
// auto calculate the display value based on the value. Also, style your editable with PopoverX type 
// and size. Use the StarRating widget from Krajee for editing content and customize the style of 
// your editable value displayed.
echo '<label>User Rating</label><br>';
echo Editable::widget([
    'model'=>$model, 
    'attribute' => 'rating',
    'header' => 'User Rating',
    'asPopover' => true,
    'type'=>'success',
    'size'=>'lg',
    'displayValueConfig'=>[
        1=>'One Star',
        2=>'Two Stars',
        3=>'Three Stars',
        4=>'Four Stars',
        5=>'Five Stars',
    ],
    'inputType'=>Editable::INPUT_RATING,
    'editableValueOptions'=>['class'=>'text-success h2']
]);


// An advanced usage using a datepicker widget from kartik\widgets and
// additional content rendered after the input using a Closure callback
echo '<label>Dates</label><br>';
echo Editable::widget([
    'model'=>$model,
    'attribute'=>'begin_date',
    'header' => 'Date Range',
    'asPopover' => true,
    'afterInput'=>function($form, $widget) {
        echo $form->field($widget->model, 'to_date')->widget(\kartik\widgets\DatePicker::classname(), [
            'options'=>['placeholder'=>'To date']
        ])->label(false);
    },
    'size'=>'md',
    'inputType' => Editable::INPUT_DATE,
    'options'=>[
        'options'=>['placeholder'=>'From date']
    ]
]);

// A complex usage of the Editable widget that allows you to extend fields 
// in the form before and after the input. Ajax response converts the displayed
// value from these fields as you need. Note that when using Krajee Select2 widgets
// inside popovers - you must set the `dropdownParent` setting within 
// `select2Options['pluginOptions']` to a value of "#<EDITABLE_ID>-popover", 
// where <EDITABLE_ID> is your Editable widget id as set in Editable::options['id'].

echo '<label>Address</label><br>'; 
$editable = Editable::begin([
    'model'=>$model,
    'attribute'=>'address',
    'asPopover' => true,
    'size'=>'md',
    'displayValue' => '15th Main, OK, 10322',
    'options' => ['id'=> 'editable-01', 'placeholder'=>'Enter location...']
]);
$form = $editable->getForm();
echo Html::hiddenInput('kv-complex', '1');
$editable->afterInput = 
    $form->field($model, 'state_1')->widget(\kartik\select2\Select2::classname(), [
        'data' => $data, // any list of values
        'options' => ['placeholder'=>'Enter state...'],
        'pluginOptions' => [
            'dropdownParent' => '#editable-01-popover', // set this to "#<EDITABLE_ID>-popover" to ensure select2 renders properly within the popover
            'allowClear' => true
        ]
    ]) . "\n" .
    $form->field($model, 'zip_code')->textInput(['placeholder'=>'Enter zip code...']);
Editable::end();

// Extension of advanced Editable for usage with complex widgets like DepDrop using 
// dependent data. Note that when using Krajee Select2 widgets inside popovers - you 
// must set the `dropdownParent` setting within `select2Options['pluginOptions']` to 
// a value of "#<EDITABLE_ID>-popover", where <EDITABLE_ID> is your Editable widget id 
// as set in Editable::options['id']
$editable = Editable::begin([
    'model' => $model,
    'attribute' => 'subcat',
    'asPopover' => true,
    'size' => PopoverX::SIZE_MEDIUM,
    'inputType' => Editable::INPUT_DEPDROP,
    'options' => [
        'type' => DepDrop::TYPE_SELECT2,
        'options' => ['id'=>'subcat-id-p', 'placeholder' => 'Select subcat...'],
        'select2Options' => [
            'pluginOptions' => [
                'dropdownParent' => '#subcat-id-p-popover', // set this to "#<EDITABLE_ID>-popover" to ensure select2 renders properly within the popover
                'allowClear' => true,
            ]
        ],
        'pluginOptions'=>[
            'depends'=>['cat-id-p'],
            'url' => Url::to(['/site/subcat'])
        ]
    ]
]);
$form = $editable->getForm();
// use a hidden input to understand if form is submitted via POST
$editable->beforeInput = Html::hiddenInput('kv-editable-depdrop', 1) . 
    $form->field($model, 'cat')->dropDownList(['' => 'Select cat...'] + Demo::$catList, ['id'=>'cat-id-p'])->label(false) . "\n";
$editable->afterInput = $form->field($model, 'prod')->widget(DepDrop::classname(), [
    'type' => DepDrop::TYPE_SELECT2,
    'options' => ['id'=>'prod-id-p', 'placeholder' => 'Select prod...'],
    'select2Options' => [
        'pluginOptions' => [
            'dropdownParent' => '#prod-id-p-popover', // set this to "#<EDITABLE_ID>-popover" to ensure select2 renders properly within the popover
            'allowClear' => true,
        ]
    ],
    'pluginOptions'=>[
        'depends'=>['cat-id-p', 'subcat-id-p'],
        'url' => Url::to(['/site/prod'])
    ]
])->label(false) . "\n";
Editable::end();


A simple editable content used without a model and the value defaulting to display value. Note that by default the input type is set to Editable::INPUT_TEXT and the editable format is displayed as a Editable::FORMAT_LINK. With asPopover set to false the editable content will be rendered inline using the default type 1 template i.e. Editable::INLINE_BEFORE_1 and Editable::INLINE_AFTER_1.



(not set)
An editable content using the Editable::FORMAT_BUTTON as the editable format. Note that no value is set initially. It uses the Editable::INPUT_DROPDOWN_LIST as the input type for editing. Also displayed editable value can be styled.



An editable content using displayValueConfig to dynamically configure your displayed values and markup based on selected values.



A simple editable content with input type set to Editable::INPUT_TEXTAREA and having a different display value. The editable format is displayed as a Editable::FORMAT_LINK. Note that the submitOnEnter property is set to false so that the text area can capture new lines in input.



Advanced usage with a model attribute with an initial value, including model validation rules. The header is defaulted from the model attribute label. . A displayValueConfig array is set to auto calculate the display value based on the value. Use the StarRating widget from Krajee for editing content and customize the style of your editable value displayed. NOTICE how you can change the INLINE TEMPLATE settings.



An advanced usage using a datepicker widget from kartik\widgets and additional content rendered after the input using a Closure callback.



A complex usage of the Editable widget that allows you to extend fields in the form before and after the input. Ajax response converts the displayed value from these fields as you need. In addition to setting INLINE TEMPLATES, you can also alter the styling (e.g. size) of your content container.



Extension of advanced Editable for usage with complex widgets like DepDrop using dependent data. Note that when using Krajee Select2 widgets inside popovers - you must set the dropdownParent setting within select2Options['pluginOptions'] to a value of #<EDITABLE_ID>-popover, where <EDITABLE_ID> is your Editable widget id as set in Editable::options['id'].
use kartik\editable\Editable;

// A simple editable content used without a model and the value defaulting to display value. 
// Note that by default the input type is set to `Editable::INPUT_TEXT` and the editable format 
// is displayed as a `Editable::FORMAT_LINK`. With `asPopover` set to `false` the editable  
// content will be rendered inline using the default template `Editable::INLINE_BEFORE_1` and 
// `Editable::INLINE_AFTER_1`.
echo '<label>Person Name</label><br>';
echo Editable::widget([
    'name'=>'person_name', 
    'asPopover' => false,
    'value' => 'Kartik Visweswaran',
    'header' => 'Name',
    'size'=>'md',
    'options' => ['class'=>'form-control', 'placeholder'=>'Enter person name...']
]);

// An editable content using the `Editable::FORMAT_BUTTON` as the editable format. Note that
// no value is set initially. It uses the `Editable::INPUT_DROPDOWN_LIST` as the input type 
// for editing. Also displayed editable value can be styled.
echo '<label>Province</label><br>';
echo Editable::widget([
    'name'=>'province', 
    'asPopover' => false,
    'header' => 'Province',
    'format' => Editable::FORMAT_BUTTON,
    'inputType' => Editable::INPUT_DROPDOWN_LIST,
    'data'=>$data, // any list of values
    'options' => ['class'=>'form-control', 'prompt'=>'Select province...'],
    'editableValueOptions'=>['class'=>'text-danger']
]);

// An editable content using `displayValueConfig` to dynamically configure your displayed values
// and markup based on selected values.
echo '<label>Status</label><br>' . 
Editable::widget([
    'name'=>'status', 
    'value' => 0,
    'asPopover' => false,
    'header' => 'Status',
    'inputType' => Editable::INPUT_DROPDOWN_LIST,
    'data' => [0 => 'pass', 1 => 'fail', 2 => 'waived', 3 => 'todo'],
    'options' => ['class'=>'form-control', 'prompt'=>'Select status...'],
    'displayValueConfig'=> [
        '0' => '<i class="fas fa-thumbs-up"></i> pass',
        '1' => '<i class="fas fa-thumbs-down"></i> fail',
        '2' => '<i class="fas fa-hourglass"></i> waived',
        '3' => '<i class="fas fa-flag"></i> todo',
    ],
]);

// A simple editable content with input type set to `Editable::INPUT_TEXTAREA` and having 
// a different display value. The editable format is displayed as a `Editable::FORMAT_LINK`.
// Note that the `submitOnEnter` property is set to `false` so that the text area can capture 
// new lines in input.
echo Editable::widget([
    'name'=>'notes', 
    'asPopover' => false,
    'displayValue' => 'more...',
    'inputType' => Editable::INPUT_TEXTAREA,
    'value' => "Raw denim you...",
    'header' => 'Notes',
    'submitOnEnter' => false,
    'options' => [
        'class'=>'form-control', 
        'rows'=>5, 
        'style'=>'width:400px', 
        'placeholder'=>'Enter notes...'
    ]
]);

// Advanced usage with a model attribute with an initial value, including model validation rules. 
// The header is defaulted from the model attribute label. A `displayValueConfig` array is set to 
// auto calculate the display value based on the value. Also, style your editable with PopoverX type 
// and size. Use the StarRating widget from Krajee for editing content and customize the style of 
// your editable value displayed. NOTICE how you can change the INLINE TEMPLATE settings.
echo '<label>User Rating</label><br>';
echo Editable::widget([
    'model'=>$model, 
    'attribute' => 'rating_1',
    'header' => 'User Rating',
    'asPopover' => false,
    'inlineSettings' => [
        'templateBefore' => Editable::INLINE_BEFORE_2, 
        'templateAfter' =>  Editable::INLINE_AFTER_2
    ],
    'displayValueConfig'=>[
        1=>'One Star',
        2=>'Two Stars',
        3=>'Three Stars',
        4=>'Four Stars',
        5=>'Five Stars',
    ],
    'inputType'=>Editable::INPUT_RATING,
    'editableValueOptions'=>['class'=>'text-success h2']
]);


// An advanced usage using a datepicker widget from kartik\widgets and
// additional content rendered after the input using a Closure callback
echo '<label>Dates</label><br>';
echo Editable::widget([
    'model'=>$model,
    'attribute'=>'from_date',
    'header' => 'Date Range',
    'asPopover' => false,
    'inlineSettings' => [
        'templateBefore' => Editable::INLINE_BEFORE_2, 
        'templateAfter' =>  Editable::INLINE_AFTER_2
    ],
    'afterInput'=>function($form, $widget) {
        echo $form->field($widget->model, 'to_date')->widget(\kartik\widgets\DatePicker::classname(), [
            'options'=>['placeholder'=>'To date']
        ])->label(false);
    },
    'size'=>'md',
    'inputType' => Editable::INPUT_DATE,
    'options'=>[
        'options'=>['placeholder'=>'From date']
    ]
]);

// A complex usage of the Editable widget that allows you to extend fields 
// in the form before and after the input. Ajax response converts the displayed
// value from these fields as you need. In addition to setting INLINE TEMPLATES, 
// you can also alter the styling (e.g. size) of your content container.
echo '<label>Address</label><br>'; 
$editable = Editable::begin([
    'model'=>$model,
    'attribute'=>'address_1',
    'asPopover' => false,
    'inlineSettings' => [
        'templateBefore' => Editable::INLINE_BEFORE_2, 
        'templateAfter' =>  Editable::INLINE_AFTER_2
    ],
    'contentOptions' => ['style'=>'width:350px'],
    'displayValue' => '15th Main, OK, 10322',
    'options'=>['placeholder'=>'Enter location...']
]);
$form = $editable->getForm();
echo Html::hiddenInput('kv-complex', '1');
$editable->afterInput = 
    $form->field($model, 'state_2')->widget(\kartik\select2\Select2::classname(), [
        'data'=>$data, // any list of values
        'options'=>['placeholder'=>'Enter state...'],
        'pluginOptions'=>['allowClear'=>true]
    ]) . "\n" .
    $form->field($model, 'zip_code_1')->textInput(['placeholder'=>'Enter zip code...']);
Editable::end();

// Extension of advanced Editable for usage with complex widgets like DepDrop using 
// dependent data
$editable = Editable::begin([
    'model' => $model,
    'attribute' => 'subcat',
    'asPopover' => false,
    'inlineSettings' => [
        'templateBefore' => Editable::INLINE_BEFORE_2, 
        'templateAfter' =>  Editable::INLINE_AFTER_2
    ],
    'inputType' => Editable::INPUT_DEPDROP,
    'options' => [
        'type' => DepDrop::TYPE_SELECT2,
        'select2Options'=> ['pluginOptions'=>['allowClear'=>true]],
        'options' => ['id'=>'subcat-id-i', 'placeholder' => 'Select subcat...'],
        'pluginOptions'=>[
            'depends'=>['cat-id-i'],
            'url' => Url::to(['/site/subcat'])
        ]
    ]
]);
$form = $editable->getForm();
// use a hidden input to understand if form is submitted via POST
$editable->beforeInput = Html::hiddenInput('kv-editable-depdrop', 1) . 
    $form->field($model, 'cat')->dropDownList(['' => 'Select cat...'] + Demo::$catList, ['id'=>'cat-id-i'])->label(false) . "\n";
$editable->afterInput = $form->field($model, 'prod')->widget(DepDrop::classname(), [
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options'=> ['pluginOptions'=>['allowClear'=>true]],
    'options' => ['id'=>'prod-id-i', 'placeholder' => 'Select prod...'],
    'pluginOptions'=>[
        'depends'=>['cat-id-i', 'subcat-id-i'],
        'url' => Url::to(['/site/prod'])
    ]
])->label(false) . "\n";
Editable::end();

yii2-editable is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017