latest SS3.1 branch compatibility

This commit is contained in:
colymba 2013-06-02 21:07:00 +03:00
parent cdbf3708a0
commit 9b4608f3d3
6 changed files with 224 additions and 152 deletions

25
code/GFBIUploadField.php Normal file
View File

@ -0,0 +1,25 @@
<?php
class GFBIUploadField extends UploadField
{
public function setConfig($key, $val) {
$this->ufConfig[$key] = $val;
return $this;
}
function extractFileData($postvars)
{
return $this->extractUploadedFileData($postvars);
}
function saveTempFile($tmpFile, &$error = null)
{
return $this->saveTemporaryFile($tmpFile, $error);
}
function encodeFileAttr(File $file)
{
return $this->encodeFileAttributes($file);
}
}

View File

@ -172,6 +172,101 @@ class GridFieldBulkImageUpload_Request extends RequestHandler {
return $formFieldsHTML; return $formFieldsHTML;
} }
/**
* Creates and return the bulk upload form
*
* @return Form
*/
public function uploadForm($id = null, $fields = null)
{
$actions = new FieldList();
$actions->push(
FormAction::create('SaveAll', 'Save All')
->setAttribute('id', 'bulkImageUploadUpdateBtn')
->addExtraClass('ss-ui-action-constructive')
->setAttribute('data-icon', 'accept')
->setAttribute('data-url', $this->Link('update'))
->setUseButtonTag(true)
->setAttribute('src', '')//changes type to image so isn't hooked by default actions handlers
);
$actions->push(
FormAction::create('Cancel', 'Cancel & Delete All')
->setAttribute('id', 'bulkImageUploadUpdateCancelBtn')
->addExtraClass('ss-ui-action-destructive')
->setAttribute('data-icon', 'decline')
->setAttribute('data-url', $this->Link('cancel'))
->setUseButtonTag(true)
->setAttribute('src', '')//changes type to image so isn't hooked by default actions handlers
);
/* *
* UploadField
*/
$uploadField = GFBIUploadField::create('BulkUploadField', '');
$uploadField->setConfig('previewMaxWidth', 40);
$uploadField->setConfig('previewMaxHeight', 30);
$uploadField->addExtraClass('ss-assetuploadfield');
$uploadField->removeExtraClass('ss-uploadfield');
$uploadField->setTemplate('AssetUploadField');
$uploadField->setDownloadTemplateName('colymba-gfbiu-uploadfield-downloadtemplate');
//always overwrite
$uploadField->setOverwriteWarning(false);
/* *
* UploadField configs
*/
//custom upload url
$uploadField->setConfig('url', $this->Link('upload'));
//max file size
$maxFileSize = $this->component->getConfig('maxFileSize');
if ( $maxFileSize !== null )
{
$uploadField->getValidator()->setAllowedMaxFileSize( $maxFileSize );
}
//upload dir
$uploadDir = $this->component->getConfig('folderName');
if ( $uploadDir !== null )
{
$uploadField->setFolderName($uploadDir);
}
//sequential upload
$uploadField->setConfig('sequentialUploads', $this->component->getConfig('sequentialUploads'));
/* *
* Create form
*/
$form = new Form(
$this,
'uploadForm',
new FieldList(
$uploadField
),
$actions
);
$crumbs = $this->Breadcrumbs();
if($crumbs && $crumbs->count()>=2)
{
$one_level_up = $crumbs->offsetGet($crumbs->count()-2);
$form->Backlink = $one_level_up->Link;
}
$form->setTemplate('LeftAndMain_EditForm');
$form->addExtraClass('cms-content center'); //not using cms-edit-form to avoid btn being hooked with default handlers
$form->setAttribute('data-pjax-fragment', 'Content');
return $form;
}
/** /**
* Default and main action that returns the upload form etc... * Default and main action that returns the upload form etc...
@ -182,92 +277,25 @@ class GridFieldBulkImageUpload_Request extends RequestHandler {
{ {
Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js'); Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js');
Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css'); Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css');
$crumbs = $this->Breadcrumbs();
if($crumbs && $crumbs->count()>=2) $one_level_up = $crumbs->offsetGet($crumbs->count()-2);
$actions = new FieldList();
$actions->push(
FormAction::create('SaveAll', 'Save All')
->setAttribute('id', 'bulkImageUploadUpdateBtn')
->addExtraClass('ss-ui-action-constructive cms-panel-link')
->setAttribute('data-icon', 'accept')
->setAttribute('data-url', $this->Link('update'))
->setUseButtonTag(true)
//->setDisabled(true)
);
$actions->push(
FormAction::create('Cancel', 'Cancel & Delete All')
->setAttribute('id', 'bulkImageUploadUpdateCancelBtn')
->addExtraClass('ss-ui-action-destructive cms-panel-link')
->setAttribute('data-icon', 'decline')
->setAttribute('data-url', $this->Link('cancel'))
->setUseButtonTag(true)
//->setDisabled(true)
);
$uploadField = UploadField::create('BulkImageUploadField', '');
$uploadField->setConfig('previewMaxWidth', 40);
$uploadField->setConfig('previewMaxHeight', 30);
$uploadField->addExtraClass('ss-assetuploadfield');
$uploadField->removeExtraClass('ss-uploadfield');
$uploadField->setTemplate('AssetUploadField');
$uploadField->setConfig('downloadTemplateName','GridFieldBulkImageUpload_downloadtemplate');
$uploadField->setConfig('sequentialUploads', $this->component->getConfig('sequentialUploads'));
$maxFileSize = $this->component->getConfig('maxFileSize');
if ( $maxFileSize !== null )
{
$uploadField->getValidator()->setAllowedMaxFileSize( $maxFileSize );
}
$uploadField->setConfig('url', $this->Link('upload'));
//$uploadField->setFolderName(ASSETS_DIR);
$form = new Form(
$this,
'bulkImageUploadForm',
new FieldList(
$uploadField
),
$actions
);
$form->setTemplate('LeftAndMain_EditForm');
//$form->addExtraClass('center cms-edit-form cms-content');
$form->addExtraClass('center cms-content');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
if($crumbs && $crumbs->count()>=2){
$form->Backlink = $one_level_up->Link;
}
// this actually fixes the JS Requirements issue.
// Calling forTemplate() before other requirements forces SS to add the Form's X-Include-JS before
$formHTML = $form->forTemplate();
Requirements::javascript(BULK_EDIT_TOOLS_PATH . '/javascript/GridFieldBulkImageUpload.js'); Requirements::javascript(BULK_EDIT_TOOLS_PATH . '/javascript/GridFieldBulkImageUpload.js');
Requirements::css(BULK_EDIT_TOOLS_PATH . '/css/GridFieldBulkImageUpload.css'); Requirements::css(BULK_EDIT_TOOLS_PATH . '/css/GridFieldBulkImageUpload.css');
Requirements::javascript(BULK_EDIT_TOOLS_PATH . '/javascript/GridFieldBulkImageUpload_downloadtemplate.js'); Requirements::javascript(BULK_EDIT_TOOLS_PATH . '/javascript/GridFieldBulkImageUpload_downloadtemplate.js');
$response = new SS_HTTPResponse($formHTML); $form = $this->uploadForm();
$response->addHeader('Content-Type', 'text/plain');
$response->addHeader('X-Title', 'SilverStripe - Bulk '.$this->gridField->list->dataClass.' Image Upload'); if($request->isAjax())
if($request->isAjax()) { {
$response = new SS_HTTPResponse($form->forAjaxTemplate()->getValue());
$response->addHeader('X-Pjax', 'Content');
$response->addHeader('X-Title', 'SilverStripe - Bulk '.$this->gridField->list->dataClass.' Image Upload');
return $response; return $response;
} else { }
else {
$controller = $this->getToplevelController(); $controller = $this->getToplevelController();
// If not requested by ajax, we need to render it within the controller context+template
return $controller->customise(array( return $controller->customise(array(
'Content' => $response->getBody(), 'Content' => $form
)); ));
} }
} }
@ -302,73 +330,79 @@ class GridFieldBulkImageUpload_Request extends RequestHandler {
*/ */
public function upload(SS_HTTPRequest $request) public function upload(SS_HTTPRequest $request)
{ {
// Protect against CSRF on destructive action
$token = $this->uploadForm()->getSecurityToken();
if(!$token->checkRequest($request)) return $this->httpError(400);
//create DataObject
$recordClass = $this->gridField->list->dataClass; $recordClass = $this->gridField->list->dataClass;
$record = Object::create($recordClass); $record = Object::create($recordClass);
// passes the current gridfield-instance to a call-back method on the new object // passes the current gridfield-instance to a call-back method on the new object
$record->extend("onBulkImageUpload", $this->gridField); $record->extend("onBulkImageUpload", $this->gridField);
//Write + add DO to gridField relation list
$record->write(); $record->write();
$this->gridField->list->add($record->ID); $this->gridField->list->add($record->ID);
$upload = new Upload(); //process upload and file attachement
$tmpfile = $request->postVar('BulkImageUploadField'); $error = null;
$return = array();
// Check if the file has been uploaded into the temporary storage.
if (!$tmpfile) { // Get field details
$return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found')); $uploadField = $this->uploadForm()->Fields()->fieldByName('BulkUploadField');
//$fileRecordName = $this->getRecordImageField();
//$fileRecordName = substr( $fileRecordName, 0, strlen($fileRecordName)-2 );
//$uploadField->setName($fileRecordName); //File/Image obj where to save the upload
//$uploadField->setRecord($record); //record containing the File/Image obj
$postVars = $request->postVar('BulkUploadField');
//$uploadedFiles = $uploadField->extractUploadedFileData($postVars);
$uploadedFiles = $uploadField->extractFileData($postVars);
$tmpFile = reset($uploadedFiles);
//$file = $uploadField->saveTemporaryFile($tmpFile, $error);
//$file = $uploadField->saveTempFile($tmpFile, $error);
/*
if(empty($file)) {
$return = array('error' => $error);
} else { } else {
$return = array( //$return = $uploadField->encodeFileAttributes($file);
'name' => $tmpfile['name'], $return = $uploadField->encodeFileAttr($file);
'size' => $tmpfile['size'], }*/
'type' => $tmpfile['type'],
'error' => $tmpfile['error'] $file = Object::create($this->getRecordImageClass());
);
// Get the uploaded file into a new file object.
try {
$upload = new Upload();
$upload->loadIntoFile($tmpFile, $file, $this->component->getConfig('folderName'));
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$return['error'] = $e->getMessage();
} }
// Attach the file to the related record.
$record->setField($this->getRecordImageField(), $file->ID);
$record->write();
//get record's CMS Fields
$recordEditableFormFields = $this->getRecordHTMLFormFields( $record->ID );
// Process the uploaded file // Collect all output data.
if (!$return['error']) { $return = array_merge($return, array(
$fileObject = Object::create($this->getRecordImageClass()); 'id' => $file->ID,
'name' => $file->getTitle() . '.' . $file->getExtension(),
// Get the uploaded file into a new file object. 'url' => $file->getURL(),
try { 'preview_url' => $file->setHeight(55)->Link(),
$upload->loadIntoFile($tmpfile, $fileObject, $this->component->getConfig('folderName')); 'thumbnail_url' => $file->SetRatioSize(40,30)->getURL(),
} catch (Exception $e) { 'size' => $file->getAbsoluteSize(),
// we shouldn't get an error here, but just in case //'buttons' => $file->UploadFieldFileButtons,
$return['error'] = $e->getMessage(); 'record' => array(
} 'ID' => $record->ID,
'fields' => $recordEditableFormFields
if (!$return['error']) { )
if ($upload->isError()) { ));
$return['error'] = implode(' '.PHP_EOL, $upload->getErrors());
} else {
$file = $upload->getFile();
// Attach the file to the related record.
$record->setField($this->getRecordImageField(), $file->ID);
$record->write();
//get record's CMS Fields
$recordEditableFormFields = $this->getRecordHTMLFormFields( $record->ID );
// Collect all output data.
$return = array_merge($return, array(
'id' => $file->ID,
'name' => $file->getTitle() . '.' . $file->getExtension(),
'url' => $file->getURL(),
'preview_url' => $file->setHeight(55)->Link(),
'thumbnail_url' => $file->SetRatioSize(40,30)->getURL(),
'size' => $file->getAbsoluteSize(),
//'buttons' => $file->UploadFieldFileButtons,
'record' => array(
'ID' => $record->ID,
'fields' => $recordEditableFormFields
)
));
}
}
}
$response = new SS_HTTPResponse(Convert::raw2json(array($return))); $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
$response->addHeader('Content-Type', 'text/plain'); $response->addHeader('Content-Type', 'text/plain');

View File

@ -10,7 +10,7 @@
/* ************************************************************************ /* ************************************************************************
* UPLOAD * UPLOAD
*/ */
.ss-assetuploadfield .ss-uploadfield-files .ss-uploadfield-item-editform .ss-assetuploadfield .ss-uploadfield-files .ss-uploadfield-item-editform
{ {
@ -31,7 +31,7 @@ li.ss-uploadfield-item.template-download .imgPreview
right: 10px; right: 10px;
} }
#BulkImageUploadField .ss-uploadfield-item-info.updated #BulkUploadField .ss-uploadfield-item-info.updated
{ {
background-color: #a4ca3a; background-color: #a4ca3a;
@ -43,7 +43,7 @@ li.ss-uploadfield-item.template-download .imgPreview
background-image: linear-gradient(top, #a4ca3a 0%, #59781D 100%); background-image: linear-gradient(top, #a4ca3a 0%, #59781D 100%);
} }
#BulkImageUploadField .ss-uploadfield-item-info.dirty #BulkUploadField .ss-uploadfield-item-info.dirty
{ {
background-color: #f2ba11; background-color: #f2ba11;
@ -55,11 +55,11 @@ li.ss-uploadfield-item.template-download .imgPreview
background-image: linear-gradient(top, #f2ba11 0%, #df6e00 100%); background-image: linear-gradient(top, #f2ba11 0%, #df6e00 100%);
} }
#BulkImageUploadField .ss-uploadfield-item-status.updated #BulkUploadField .ss-uploadfield-item-status.updated
{ {
color: #3b8716; color: #3b8716;
} }
#BulkImageUploadField .ss-uploadfield-item-status.dirty #BulkUploadField .ss-uploadfield-item-status.dirty
{ {
color: #f25000; color: #f25000;
} }

View File

@ -153,7 +153,9 @@
} }
}); });
}) });
return false;
} }
}); });
@ -195,7 +197,9 @@
} }
}); });
}); });
return false;
} }
}); });

View File

@ -1,13 +1,17 @@
jQuery(document).ready(function(){ jQuery(document).ready(function(){
window.tmpl.cache['GridFieldBulkImageUpload_downloadtemplate'] = tmpl( window.tmpl.cache['colymba-gfbiu-uploadfield-downloadtemplate'] = tmpl(
'{% for (var i=0, files=o.files, l=files.length, file=files[0]; i<l; file=files[++i]) { %}' + '{% for (var i=0, files=o.files, l=files.length, file=files[0]; i<l; file=files[++i]) { %}' +
'<li class="ss-uploadfield-item template-download{% if (file.error) { %} ui-state-error{% } %}" data-fileid="{%=file.id%}">' + '<li class="ss-uploadfield-item template-download{% if (file.error) { %} ui-state-error{% } %}" data-fileid="{%=file.id%}">' +
'<div class="ss-uploadfield-item-preview preview"><span>' + '<div class="ss-uploadfield-item-preview preview"><span>' +
'<img src="{%=file.thumbnail_url%}" alt="" />' + '<img src="{%=file.thumbnail_url%}" alt="" />' +
'</span></div>' + '</span></div>' +
'<div class="ss-uploadfield-item-info">' + '<div class="ss-uploadfield-item-info">' +
'{% if (!file.error) { %}' +
'<input type="hidden" name="{%=file.fieldname%}[Files][]" value="{%=file.id%}" />' +
'{% } %}' +
'<label class="ss-uploadfield-item-name">' + '<label class="ss-uploadfield-item-name">' +
'<span class="name" title="{%=file.name%}">{%=file.name%}</span> ' + '<span class="name" title="{%=file.name%}">{%=file.name%}</span> ' +
'<span class="size">{%=o.formatFileSize(file.size)%}</span>' +
'{% if (!file.error) { %}' + '{% if (!file.error) { %}' +
'<div class="ss-uploadfield-item-status ui-state-success-text" title="'+ss.i18n._t('UploadField.Uploaded', 'Uploaded')+'">'+ss.i18n._t('UploadField.Uploaded', 'Uploaded')+'</div>' + '<div class="ss-uploadfield-item-status ui-state-success-text" title="'+ss.i18n._t('UploadField.Uploaded', 'Uploaded')+'">'+ss.i18n._t('UploadField.Uploaded', 'Uploaded')+'</div>' +
'{% } else { %}' + '{% } else { %}' +
@ -17,11 +21,14 @@ jQuery(document).ready(function(){
'</label>' + '</label>' +
'{% if (file.error) { %}' + '{% if (file.error) { %}' +
'<div class="ss-uploadfield-item-actions">' + '<div class="ss-uploadfield-item-actions">' +
'<div class="ss-uploadfield-item-cancel ss-uploadfield-item-cancelfailed"><button class="icon icon-16">' + ss.i18n._t('UploadField.CANCEL', 'Cancel') + '</button></div>' + '<div class="ss-uploadfield-item-cancel ss-uploadfield-item-cancelfailed delete"><button class="icon icon-16" data-icon="delete" title="' + ss.i18n._t('UploadField.CANCELREMOVE', 'Cancel/Remove') + '">' + ss.i18n._t('UploadField.CANCELREMOVE', 'Cancel/Remove') + '</button></div>' +
'</div>' + '</div>' +
'{% } else { %}' +
//'<div class="ss-uploadfield-item-actions">{% print(file.buttons, true); %}</div>' +
'{% } %}' + '{% } %}' +
'</div>' + '</div>' +
'{% if (!file.error) { %}' + '{% if (!file.error) { %}' +
'<div class="ss-uploadfield-item-editform">'+ '<div class="ss-uploadfield-item-editform">'+
'<form action="" method="post" class="bulkImageUploadUpdateForm" name="BIUUF_{%=file.record.ID%}">'+ '<form action="" method="post" class="bulkImageUploadUpdateForm" name="BIUUF_{%=file.record.ID%}">'+
'<input type="hidden" name="record_{%=file.record.ID%}_ID" value="{%=file.record.ID%}"/>'+ '<input type="hidden" name="record_{%=file.record.ID%}_ID" value="{%=file.record.ID%}"/>'+
@ -32,9 +39,11 @@ jQuery(document).ready(function(){
'{% } %}' + '{% } %}' +
'</form>'+ '</form>'+
'</div>' + '</div>' +
'{% } %}' +
'{% } %}' +
'</li>' + '</li>' +
'{% } %}' '{% } %}'
); );
}); });
//'<div class="ss-uploadfield-item-editform loading"><iframe frameborder="0" src="{%=file.edit_url%}"></iframe></div>' +

View File

@ -1,3 +1,3 @@
<a id="bulkImageUploadGFButton" href="$Link" class="action action-detail ss-ui-action-constructive ss-ui-button ui-button ui-widget ui-state-default ui-corner-all new new-link" data-icon="add"> <a id="bulkImageUploadGFButton" href="$Link" class="action action-detail ss-ui-action-constructive ss-ui-button ui-button ui-widget ui-state-default ui-corner-all new new-link" data-icon="drive-upload">
$Label $Label
</a> </a>