
# Create column

```js
const fields = [
  { fieldName: 'KorName', dataType: 'text' },
  { fieldName: 'Gender', dataType: 'text' },
  { fieldName: 'Age', dataType: 'number' },
  { fieldName: 'Phone', dataType: 'text' },
  { fieldName: 'ProductId', dataType: 'text' },
  { fieldName: 'KorCountry', dataType: 'text' },
  { fieldName: 'OrderDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'CardNumber', dataType: 'text' },
  { fieldName: 'Monetary', dataType: 'text' },
  { fieldName: 'StartDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'EndDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'ToMonth', dataType: 'number' },
  { fieldName: 'Month', dataType: 'number' },
  { fieldName: 'Year', dataType: 'number' },
  { fieldName: 'InterestRate', dataType: 'number' },
  { fieldName: 'SaveCost', dataType: 'number' },
  { fieldName: 'SaveMaturity', dataType: 'number' },
  { fieldName: 'CurrentSave', dataType: 'number' }
];

const columns = [
  { name: 'KorName', fieldName: 'KorName', width: '60', header: { text: 'Name' } },
  { name: 'Gender', fieldName: 'Gender', width: '40', header: { text: 'Gender' } },
  { name: 'Age', fieldName: 'Age', width: '40', header: { text: 'Age' } },
  { name: 'Phone', fieldName: 'Phone', width: '100', header: { text: 'Phone' } },
  { name: 'ProductId', fieldName: 'ProductId', width: '120', header: { text: 'Product ID' } },
  { name: 'KorCountry', fieldName: 'KorCountry', width: '100', header: { text: 'Investment Country' } },
  { name: 'OrderDate', fieldName: 'OrderDate', width: '100', header: { text: 'Order Date' } },
  { name: 'CardNumber', fieldName: 'CardNumber', width: '140', header: { text: 'Card Number' } },
  { name: 'Monetary', fieldName: 'Monetary', width: '40', header: { text: 'Currency' } },
  { name: 'StartDate', fieldName: 'StartDate', width: '100', header: { text: 'First Payment Date' } },
  { name: 'EndDate', fieldName: 'EndDate', width: '100', header: { text: 'End Date' } },
  { name: 'ToMonth', fieldName: 'ToMonth', width: '50', header: { text: 'Payment Count' } },
  { name: 'Month', fieldName: 'Month', width: '50', header: { text: 'Remaining Count' } },
  { name: 'InterestRate', fieldName: 'InterestRate', width: '50', numberFormat: '0.00', header: { text: 'Interest Rate' } },
  { name: 'SaveCost', fieldName: 'SaveCost', width: '80', numberFormat: '#,##0', header: { text: 'Payment Amount' } },
  { name: 'SaveMaturity', fieldName: 'SaveMaturity', width: '80', numberFormat: '#,##0', header: { text: 'Maturity Amount' } },
  { name: 'CurrentSave', fieldName: 'CurrentSave', width: '80', numberFormat: '#,##0', header: { text: 'Current Balance' } }
];

const datas = [
  { Field1: 'Cell(0, 0)', Field2: 'Cell(0, 1)', Field3: 'Cell(0, 2)', Field4: 'Cell(0, 3)', Field5: 'Cell(0, 4)' },
  { Field1: 'Cell(1, 0)', Field2: 'Cell(1, 1)', Field3: 'Cell(1, 2)', Field4: 'Cell(1, 3)', Field5: 'Cell(1, 4)' },
  { Field1: 'Cell(2, 0)', Field2: 'Cell(2, 1)', Field3: 'Cell(2, 2)', Field4: 'Cell(2, 3)', Field5: 'Cell(2, 4)' },
  { Field1: 'Cell(3, 0)', Field2: 'Cell(3, 1)', Field3: 'Cell(3, 2)', Field4: 'Cell(3, 3)', Field5: 'Cell(3, 4)' },
  { Field1: 'Cell(4, 0)', Field2: 'Cell(4, 1)', Field3: 'Cell(4, 2)', Field4: 'Cell(4, 3)', Field5: 'Cell(4, 4)' },
  { Field1: 'Cell(5, 0)', Field2: 'Cell(5, 1)', Field3: 'Cell(5, 2)', Field4: 'Cell(5, 3)', Field5: 'Cell(5, 4)' },
  { Field1: 'Cell(6, 0)', Field2: 'Cell(6, 1)', Field3: 'Cell(6, 2)', Field4: 'Cell(6, 3)', Field5: 'Cell(6, 4)' },
  { Field1: 'Cell(7, 0)', Field2: 'Cell(7, 1)', Field3: 'Cell(7, 2)', Field4: 'Cell(7, 3)', Field5: 'Cell(7, 4)' },
  { Field1: 'Cell(8, 0)', Field2: 'Cell(8, 1)', Field3: 'Cell(8, 2)', Field4: 'Cell(8, 3)', Field5: 'Cell(8, 4)' },
  { Field1: 'Cell(9, 0)', Field2: 'Cell(9, 1)', Field3: 'Cell(9, 2)', Field4: 'Cell(9, 3)', Field5: 'Cell(9, 4)' }
];

const { gridView, dataProvider } = RealGrid.createGrid('realgrid', {
  columns,
  header: { height: 40 },
  display: { rowHeight: 36, emptyMessage: 'No data to display.' },
  edit: { insertable: true, appendable: true },
  footer: { height: 40 },
  stateBar: { width: 16 },
  onInitialized: (grid) => {
    fetch('/data/en/simple_data.json')
      .then(response => response.json())
      .then(data => {
        grid.getDataSource().setRows(data);
      });
  }
}, {
  fields
});

window.gridView = gridView;
window.dataProvider = dataProvider;

function btnSetColumns() {
  const newFields = [
    { fieldName: 'Field1' },
    { fieldName: 'Field2' },
    { fieldName: 'Field3' },
    { fieldName: 'Field4' },
    { fieldName: 'Field5' }
  ];

  dataProvider.setFields(newFields);

  const newColumns = [
    { name: 'column1', fieldName: 'Field1', header: { text: 'Column 1' }, tag: 'columntag1', width: 90 },
    { name: 'column2', fieldName: 'Field2', header: { text: 'Column 2' }, tag: 'columntag2', width: 90 },
    { name: 'column3', fieldName: 'Field3', header: { text: 'Column 3' }, tag: 'columntag3', width: 90 },
    { name: 'column4', fieldName: 'Field4', header: { text: 'Column 4' }, tag: 'columntag4', width: 90 },
    { name: 'column5', fieldName: 'Field5', header: { text: 'Column 5' }, tag: 'columntag5', width: 90 },
    { name: 'column6', fieldName: 'Field3', header: { text: 'Column 6' }, tag: 'columntag6', width: 90 }
  ];

  gridView.setColumns(newColumns);

  dataProvider.fillJsonData(datas);
}
```

Create columns with the [`GridBase.setColumns()`](/refs/Class/GridBase#setcolumns) function. At this time, the name of the registered column must be undefined or unique.


```js
var columns = [{
     "name": "column1",
     "fieldName": "Field1",
     "header": {"text": "Column 1"}
     "width": 90
   },{
     "name": "column2",
     "fieldName": "Field2",
     "header": {"text": "Column 2"}
     "width": 90
   },{
     "name": "column3",
     "fieldName": "Field3",
     "header": {"text": "Column 3"}
     "width": 90
   },{
     "name": "column4",
     "fieldName": "Field4",
     "header": {"text": "Column 4"}
     "width": 90
   },{
     "name": "column5",
     "fieldName": "Field5",
     "header": {"text": "Column 5"}
     "width": 90
   },{
     "name": "column6",
     "fieldName": "Field3",
     "header": {"text": "Column 6"}
     "width": 90
   }];

   gridView.setColumns(columns);
```

The GridBase.setColumns() function deletes existing columns and adds new columns using the column information passed as a parameter.
In the example, columns `column3` and `column6` display the same `Field3` field. In this way, one data field can be referenced by multiple columns simultaneously and displayed in different ways.

The function [`GridBase.columnByName()`](/refs/Class/GridBase#columnbyname) returns the column object corresponding to the given name.

```js
var column = gridView.columnByName("column3");
alert(JSON.stringify(column));
```

If one result is expected, use the [`GridBase.columnByField()`](/refs/Class/GridBase#columnbyfield) function.

#### Add dynamic column (field)

It seems uncommon to dynamically add new fields and columns to a grid. Normally, it will be rare for users to add or delete fields in business data structures, but that doesn't mean it's completely unexpected.

If this is the case, I will think about how to handle it and write a demo.

- [dataProvider.setFields](/refs/Class/DataProviderBase#setfields) and
- Use the [gridView.setColumns()](/refs/Class/GridBase#setcolumns) function

You can set the entire structure of fields and columns, but

- [dataProvider.addField](/refs/Class/DataProviderBase#addfield) and
- Use the [gridView.addColumn()](/refs/Class/GridBase#addcolumn) function

You can also add fields and columns separately.

```js
provider.addField({
   fieldName: "TEXT_Column",
   valueType: "text",
});

viewer.addColumn({
   name: "TEXT_Column",
   fieldName: "TEXT_Column",
   width: 150,
   header: {
     text: "TEXT Column",
   },
   editor: { type: "line" },
});
```

```js
let manager, dataProvider, gridView;

const GridManager = (dp, gv) => {
  if (!dp || !gv) throw new Error('DataProvider and GridView objects are required.');

  const provider = dp;
  const viewer = gv;

  viewer.setDataSource(provider);

  return {
    getNewFieldName: function(fieldName) {
      let newFieldName = fieldName.replace(' ', '_');
      const index = provider.getFieldIndex(newFieldName);

      if (index === -1) return newFieldName;
      return this.getNewFieldName(newFieldName.concat('1'));
    },
    hasColumns: function() {
      return viewer.getColumns().length > 0 && provider.getFields().length > 0;
    },
    hasData: function() {
      return provider.getRowCount() > 0;
    },
    _checkData: function() {
      if (this.hasColumns() && !this.hasData()) {
        provider.setRowCount(10);
      }
    },
    addColumn: function(colName, valueType, editor, renderer) {
      const fieldName = this.getNewFieldName(colName);
      provider.addField({ 
        fieldName: fieldName,
        dataType: valueType,
      });
      
      viewer.addColumn({
        name: fieldName,
        fieldName: fieldName,
        width: 130,
        header: {
          text: colName,
        },
        editor: editor,
        renderer: renderer,
      });

      this._checkData();

      return fieldName;
    },
  };
};

dataProvider = new RealGrid.LocalDataProvider();
gridView = new RealGrid.GridView('realgrid');
gridView.setDataSource(dataProvider);
gridView.displayOptions.emptyMessage = 'No data to display.';

manager = new GridManager(dataProvider, gridView);

window.dataProvider = dataProvider;
window.gridView = gridView;
window.manager = manager;

function onClickBtnAddTextColumn() {
  const fieldName = manager.addColumn('TEXT Column', 'text', { type: 'line' });
  dataProvider.setValue(1, fieldName, 'Text Value');
}

function onClickBtnAddNumberColumn() {
  const fieldName = manager.addColumn('NUMBER Column', 'number', {
    type: 'number',
    positiveOnly: true,
  });
  dataProvider.setValue(1, fieldName, 710708);
}

function onClickBtnAddDateColumn() {
  const fieldName = manager.addColumn('DATETIME Column', 'datetime', {
    type: 'date',
    maxLength: 6,
    yearNavigation: true,
  });
  dataProvider.setValue(1, fieldName, '2020.07.08');
}

function onClickBtnAddDropdownColumn() {
  const fieldName = manager.addColumn('DROPDOWN Column', 'text', {
    type: 'list',
    values: ['Value1', 'Value2', 'Value3'],
    labels: ['Value is 1', 'Value is 2', 'Value is 3'],
    displayLabels: 'valueLabel',
    textReadOnly: true
  });
  dataProvider.setValue(1, fieldName, 'Value2');
}

function onClickBtnAddBooleanColumn() {
  const fieldName = manager.addColumn('BOOLEAN Column', 'boolean', undefined, {
    type: 'check',
    trueValues: 'true',
    falseValues: 'false',
  });
  dataProvider.setValue(1, fieldName, true);
}

function onClickBtnAddObjectColumn() {
  const fieldName = manager.addColumn('Object Column', 'object', { type: 'line' }, {
    type: 'html',
    callback: function(grid, cell, w, h) {
      const p = cell.value;
      console.log(p);
      if (p && p.from && p.to) {
        p.rendom = p.rendom || Math.floor(Math.random() * (p.to - p.from) + p.from);
        cell.value = p;
        return p.rendom;
      }

      return '';
    },
  });
  dataProvider.setValue(1, fieldName, { from: 100, to: 250 });
}
```