Skip to content

Instantly share code, notes, and snippets.

@Casmo
Created October 26, 2016 16:31
Show Gist options
  • Save Casmo/d64c6033a16f569e44503cde61cfb0d5 to your computer and use it in GitHub Desktop.
Save Casmo/d64c6033a16f569e44503cde61cfb0d5 to your computer and use it in GitHub Desktop.
ArrayType for CakePHP 3
<?php
use Cake\Database\Type;
Type::map('array', 'App\Database\Type\ArrayType');
<?php
/**
* File src/Database/Type/ArrayType.php
*/
namespace App\Database\Type;
use Cake\Database\Driver;
use Cake\Database\Type;
use PDO;
class ArrayType extends Type
{
public function toPHP($value, Driver $driver)
{
if ($value === null || empty($value)) {
return [];
}
return explode(',', $value);
}
public function marshal($value)
{
if ($value === null || empty($value)) {
return [];
}
return explode(',', $value);
}
public function toDatabase($value, Driver $driver)
{
if (is_array($value)) {
$string = implode(",", $value);
$string = preg_replace('/\s?,\s?/', ',', $string);
return $string;
}
else {
return $value;
}
}
public function toStatement($value, Driver $driver)
{
if ($value === null) {
return PDO::PARAM_NULL;
}
return PDO::PARAM_STR;
}
}
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Database\Schema\Table as Schema;
/**
* Users Model
*/
class ModelTable extends Table
{
protected function _initializeSchema(Schema $schema)
{
$schema->columnType('options', 'array');
return $schema;
}
}
?>
<?php
namespace App\View;
use Cake\View\View;
/**
* Application View
* Your application’s default view class
* @link http://book.cakephp.org/3.0/en/views.html#the-app-view
*/
class AppView extends View
{
public function initialize()
{
$this->loadHelper('Form',
[
'widgets' => [
'array' => [
'App\View\Widget\ArrayWidget'
]
]
]
);
}
}
<?php
namespace App\View\Widget;
use Cake\View\Form\ContextInterface;
use Cake\View\Widget\WidgetInterface;
class ArrayWidget implements WidgetInterface
{
protected $_templates;
public function __construct($templates)
{
$this->_templates = $templates;
}
public function render(array $data, ContextInterface $context)
{
$data += [
'value' => implode(',', $data['val'])
];
return $this->_templates->format('input', [
'name' => $data['name'],
'type' => 'text',
'attrs' => $this->_templates->formatAttributes(
$data
)
]);
}
public function secureFields(array $data)
{
return [$data['name']];
}
}
<?php
echo $this->Form->input('options', [
'type' => 'array',
]);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment