Pregunta

Hola me preguntaba si alguien sabe si es posible definir una columna en slickgrid como una lista desplegable de selección. Si no lo hace cualquier persona con cierta experiencia con conocimientos slickgrid cómo debería ir sobre la adición de esta opción?

Gracias

¿Fue útil?

Solución

supongo que quiere decir un editor de celda personalizado. Aquí está una muestra basada en seleccionar editor de celdas booleano de slick.editors.js. Desde aquí se puede modificar para que funcione con un conjunto arbitrario de valores posibles.

function YesNoSelectCellEditor($container, columnDef, value, dataContext) {
    var $select;
    var defaultValue = value;
    var scope = this;

    this.init = function() {
        $select = $("<SELECT tabIndex='0' class='editor-yesno'><OPTION value='yes'>Yes</OPTION><OPTION value='no'>No</OPTION></SELECT>");

        if (defaultValue)
            $select.val('yes');
        else
            $select.val('no');

        $select.appendTo($container);

        $select.focus();
    };


    this.destroy = function() {
        $select.remove();
    };


    this.focus = function() {
        $select.focus();
    };

    this.setValue = function(value) {
        $select.val(value);
        defaultValue = value;
    };

    this.getValue = function() {
        return ($select.val() == 'yes');
    };

    this.isValueChanged = function() {
        return ($select.val() != defaultValue);
    };

    this.validate = function() {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
};

Otros consejos

Es probable que no quiero hacer un nuevo editor de selección para cada gama de opciones. También es posible que no sepa que toda gama de valor de la opción de antemano.

En ese caso usted quiere una gama flexible de opciones en un selecto editor de tipos. Con el fin de hacer esto usted puede agregar una opción adicional a sus definiciones de columna (por ejemplo, llamadas opciones) así:

 var columns = [
  {id:"color", name:"Color", field:"color",  options: "Red,Green,Blue,Black,White", editor: SelectCellEditor},
  {id:"lock", name:"Lock", field:"lock",  options: "Locked,Unlocked", editor: SelectCellEditor}
 ]

y el acceso que el uso de args.column.options en el método init de su propio objeto SelectEditor como esto:

 SelectCellEditor : function(args) {
        var $select;
        var defaultValue;
        var scope = this;

        this.init = function() {

            if(args.column.options){
              opt_values = args.column.options.split(',');
            }else{
              opt_values ="yes,no".split(',');
            }
            option_str = ""
            for( i in opt_values ){
              v = opt_values[i];
              option_str += "<OPTION value='"+v+"'>"+v+"</OPTION>";
            }
            $select = $("<SELECT tabIndex='0' class='editor-select'>"+ option_str +"</SELECT>");
            $select.appendTo(args.container);
            $select.focus();
        };

        this.destroy = function() {
            $select.remove();
        };

        this.focus = function() {
            $select.focus();
        };

        this.loadValue = function(item) {
            defaultValue = item[args.column.field];
            $select.val(defaultValue);
        };

        this.serializeValue = function() {
            if(args.column.options){
              return $select.val();
            }else{
              return ($select.val() == "yes");
            }
        };

        this.applyValue = function(item,state) {
            item[args.column.field] = state;
        };

        this.isValueChanged = function() {
            return ($select.val() != defaultValue);
        };

        this.validate = function() {
            return {
                valid: true,
                msg: null
            };
        };

        this.init();
    }

Si su celular ya contiene una -tag "seleccionar" con múltiples opciones, se puede extraer este código HTML a partir de los argumentos. Los difiere de aproximación de las respuestas anteriores, pero me preocupaba personalmente con estas soluciones, por supuesto, mi celular ya contenía una etiqueta de selección. Me gustaría volver a utilizar este celda en lugar de reconstruir por completo en el this.init. Del mismo modo, me gustaría seguir usando las mismas opciones, como mi existente seleccione ya tienen, en lugar de analizar a la var column = { ...

El $( args.item[ args.column.field ] ) devolver el contenido células activo, que, básicamente, sólo conseguir re-anexa a la la container (la célula a objetos). De if ( document.createEvent ) y hacia abajo, es sólo una funcionalidad que se abre automáticamente en el menú desplegable en la activación; etc., cuando se utiliza el tabulador para desplazarse a la celda.

function SelectCellEditor( args ) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
        $select = $( args.item[ args.column.field ] );
        $select.appendTo( args.container );
        $select.focus();

        // Force the select to open upon user-activation
        var element = $select[ 0 ];

        if ( document.createEvent ) { // all browsers
            var e = new MouseEvent( "mousedown", {
                bubbles: true,
                cancelable: true,
                view: window
            });

            element.dispatchEvent( e );
        } else if ( element.fireEvent ) { // ie
            element.fireEvent( "onmousedown" );
        }

    };
}

editor de Complet para desplegable HTML de entrada -> desplegable html-salida

function SelectCellEditor( args ) {
    var $select = $( args.item[ args.column.field ] );
    var defaultValue;
    var scope = this;

    this.init = function () {
        //$select
        $select.appendTo( args.container );

        // Force the select to open upon user-activation
        var element = $select[ 0 ];

        if ( document.createEvent ) { // all browsers
            var e = new MouseEvent( "mousedown", {
                bubbles: true,
                cancelable: true,
                view: window
            });

            element.dispatchEvent( e );
        } else if ( element.fireEvent ) { // ie
            element.fireEvent( "onmousedown" );
        }

        $select.on("click", function( e ) {
            var selected = $( e.target ).val();

            $select.find( "option" ).removeAttr( "selected" );
            $select.find( "option[value='" + selected + "']" ).attr( "selected", "selected" );
        });

    };

    this.destroy = function () {
        $select.remove();
    };

    this.focus = function () { };

    this.loadValue = function ( item ) { };

    this.serializeValue = function () { };

    // Only runs if isValueChanged returns true
    this.applyValue = function ( item, state ) {
        item[ args.column.field ] = $select[ 0 ].outerHTML;
    };

    this.isValueChanged = function () {
        return true;
    };

    this.validate = function () {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}

Sin jq, y los elementos en línea inyectados, envasado en módulo:

'use strict';
 class SelectCellWidget {
    constructor(args) {
        this._args = args;
        this._$select = undefined;
        this._defaultValue = undefined;
        this._init();
    }
     _init () {
        let selects, container, divend, opt_values;
        const args = this._args;
        if(args.column.options){
            opt_values = args.column.options.split(',');
        }else{
            opt_values = ["yes","no"];
        }
        container = document.createElement("div");
        container.classList.add('select-editable');
        divend = document.createElement('input');
        divend.setAttribute("type", "text");
        divend.setAttribute("name", "format");
        divend.setAttribute("value", "");
        selects = document.createElement("select");//"<select id='Mobility' tabIndex='0' class='editor-select'>"+ option_str +"</select>";
        selects.setAttribute("id", "Mobility");
        selects.setAttribute("tabIndex", 0);
        selects.setAttribute("class", "editor-select");
        for(let i = 0; i < opt_values.length; i++) {
            let v = opt_values[i];
            let option = document.createElement("option");
            option.setAttribute("value", v);
            option.innerText = v;
            selects.appendChild(option);
        }

        container.appendChild(divend);
        container.appendChild(selects);
        this._$select = container;
        args.container[0].appendChild(this._$select);
        this._$select.focus();
        document.getElementById("Mobility").selectedIndex = args.item[args.column.field] ? opt_values.indexOf(args.item[args.column.field]) : 0;
    }
     destroy () {
        this._$select.remove();
    }
     focus () {
        this._$select.focus();
    }
     loadValue (item) {
       this._defaultValue = item[this._args.column.field];
       this._$select.value = this._defaultValue;
    }
     serializeValue () {
        if(this._args.column.options){
            return this._$select.lastElementChild.value;
        }else{
            return (this._$select.lastElementChild.value === "yes");
        }
    }
     applyValue (item,state) {
       item[this._args.column.field] = state;
    }
     isValueChanged () {
       return (this._$select.lastElementChild.value !== this._defaultValue);
    }
     validate () {
       return {
           valid: true,
           msg: null
       };
    }
}
module.exports=SelectCellWidget; 

https://github.com/YaAlfred/SlickgridSelectDropdownWidget

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top