# Columns

In this part, we will learn the following:

* Columns Introduction
* Column Types
  * Select
  * Action
    * Button
    * Checkbox
    * Icon
    * Actions Options
  * ExternalData
  * Columns Options
* Column Data Types
  * PhpString
  * DateTime
  * Image
  * Number
  * PhpArray
* Column Data Styles
  * Background color
  * Bold
  * Color
  * Italic
  * Align
  * Strikethrough
  * Applying Style
* Column Data Formatters
  * Email
  * File Size
  * Image Formatter
  * Link

## Columns Introduction

The column definition is a central part of ZfcDatagrid, they are used to tell the grid what columns to display and how to display them.

A minimal column definition looks like this:
```php
use ZfcDatagrid\Column;

$col = new Column\Select('columnDataKey');
$col->setLabel('Display Name');
$grid->addColumn($col);
```
You can also use the [zfc-data-grid-plugin](https://github.com/agerecompany/zfc-data-grid-plugin) to create columns with an array configuration, instead of objects!

## Column Types
The column type is the basic object that is created and added to the ZfcDatagrid to contruct the grid table, you can choose between `Action`, `ExternalData` and `Select` column types.

### Select
The following is an example of a select column type:
```php
$col = new Column\Select('columnDataKey');
```

You can also use the select column to display data from database table (Doctrine...), and you can pass an alias for the table as the following:
```php
$col = new Column\Select('databaseColumnName', 'tableNameOrAlias');
```
If you are using **Doctrine** you can use select column type with a Query Select expression as the following example:
```php
use ZfcDatagrid\Column;
use Doctrine\ORM\Query\Expr;

$querySelect = new Expr\Select("concat(first_name, ' ', last_name)");
$col = new Column\Select($querySelect, 'full_name');
```

### Action
The actions are special type of columns that will only be shown on HTML renderer, the action column takes one or more actions and display them in one column. Creating an Action column is same as creating a select column, the difference is that it takes actions objects instead of data to display in the grid.

See the following is an example of button action, first you need to craete action and then you add the action to action folumn as the following:
```php
use ZfcDatagrid\Column;

$viewAction = new Column\Action\Button();
$viewAction->setLabel('View');
$viewAction->setLink('view/url/id');

//or set a dynamic column/row value as label
$viewAction->setLabel($oneColumn);

$actions = new Column\Action();
$actions->setLabel('');
$actions->addAction($viewAction);
$grid->addColumn($actions);
```

The following are the available actions available in ZfcDatagrid:

#### Button
Button action is a simple link that is displayed as button using Bootstrap classes, to create a button and to know the available options see the following:
```php
use ZfcDatagrid\Column;

//Create the button action
$btn = new Column\Action\Button();

//Set the lable of the button
$btn->setLabel('View');
```
More options and manipulation can be applied to Button are in the [Actions Options](/docs/03. Columns.md#action-options) bellow.

#### Checkbox
Checkbox action is a checkbox html, the value of the checkbox will be a unique row id of the grid. To create a checkbox action and to know the available options see the following:
```php
use ZfcDatagrid\Column;

//Create the Checkbox action
$chkbox = new Column\Action\Checkbox('checkboxName');
```
More options and manipulation can be applied to Checkbox are in the [Actions Options](/docs/03. Columns.md#action-options) bellow.

#### Icon
Icon action is either an HTML **img** element with image, or an HTML **i** element with Bootstrap icon class. To create either of them see the following:
```php
use ZfcDatagrid\Column;

//Create the Icon action
$icon = new Column\Action\Icon();

//Set the bootstrap icon class name
$icon->setIconClass('glyphicon glyphicon-remove');
//OR
//Set the icon image source
$icon->setIconLink('path/to/icon/image');
```
More options and manipulation can be applied to Icon are in the [Actions Options](/docs/03. Columns.md#action-options) bellow.

#### Action Options
The following options are common for all actions:
```php
use ZfcDatagrid\Filter;

//Set the link of the click on the button
$btn->setLink('url');

//Set html attribute value
$btn->setAttribute('id' ,'linkHtmlId');

//Set the html title attribute
$btn->setTitle('View Details');

//Add css class to the html link
$btn->addClass('class-name');

//Set when to display the action condition, for example this
//display the action when column value = 1
$btn->addShowOnValue($columnToCompate, 1, Filter::EQUAL);

//When adding multiple show on value conditions, you can
//specify if the check of all conditions is 'OR' or 'AND'
$btn->setShowOnValueOperator('OR');

//You can also use another column's value to make the comparison
//display only when the value of the column $colPaid is greater or equal than the value of the column $colDue
$btn->addShowOnValue($columnPaid, $colDue, Filter::GREATER_EQUAL);

//You can also get the current row ID value, and you may use it to set
//the edit link or anything you want which depends on row ID like this:
$rowId = $btn->getRowIdPlaceholder();
$btn->setLink('edit/' . $rowId);

//To get a place holder for a column to be used in an action:
$btn->getColumnRowPlaceholder($myCol)
```

### ExternalData
The ExternalData action is an action that is rendered using one of the `Column\DataPopulation` methods, the following example uses `Column\DataPopulation\Object\Gravatar` to render the action:

```php
use ZfcDatagrid\Column;

$colEmail = new Column\Select('email');

$dataPopulation = new Column\DataPopulation\Object();
$dataPopulation->setObject(new Column\DataPopulation\Object\Gravatar());
$dataPopulation->addObjectParameterColumn('email', $colEmail);

$col = new Column\ExternalData('avatar');
$col->setLabel('Avatar');
$col->setType(new Type\Image());
$col->setDataPopulation($dataPopulation);
```

### Columns Options
All column types share together an abstract class, there following options are possible:
```php
use ZfcDatagrid\Column;
use ZfcDatagrid\Column\Formatter;
use ZfcDatagrid\Column\Type;
use ZfcDatagrid\Column\Style;
use ZfcDatagrid\Filter;

$col = new Column\Select('myColumn');

//The displayed column label
$col->setLabel('Label');

//a uniqueId is auto generated, but you can override this way
$col->setUniqueId('myUniqueId');

//the width is in percent, because there are different output modes. If the sum of all percentage is not 100 it's adjusted automatically by the grid!
$col->setWidth(20);

 //hide or show this column
$col->setHidden($bool);

//set this as a `primaryKey` column (all identity columns will be used together as the ID for actions and rowIds)
$col->setIdentity($bool);

//set the columnType. Default is string (other types see later)
//types also changes things: change filtering, formatting, styling ...
$col->setType(new Type\Image());

//format the value with this formatter
//many things are already good when using the right Type!
$col->addFormatter(new Formatter\FileSize());

//you can set different styles for columns
//you can also combine multiple styles
$col->addStyle(new Style\Bold());

//style can also be applied on different values only!
$style = new Style\Color(Style\Color::$RED);
$style->setByValue($col, 20, Filter::EQUAL); //or NOT_EQUAL
$col->addStyle($style);

//you can add multiple class names
//by default bootstrapTable will add the class name 'btn' when type is of 'Action'
$col->addClass('btn-primary'); // generates "btn btn-primary"

//you can override this default behaviour by (re-)setting the complete class attribute
$col->setAttribute('class', 'non-twb-class'); // overrides all existing class names

//disable or enable user sorting on this column
//default: on, e.g. on Type\Image default disabled)
$col->setUserSortDisabled($bool);

//Sort by this column, as long the user does not override sorting
//you can define multiple sort columns! (just increase the priority)
$col->setSortDefault(1, 'ASC');

//Disable or enable column filtering
//is also automatically disabled e.g. on Type\Image
$col->setUserFilterDisabled($bool);

//filter the data by this value, as long no user filtering is taken
$col->setFilterDefaultValue('myFilterValue');

//adjust the filter operator (default is LIKE, dependend on the type)
$col->setFilterDefaultOperation(Filter::LIKE_RIGHT);

//replace the retrieved data values with those
$replaces = array('m' => 'male', 'f' => 'female');
$col->setReplaceValues($replaces, $boolNotReplacedGetEmpty);

//enable translation for this column data
$col->setTranslationEnabled($bool);

//set filter options (if u use replaceValues, this is already done automatically)
$options = array('m' => 'male', 'f' => 'female');
$col->setFilterSelectOptions($options);

//only jqGrid currently (custom display)
$col->setRendererParameter('formatters', '
    function (value, options, rowObject) {
    	//do something custom
    	return value;
	}
', 'jqgrid');

//disable the rowClick action on this column (if a row click action is available)
$col->setRowClickDisabled($bool);

$grid->addColumn($col);
```

## Column Data Types

The column data types are used to convert the value from the data source to the value that will appear in the grid table.

### DateTime
To use the `DateTime` column data type you need to create a `Type\DateTime` object which can takes the following parameters in order:
* Source DateTime Format: default `'Y-m-d H:i:s'`
* Output DateTime Format: default `IntlDateFormatter::MEDIUM`
* Locale: default `Locale::getDefault()`
* Source Timezone: default `'UTC'`
* Output Timezone: default `date_default_timezone_get()`

The following is an example of how to use DateTime column data type:
```php
$colType = new Type\DateTime(
        'Y-m-d H:i:s',
        \IntlDateFormatter::MEDIUM,
        \IntlDateFormatter::MEDIUM
	);
$colType->setSourceTimezone('UTC');
$colType->setOutputTimezone('Asia/Jerusalem');

$col = new Column\Select('changeDate');
$col->setLabel('Last change');
//Here set the column data type to be displayed based on the type
$col->setType($colType);
```

### Image
The Image column data type is used to display an image, you can set the column data type as the following to display image column:
```php
$col->setType(new Type\Image());
```

### Number
The Number column data types is used to format numbers using the PHP `NumberFormatter`, and so you can use the `NumberFormatter` properties in this data type, to do so you create a `Type\Number` object which can takes the following parameters in order:
* Format Style: default `NumberFormatter::DECIMAL`
* Format Type: default `NumberFormatter::TYPE_DEFAULT`
* Locale: Default `Locale::getDefault()`

You can also do the following for this type:
* `setPrefix('prefix')`
* `setSuffix('prefix')`
* `addAttribute('attrName', 'attrValue')`

A usage Example of this column data type is the following:
```php
$colType = new Type\Number();
$colType->addAttribute(\NumberFormatter::FRACTION_DIGITS, 2);
$colType->setSuffix(' kg');

$col = new Column\Select('weight');
$col->setLabel('Weight');
$col->setType($colType);
```

### PhpArray
The `PhpArray` column data type is used to convert a value into an array, the default separator of the string is comma `,`, a usage example is like the following:
```php
$colTags = new Column\Select('tags');
$colTags->setLabel('Tags');
$colTags->setType(new Type\PhpArray());
```
You can change the separator by one of the following ways:
```php
new Type\PhpArray(',');
```
```php
$arrayType = new Type\PhpArray();
$arrayType->setSeparator(',');
```

## Column Data Styles

The column data styles are used to give styles for the data, you can apply styles like bold, add color, make italic and other styles.

### Background color
The `Style\BackgroundColor` is used to change the background color of rows or columns of the grid, to create a `Style\BackgroundColor` do the following:
```php
$bgStyle = new Style\BackgroundColor(array(200, 200, 200));
```
where the parameters are the color red green blue values.

To see how to apply style on rows or columns see the [Applying Style](/docs/03. Columns.md#applying-style) section.

### Bold
The `Style\Bold` style simply make the text bold, you can create a bold style like this `$boldStyle = new Style\Bold();`

To see how to apply style on rows or columns see the [Applying Style](/docs/03. Columns.md#applying-style) section.

### Color
The `Style\Color` is used to change the color of rows or columns of the grid, to create a `Style\Color` do the following:
```php
$colorStyle = new Style\Color(array(200, 200, 200));
```
where the parameters are the color red green blue values.

To see how to apply style on rows or columns see the [Applying Style](/docs/03. Columns.md#applying-style) section.

### Italic
The `Style\Italic` style simply make the text italic, you can create an Italic style like this `$italicStyle = new Style\Italic();`

To see how to apply style on rows or columns see the [Applying Style](/docs/03. Columns.md#applying-style) section.

### Applying Style
To apply a style on a column, you simply do the following:
```php
$col->addStyle($style);
```
To apply a style on rows, you can set this on the grid like the following:
```php
$grid->addRowStyle($style);
```
In setting style for rows you can apply a conditional applying like the following:
```php
$style = new Style\Color(Style\Color::$RED);
//Apply only when the value of the column $col = 20
$style->addByValue($col, 20, Filter::EQUAL);
```
You can add multiple conditions for the style using `addByValue`, and you can set the operator between the multiple conditions to be 'OR' or 'AND' like the following:
```php
$style = new Style\Color(Style\Color::$RED);
//Apply only when the value of the column $col between 20 and 40 (inclusive)
$style->setByValueOperator('AND');
$style->addByValue($col, 20, Filter::GREATER_EQUAL);
$style->addByValue($col, 40, Filter::LESS_EQUAL);
```

You can also use another column's value to make the comparison:
```php
$style = new Style\Color(Style\Color::$GREEN);
//Apply only when the value of the column $colPaid is greater or equal than the value of the column $colDue
$style->addByValue($colPaid, $colDue, Filter::GREATER_EQUAL);
```

## Column Data Formatters
The column data formatters are custom formatters used to format the value from the datasource to be displayed in the grid table.

### Email
The Email formatters displays a mailto link to the email, to use it do the following:
```php
$col->addFormatter(new Formatter\Email());
```

### File Size
The FileSize formatters displays a number as a file size with a letter that indicates the size unit (K=>Kilobyte, M=>Megabyte, ...etc), to use it do the following:
```php
$col->setFormatters([new Formatter\FileSize()]);
```

### Image Formatter
The Image formatters displays a linkable image HTML tags, the link will be to the pointing to the image, a usage example is like the following:
```php
$imageFormatter = new Formatter\Image();

//Set the prefix of the image path and the prefix of the link
$imageFormatter->setPrefix('path/prefix/');

//set <img> attributes like this:
$imageFormatter->setAttribute('alt', 'Image Alt');

//set <a> attributes of the image like this:
$imageFormatter->setLinkAttribute('title', 'View Full Image');

//apply the style on the column $col
$col->addFormatter($imageFormatter);
```

### Link
The Link formatters displays a column content as an HTML link with value and href is the column content, to use it do the following:
```php
$col->addFormatter(new Formatter\Link());
```

### Navigation

* Continue to [**Filtering**](/docs/04. Filtering.md)
* Back to [Quick Start](/docs/02. Quick Start.md)
* Back to [the Index](/docs/README.md)
