silverstripe-framework/src/Forms/GridField/GridFieldAddNewButton.php

69 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Forms\GridField;
use SilverStripe\Control\Controller;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\RelationList;
use SilverStripe\View\ArrayData;
use SilverStripe\View\SSViewer;
/**
2014-08-15 08:53:05 +02:00
* This component provides a button for opening the add new form provided by
* {@link GridFieldDetailForm}.
*
2014-08-15 08:53:05 +02:00
* Only returns a button if {@link DataObject->canCreate()} for this record
* returns true.
*/
2016-11-29 00:31:16 +01:00
class GridFieldAddNewButton implements GridField_HTMLProvider
{
2016-11-29 00:31:16 +01:00
protected $targetFragment;
2016-11-29 00:31:16 +01:00
protected $buttonName;
2016-11-29 00:31:16 +01:00
public function setButtonName($name)
{
$this->buttonName = $name;
2016-11-29 00:31:16 +01:00
return $this;
}
2016-11-29 00:31:16 +01:00
public function __construct($targetFragment = 'before')
{
$this->targetFragment = $targetFragment;
}
2016-11-29 00:31:16 +01:00
public function getHTMLFragments($gridField)
{
$singleton = singleton($gridField->getModelClass());
$context = [];
if ($gridField->getList() instanceof RelationList) {
$record = $gridField->getForm()->getRecord();
if ($record && $record instanceof DataObject) {
$context['Parent'] = $record;
}
}
if (!$singleton->canCreate(null, $context)) {
return [];
2016-11-29 00:31:16 +01:00
}
2016-11-29 00:31:16 +01:00
if (!$this->buttonName) {
// provide a default button name, can be changed by calling {@link setButtonName()} on this component
$objectName = $singleton->i18n_singular_name();
$this->buttonName = _t('SilverStripe\\Forms\\GridField\\GridField.Add', 'Add {name}', ['name' => $objectName]);
2016-11-29 00:31:16 +01:00
}
$data = new ArrayData([
2016-11-29 00:31:16 +01:00
'NewLink' => Controller::join_links($gridField->Link('item'), 'new'),
'ButtonName' => $this->buttonName,
]);
2016-11-29 00:31:16 +01:00
$templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
return [
2016-11-29 00:31:16 +01:00
$this->targetFragment => $data->renderWith($templates),
];
2016-11-29 00:31:16 +01:00
}
}