This commit is contained in:
Roël Couwenberg 2024-04-19 10:47:54 +00:00 committed by GitHub
commit d901ebf74e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 241 additions and 209 deletions

5
.gitignore vendored
View File

@ -6,4 +6,7 @@
.transifexrc .transifexrc
**/css/bourbon **/css/bourbon
**/.sass-cache **/.sass-cache
node_modules/ node_modules/
vendor/
public/
composer.lock

3
_config/config.yml Normal file
View File

@ -0,0 +1,3 @@
SilverStripe\Admin\LeftAndMain:
extra_requirements_javascript:
- "colymba/gridfield-bulk-editing-tools: client/dist/js/main.js"

View File

@ -1 +1 @@
!function(){"use strict";var e={157:function(e,t,i){var s;((s=i(311))&&s.__esModule?s:{default:s}).default.entwine("ss",(e=>{window.bulkTools={gridfieldRefresh(e,t){t.isError||(t.isDestructive?this.removeGridFieldRows(e,t.records.success):this.updateGridFieldRows(e,t.records.success),this.failedGridFieldRows(e,t.records.failed))},getGridFieldRow(e,t){return e.find(`.ss-gridfield-item[data-id="${t.id}"][data-class="${t.class}"]`)},cleanGridFieldRow(e){return e.removeClass("bt-deleted bt-failed bt-updated").removeAttr("bt-error")},removeGridFieldRows(e,t){t.forEach((function(t){this.getGridFieldRow(e,t).addClass("bt-deleted").fadeOut(2e3)}),this),e.entwine(".").entwine("ss").delay(2e3).reload()},failedGridFieldRows(e,t){t.forEach((function(t){this.getGridFieldRow(e,t).addClass("bt-failed").attr("bt-error",t.message)}),this)},updateGridFieldRows(t,i){t.find(".ss-gridfield-item.ss-gridfield-no-items").remove(),i.forEach((function(i){const s=this.getGridFieldRow(t,i),d=e(i.row).addClass("bt-updated");1===s.length?s.replaceWith(d):t.find(".ss-gridfield-items").prepend(d)}),this)}}}))},572:function(e,t,i){var s=n(i(311)),d=n(i(754));function n(e){return e&&e.__esModule?e:{default:e}}s.default.entwine("colymba",(e=>{e(".bulkManagerOptions").entwine({onmatch(){const t=this.parents("thead"),i=t.find("tr"),s=t.find([".filter-header",".sortable-header"].join(",")),d=i.index(this);let n=i.length-1;s.each(((e,t)=>{const s=i.index(t);s<n&&(n=s)})),d>n&&i.eq(n).insertAfter(e(this))}}),e("td.col-bulkSelect").entwine({onmouseover(){e(this).parents(".ss-gridfield-item").find(".edit-link").removeClass("edit-link").addClass("tempDisabledEditLink")},onmouseout(){e(this).parents(".ss-gridfield-item").find(".tempDisabledEditLink").addClass("edit-link").removeClass("tempDisabledEditLink")},onclick(t){const i=e(t.target).find("input");e(i).prop("checked")?e(i).prop("checked",!1):e(i).prop("checked",!0)}}),e("td.col-bulkSelect input").entwine({onmatch(){},onunmatch(){},onclick(){e(this).parents(".grid-field__table").find("input.bulkSelectAll").prop("checked","")}}),e("input.bulkSelectAll").entwine({onclick(){const t=e(this).prop("checked");e(this).parents(".grid-field__table").find("td.col-bulkSelect input").prop("checked",t).trigger("change")},getSelectRecordsID(){return e(this).parents(".grid-field__table").find("td.col-bulkSelect input:checked").map((function(){return parseInt(e(this).data("record"),10)})).get()}}),e("select.bulkActionName").entwine({onchange(){const t=e(this).val(),i=e(this).parents(".bulkManagerOptions").find(".doBulkActionButton"),s=i.data("config");if(e.each(s,((e,s)=>{e!==t&&i.removeClass(s.buttonClasses)})),t){if(i.removeClass("disabled"),i.addClass(s[t].buttonClasses).addClass("btn-outline-secondary"),s[t].icon){const e=i.find("img");e.length?e.attr("src",s[t].icon):i.prepend(`<img src="${s[t].icon}" alt="" />`)}else i.find("img").remove();s[t].destructive?i.addClass("btn-outline-danger"):i.removeClass("btn-outline-danger")}else i.addClass("disabled")}}),e(".doBulkActionButton").entwine({getActionURL(e,t){const i=(new Date).getTime();let s=t.split("?"),d="";return e&&(d=`/${e}`),s=s[1]?`${s[0]+d}?${s[1]}&cacheBuster=${i}`:`${s[0]+d}?cacheBuster=${i}`,s},onclick(){const t=e(this).parents(".bulkManagerOptions").find("select.bulkActionName").val(),i=e(this).parents(".bulkManagerOptions").find("input.bulkSelectAll:first").getSelectRecordsID();this.doBulkAction(t,i)},doBulkAction(t,i){const{bulkTools:s}=window,n=e(this).parents(".bulkManagerOptions"),a=n.find("a.doBulkActionButton"),r=n.find(".message"),l=a.data("config");let o=this.getActionURL(t,e(this).data("url"));const c={records:i};if(i.length<=0)return alert(d.default._t("GRIDFIELD_BULK_MANAGER.BULKACTION_EMPTY_SELECT")),!1;if(l[t].destructive&&!confirm(d.default._t("GRIDFIELD_BULK_MANAGER.CONFIRM_DESTRUCTIVE_ACTION")))return!1;if(a.addClass("loading"),r.removeClass("static show error warning"),l[t].xhr)e.ajax({url:o,data:c,type:"POST",context:e(this)}).always((function(t){let i=t;a.removeClass("loading"),t.responseText&&(i=JSON.parse(t.responseText)),r.html(i.message),i.isError?r.addClass("static error"):i.isWarning?r.addClass("show warning"):r.addClass("show"),s.gridfieldRefresh(e(this).parents(".ss-gridfield"),i)}));else{o=`${o}&${`records[]=${i.join("&records[]=")}`}`,window.location.href=o}return!0}})}))},453:function(e,t,i){var s;((s=i(311))&&s.__esModule?s:{default:s}).default.entwine("colymba",(e=>{e("#bulkEditToggle").entwine({onclick(){const t=this.parents("form").find(".ss-toggle .ui-accordion-header");let i=this.data("state");i=i&&"close"!==i?"close":"open",t.each((function(){const t=e(this);"open"!==i||t.hasClass("ui-state-active")||t.click(),"close"===i&&t.hasClass("ui-state-active")&&t.click()})),this.data("state",i)}}),e(".bulkEditingFieldHolder").entwine({onchange(){this.removeClass("updated"),this.hasClass("hasUpdate")||this.addClass("hasUpdate")}})}))},545:function(e,t,i){var s=n(i(311)),d=n(i(648));function n(e){return e&&e.__esModule?e:{default:e}}const{bulkTools:a}=window,r=e=>()=>(t,i)=>{let{type:d,payload:n}=i;switch(d){case"UPLOADFIELD_ADD_FILE":return-1!==n.fieldId.indexOf("_BU")&&n.file.id&&(e=>{const t=(0,s.default)(`#${e.fieldId}`),i=t.parents(".ss-gridfield"),d=t.data("schema");s.default.ajax(d.data.attachFileEndpoint.url,{method:d.data.attachFileEndpoint.method,data:{fileID:e.file.id}}).done((e=>{a.gridfieldRefresh(i,e)}))})(n),e(t,{type:d,payload:n});case"UPLOADFIELD_UPLOAD_SUCCESS":return-1!==n.fieldId.indexOf("_BU")&&(e=>{const t=(0,s.default)(`#${e.fieldId}`).parents(".ss-gridfield");a.gridfieldRefresh(t,e.json.bulkTools)})(n),e(t,{type:d,payload:n});default:return e(t,{type:d,payload:n})}};document.addEventListener("DOMContentLoaded",(()=>{d.default.transform("bulkUploaderTransformation",(e=>{e.reducer("assetAdmin",r)}))}))},648:function(e){e.exports=Injector},754:function(e){e.exports=i18n},311:function(e){e.exports=jQuery}},t={};function i(s){var d=t[s];if(void 0!==d)return d.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i(157),i(572),i(453),i(545)}(); !function(){"use strict";var e={157:function(e,t,i){var s;((s=i(311))&&s.__esModule?s:{default:s}).default.entwine("ss",(e=>{window.bulkTools={gridfieldRefresh(e,t){t.isError||(t.isDestructive?this.removeGridFieldRows(e,t.records.success):this.updateGridFieldRows(e,t.records.success),this.failedGridFieldRows(e,t.records.failed))},getGridFieldRow(e,t){return e.find(`.ss-gridfield-item[data-id="${t.id}"][data-class="${t.class}"]`)},cleanGridFieldRow(e){return e.removeClass("bt-deleted bt-failed bt-updated").removeAttr("bt-error")},removeGridFieldRows(e,t){t.forEach((function(t){this.getGridFieldRow(e,t).addClass("bt-deleted").fadeOut(2e3)}),this),e.entwine(".").entwine("ss").delay(2e3).reload()},failedGridFieldRows(e,t){t.forEach((function(t){this.getGridFieldRow(e,t).addClass("bt-failed").attr("bt-error",t.message)}),this)},updateGridFieldRows(t,i){t.find(".ss-gridfield-item.ss-gridfield-no-items").remove(),i.forEach((function(i){const s=this.getGridFieldRow(t,i),d=e(i.row).addClass("bt-updated");1===s.length?s.replaceWith(d):t.find(".ss-gridfield-items").prepend(d)}),this)}}}))},572:function(e,t,i){var s=n(i(311)),d=n(i(754));function n(e){return e&&e.__esModule?e:{default:e}}s.default.entwine("colymba",(e=>{e(".bulkManagerOptions").entwine({onmatch(){const t=this.parents("thead"),i=t.find("tr"),s=t.find([".filter-header",".sortable-header"].join(",")),d=i.index(this);let n=i.length-1;s.each(((e,t)=>{const s=i.index(t);s<n&&(n=s)})),d>n&&i.eq(n).insertAfter(e(this))}}),e("td.col-bulkSelect").entwine({onmouseover(){e(this).parents(".ss-gridfield-item").find(".edit-link").removeClass("edit-link").addClass("tempDisabledEditLink")},onmouseout(){e(this).parents(".ss-gridfield-item").find(".tempDisabledEditLink").addClass("edit-link").removeClass("tempDisabledEditLink")},onclick(t){const i=e(t.target).find("input");e(i).prop("checked")?e(i).prop("checked",!1):e(i).prop("checked",!0)}}),e("td.col-bulkSelect input").entwine({onmatch(){},onunmatch(){},onclick(){e(this).parents(".grid-field__table").find("input.bulkSelectAll").prop("checked","")}}),e("input.bulkSelectAll").entwine({onclick(){const t=e(this).prop("checked");e(this).parents(".grid-field__table").find("td.col-bulkSelect input").prop("checked",t).trigger("change")},getSelectRecordsID(){return e(this).parents(".grid-field__table").find("td.col-bulkSelect input:checked").map((function(){return parseInt(e(this).data("record"),10)})).get()}}),e("select.bulkActionName").entwine({onchange(){const t=e(this).val(),i=e(this).parents(".bulkManagerOptions").find(".doBulkActionButton"),s=i.data("config");if(e.each(s,((e,s)=>{e!==t&&i.removeClass(s.buttonClasses)})),t){if(i.removeClass("disabled"),i.addClass(s[t].buttonClasses).addClass("btn-outline-secondary"),s[t].icon){const e=i.find("img");e.length?e.attr("src",s[t].icon):i.prepend(`<img src="${s[t].icon}" alt="" />`)}else i.find("img").remove();s[t].destructive?i.addClass("btn-outline-danger"):i.removeClass("btn-outline-danger")}else i.addClass("disabled")}}),e(".doBulkActionButton").entwine({getActionURL(e,t){const i=(new Date).getTime();let s=t.split("?"),d="";return e&&(d=`/${e}`),s=s[1]?`${s[0]+d}?${s[1]}&cacheBuster=${i}`:`${s[0]+d}?cacheBuster=${i}`,s},onclick(){const t=e(this).parents(".bulkManagerOptions").find("select.bulkActionName").val(),i=e(this).parents(".bulkManagerOptions").find("input.bulkSelectAll:first").getSelectRecordsID();this.doBulkAction(t,i)},doBulkAction(t,i){const{bulkTools:s}=window,n=e(this).parents(".bulkManagerOptions"),a=n.find("a.doBulkActionButton"),r=n.find(".message"),l=a.data("config");let o=this.getActionURL(t,e(this).data("url"));const c={records:i};if(i.length<=0)return alert(d.default._t("GRIDFIELD_BULK_MANAGER.BULKACTION_EMPTY_SELECT")),!1;if(l[t].destructive&&!confirm(d.default._t("GRIDFIELD_BULK_MANAGER.CONFIRM_DESTRUCTIVE_ACTION")))return!1;if(a.addClass("loading"),r.removeClass("static show error warning"),l[t].xhr)e.ajax({url:o,data:c,type:"POST",context:e(this)}).always((function(t){let i=t;a.removeClass("loading"),t.responseText&&(i=JSON.parse(t.responseText)),r.html(i.message),i.isError?r.addClass("static error"):i.isWarning?r.addClass("show warning"):r.addClass("show"),s.gridfieldRefresh(e(this).parents(".ss-gridfield"),i)}));else{o=`${o}&${`records[]=${i.join("&records[]=")}`}`,window.location.href=o}return!0}})}))},453:function(e,t,i){var s;((s=i(311))&&s.__esModule?s:{default:s}).default.entwine("colymba",(e=>{e("#bulkEditToggle").entwine({onclick(){const t=this.parents("form").find(".ss-toggle .ui-accordion-header");let i=this.data("state");i=i&&"close"!==i?"close":"open",t.each((function(){const t=e(this);"open"!==i||t.hasClass("ui-state-active")||t.click(),"close"===i&&t.hasClass("ui-state-active")&&t.click()})),this.data("state",i)}}),e(".bulkEditingFieldHolder").entwine({onchange(){this.removeClass("updated"),this.hasClass("hasUpdate")||this.addClass("hasUpdate")}})}))},545:function(e,t,i){var s=n(i(311)),d=n(i(648));function n(e){return e&&e.__esModule?e:{default:e}}const{bulkTools:a}=window,r=e=>()=>(t,i)=>{let{type:d,payload:n}=i;switch(d){case"UPLOADFIELD_ADD_FILE":return-1!==n.fieldId.indexOf("_BU")&&n.file.id&&(e=>{const t=(0,s.default)(`#${e.fieldId}`),i=t.parents(".ss-gridfield"),d=t.data("schema");s.default.ajax(d.data.attachFileEndpoint.url,{method:d.data.attachFileEndpoint.method,data:{fileID:e.file.id}}).done((e=>{a.gridfieldRefresh(i,e)}))})(n),e(t,{type:d,payload:n});case"UPLOADFIELD_UPLOAD_SUCCESS":return-1!==n.fieldId.indexOf("_BU")&&(e=>{const t=(0,s.default)(`#${e.fieldId}`).parents(".ss-gridfield");a.gridfieldRefresh(t,e.json.bulkTools)})(n),e(t,{type:d,payload:n});default:return e(t,{type:d,payload:n})}};document.addEventListener("DOMContentLoaded",(()=>{d.default.transform("bulkUploaderTransformation",(e=>{e.reducer("assetAdmin",r)}))}))},648:function(e){e.exports=Injector},754:function(e){e.exports=i18n},311:function(e){e.exports=jQuery}},t={};function i(s){var d=t[s];if(void 0!==d)return d.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i(157),i(572),i(453),i(545)}();

View File

@ -1,18 +1,18 @@
/* global window, alert, confirm */ /* global window, alert, confirm */
import jQuery from 'jquery'; import jQuery from "jquery";
import i18n from 'i18n'; import i18n from "i18n";
jQuery.entwine('colymba', ($) => { jQuery.entwine("colymba", ($) => {
/** /**
* Makes sure the component is above the headers * Makes sure the component is above the headers
*/ */
$('.bulkManagerOptions').entwine({ $(".bulkManagerOptions").entwine({
onmatch() { onmatch() {
const $parent = this.parents('thead'); const $parent = this.parents("thead");
const $tr = $parent.find('tr'); const $tr = $parent.find("tr");
const targets = ['.filter-header', '.sortable-header']; const targets = [".filter-header", ".sortable-header"];
const $target = $parent.find(targets.join(',')); const $target = $parent.find(targets.join(","));
const index = $tr.index(this); const index = $tr.index(this);
let newIndex = $tr.length - 1; let newIndex = $tr.length - 1;
@ -30,77 +30,84 @@ jQuery.entwine('colymba', ($) => {
}, },
}); });
/** /**
* Bulkselect table cell behaviours * Bulkselect table cell behaviours
*/ */
$('td.col-bulkSelect').entwine({ $("td.col-bulkSelect").entwine({
onmouseover() { onmouseover() {
// disable default row click behaviour -> avoid navigation to edit form when // disable default row click behaviour -> avoid navigation to edit form when
// clicking the checkbox // clicking the checkbox
$(this).parents('.ss-gridfield-item').find('.edit-link').removeClass('edit-link') $(this)
.addClass('tempDisabledEditLink'); .parents(".ss-gridfield-item")
.find(".edit-link")
.removeClass("edit-link")
.addClass("tempDisabledEditLink");
}, },
onmouseout() { onmouseout() {
// re-enable default row click behaviour // re-enable default row click behaviour
$(this).parents('.ss-gridfield-item').find('.tempDisabledEditLink').addClass('edit-link') $(this)
.removeClass('tempDisabledEditLink'); .parents(".ss-gridfield-item")
.find(".tempDisabledEditLink")
.addClass("edit-link")
.removeClass("tempDisabledEditLink");
}, },
onclick(e) { onclick(e) {
// check/uncheck checkbox when clicking cell // check/uncheck checkbox when clicking cell
const cb = $(e.target).find('input'); const cb = $(e.target).find("input");
if (!$(cb).prop('checked')) { if (!$(cb).prop("checked")) {
$(cb).prop('checked', true); $(cb).prop("checked", true);
} else { } else {
$(cb).prop('checked', false); $(cb).prop("checked", false);
} }
} },
}); });
/** /**
* Individual select checkbox behaviour * Individual select checkbox behaviour
*/ */
$('td.col-bulkSelect input').entwine({ $("td.col-bulkSelect input").entwine({
onmatch() { onmatch() {},
}, onunmatch() {},
onunmatch() {
},
onclick() { onclick() {
$(this).parents('.grid-field__table').find('input.bulkSelectAll').prop('checked', ''); $(this)
} .parents(".grid-field__table")
.find("input.bulkSelectAll")
.prop("checked", "");
},
}); });
/** /**
* Bulkselect checkbox behaviours * Bulkselect checkbox behaviours
*/ */
$('input.bulkSelectAll').entwine({ $("input.bulkSelectAll").entwine({
onclick() { onclick() {
const state = $(this).prop('checked'); const state = $(this).prop("checked");
$(this).parents('.grid-field__table') $(this)
.find('td.col-bulkSelect input') .parents(".grid-field__table")
.prop('checked', state) .find("td.col-bulkSelect input")
.trigger('change'); .prop("checked", state)
.trigger("change");
}, },
getSelectRecordsID() { getSelectRecordsID() {
return $(this).parents('.grid-field__table') return $(this)
.find('td.col-bulkSelect input:checked') .parents(".grid-field__table")
.find("td.col-bulkSelect input:checked")
.map(function () { .map(function () {
return parseInt($(this).data('record'), 10); return parseInt($(this).data("record"), 10);
}) })
.get(); .get();
} },
}); });
/** /**
* Bulk action dropdown behaviours * Bulk action dropdown behaviours
*/ */
$('select.bulkActionName').entwine({ $("select.bulkActionName").entwine({
onchange() { onchange() {
const value = $(this).val(); const value = $(this).val();
const $parent = $(this).parents('.bulkManagerOptions'); const $parent = $(this).parents(".bulkManagerOptions");
const $btn = $parent.find('.doBulkActionButton'); const $btn = $parent.find(".doBulkActionButton");
const config = $btn.data('config'); const config = $btn.data("config");
$.each(config, (configKey, configData) => { $.each(config, (configKey, configData) => {
if (configKey !== value) { if (configKey !== value) {
@ -109,45 +116,45 @@ jQuery.entwine('colymba', ($) => {
}); });
if (!value) { if (!value) {
$btn.addClass('disabled'); $btn.addClass("disabled");
return; return;
} }
$btn.removeClass('disabled'); $btn.removeClass("disabled");
$btn.addClass(config[value].buttonClasses).addClass('btn-outline-secondary'); $btn
.addClass(config[value].buttonClasses)
.addClass("btn-outline-secondary");
if (config[value].icon) { if (config[value].icon) {
const $img = $btn.find('img'); const $img = $btn.find("img");
if ($img.length) { if ($img.length) {
$img.attr('src', config[value].icon); $img.attr("src", config[value].icon);
} else { } else {
$btn.prepend(`<img src="${config[value].icon}" alt="" />`); $btn.prepend(`<img src="${config[value].icon}" alt="" />`);
} }
} else { } else {
$btn.find('img').remove(); $btn.find("img").remove();
} }
if (config[value].destructive) { if (config[value].destructive) {
$btn.addClass('btn-outline-danger'); $btn.addClass("btn-outline-danger");
} else { } else {
$btn.removeClass('btn-outline-danger'); $btn.removeClass("btn-outline-danger");
} }
} },
}); });
/** /**
* bulk action button behaviours * bulk action button behaviours
*/ */
$('.doBulkActionButton').entwine({ $(".doBulkActionButton").entwine({
getActionURL(action, url) { getActionURL(action, url) {
const cacheBuster = new Date().getTime(); const cacheBuster = new Date().getTime();
let newUrl = url.split('?'); let newUrl = url.split("?");
let newAction = ''; let newAction = "";
if (action) { if (action) {
newAction = `/${action}`; newAction = `/${action}`;
} }
@ -160,9 +167,12 @@ jQuery.entwine('colymba', ($) => {
return newUrl; return newUrl;
}, },
onclick() { onclick() {
const $parent = $(this).parents('.bulkManagerOptions'); const $parent = $(this).parents(".bulkManagerOptions");
const action = $parent.find('select.bulkActionName').val(); const action = $parent.find("select.bulkActionName").val();
const ids = $(this).parents('.bulkManagerOptions').find('input.bulkSelectAll:first').getSelectRecordsID(); const ids = $(this)
.parents(".bulkManagerOptions")
.find("input.bulkSelectAll:first")
.getSelectRecordsID();
this.doBulkAction(action, ids); this.doBulkAction(action, ids);
}, },
@ -170,38 +180,40 @@ jQuery.entwine('colymba', ($) => {
doBulkAction(action, ids) { doBulkAction(action, ids) {
const { bulkTools } = window; const { bulkTools } = window;
const $parent = $(this).parents('.bulkManagerOptions'); const $parent = $(this).parents(".bulkManagerOptions");
const $btn = $parent.find('a.doBulkActionButton'); const $btn = $parent.find("a.doBulkActionButton");
const $msg = $parent.find('.message'); const $msg = $parent.find(".message");
const config = $btn.data('config'); const config = $btn.data("config");
let url = this.getActionURL(action, $(this).data('url')); let url = this.getActionURL(action, $(this).data("url"));
const inputData = { records: ids }; const inputData = { records: ids };
if (ids.length <= 0) { if (ids.length <= 0) {
alert(i18n._t('GRIDFIELD_BULK_MANAGER.BULKACTION_EMPTY_SELECT')); alert(i18n._t("GRIDFIELD_BULK_MANAGER.BULKACTION_EMPTY_SELECT"));
return false; return false;
} }
// if ( $btn.hasClass('ss-ui-action-destructive') ) // if ( $btn.hasClass('ss-ui-action-destructive') )
if (config[action].destructive) { if (config[action].destructive) {
if (!confirm(i18n._t('GRIDFIELD_BULK_MANAGER.CONFIRM_DESTRUCTIVE_ACTION'))) { if (
!confirm(i18n._t("GRIDFIELD_BULK_MANAGER.CONFIRM_DESTRUCTIVE_ACTION"))
) {
return false; return false;
} }
} }
$btn.addClass('loading'); $btn.addClass("loading");
$msg.removeClass('static show error warning'); $msg.removeClass("static show error warning");
if (config[action].xhr) { if (config[action].xhr) {
$.ajax({ $.ajax({
url, url,
data: inputData, data: inputData,
type: 'POST', type: "POST",
context: $(this) context: $(this),
}).always(function (data) { }).always(function (data) {
let returnData = data; let returnData = data;
$btn.removeClass('loading'); $btn.removeClass("loading");
// if request fail, return a +4xx status code, extract json response // if request fail, return a +4xx status code, extract json response
if (data.responseText) { if (data.responseText) {
@ -211,23 +223,26 @@ jQuery.entwine('colymba', ($) => {
$msg.html(returnData.message); $msg.html(returnData.message);
if (returnData.isError) { if (returnData.isError) {
$msg.addClass('static error'); $msg.addClass("static error");
} else if (returnData.isWarning) { } else if (returnData.isWarning) {
$msg.addClass('show warning'); $msg.addClass("show warning");
} else { } else {
$msg.addClass('show'); $msg.addClass("show");
} }
bulkTools.gridfieldRefresh($(this).parents('.ss-gridfield'), returnData); bulkTools.gridfieldRefresh(
$(this).parents(".ss-gridfield"),
returnData,
);
}); });
} else { } else {
const records = `records[]=${ids.join('&records[]=')}`; const records = `records[]=${ids.join("&records[]=")}`;
url = `${url}&${records}`; url = `${url}&${records}`;
window.location.href = url; window.location.href = url;
} }
return true; return true;
} },
}); });
}); });

View File

@ -1,49 +1,50 @@
/* global window */ /* global window */
import jQuery from 'jquery'; import jQuery from "jquery";
jQuery.entwine('colymba', ($) => { jQuery.entwine("colymba", ($) => {
/** /**
* Toggle all accordion forms * Toggle all accordion forms
* open or closed * open or closed
*/ */
$('#bulkEditToggle').entwine({ $("#bulkEditToggle").entwine({
onclick() { onclick() {
const toggleFields = this.parents('form').find('.ss-toggle .ui-accordion-header'); const toggleFields = this.parents("form").find(
let state = this.data('state'); ".ss-toggle .ui-accordion-header",
);
let state = this.data("state");
if (!state || state === 'close') { if (!state || state === "close") {
state = 'open'; state = "open";
} else { } else {
state = 'close'; state = "close";
} }
toggleFields.each(function () { toggleFields.each(function () {
const $this = $(this); const $this = $(this);
if (state === 'open' && !$this.hasClass('ui-state-active')) { if (state === "open" && !$this.hasClass("ui-state-active")) {
$this.click(); $this.click();
} }
if (state === 'close' && $this.hasClass('ui-state-active')) { if (state === "close" && $this.hasClass("ui-state-active")) {
$this.click(); $this.click();
} }
}); });
this.data('state', state); this.data("state", state);
} },
}); });
/** /**
* Contains each rocrds editing fields, * Contains each rocrds editing fields,
* tracks changes and updates... * tracks changes and updates...
*/ */
$('.bulkEditingFieldHolder').entwine({ $(".bulkEditingFieldHolder").entwine({
onchange() { onchange() {
this.removeClass('updated'); this.removeClass("updated");
if (!this.hasClass('hasUpdate')) { if (!this.hasClass("hasUpdate")) {
this.addClass('hasUpdate'); this.addClass("hasUpdate");
} }
} },
}); });
}); });

View File

@ -3,7 +3,12 @@
"type": "silverstripe-vendormodule", "type": "silverstripe-vendormodule",
"description": "SilverStripe GridField component to upload images/files and edit records in bulk", "description": "SilverStripe GridField component to upload images/files and edit records in bulk",
"homepage": "https://github.com/colymba/GridFieldBulkEditingTools", "homepage": "https://github.com/colymba/GridFieldBulkEditingTools",
"keywords": ["silverstripe", "bulk upload", "image upload", "gridfield bulk upload"], "keywords": [
"silverstripe",
"bulk upload",
"image upload",
"gridfield bulk upload"
],
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"authors": [ "authors": [
{ {
@ -16,8 +21,7 @@
} }
], ],
"require": { "require": {
"silverstripe/framework": "^5", "silverstripe/framework": "^5 || ^4"
"silverstripe/asset-admin": "^2"
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
@ -34,5 +38,11 @@
"Colymba\\BulkManager\\": "src/BulkManager/", "Colymba\\BulkManager\\": "src/BulkManager/",
"Colymba\\BulkUpload\\": "src/BulkUploader/" "Colymba\\BulkUpload\\": "src/BulkUploader/"
} }
},
"config": {
"allow-plugins": {
"composer/installers": true,
"silverstripe/vendor-plugin": true
}
} }
} }

View File

@ -1,7 +1,9 @@
# Bulk Manager # Bulk Manager
Perform actions on multiple records straight from the GridField. Comes with *unlink*, *delete* and bulk *editing*. You can also easily create/add your own.
Perform actions on multiple records straight from the GridField. Comes with _unlink_, _delete_ and bulk _editing_. You can also easily create/add your own.
## Usage ## Usage
Simply add component to your `GridFieldConfig` Simply add component to your `GridFieldConfig`
```php ```php
@ -9,6 +11,7 @@ $config->addComponent(new \Colymba\BulkManager\BulkManager());
``` ```
## Configuration ## Configuration
The component's options can be configurated individually or in bulk through the 'config' functions like this: The component's options can be configurated individually or in bulk through the 'config' functions like this:
```php ```php
@ -16,13 +19,17 @@ $config->getComponentByType('Colymba\\BulkManager\\BulkManager')->setConfig($ref
``` ```
### $config overview ### $config overview
The available configuration options are: The available configuration options are:
* 'editableFields' : array of string referencing specific CMS fields available for editing
- 'editableFields' : array of string referencing specific CMS fields available for editing
## Custom actions ## Custom actions
You can remove or add individual action or replace them all via `addBulkAction()` and `removeBulkAction()` You can remove or add individual action or replace them all via `addBulkAction()` and `removeBulkAction()`
### Adding a custom action ### Adding a custom action
To add a custom bulk action to the list use: To add a custom bulk action to the list use:
```php ```php
@ -32,9 +39,11 @@ $config
``` ```
#### Custom action handler #### Custom action handler
When creating your own bulk action `RequestHandler`, you should extend `Colymba\BulkManager\BulkAction\Handler` which will expose 2 useful functions `getRecordIDList()` and `getRecords()` returning either an array with the selected records IDs or a `DataList` of the selected records. When creating your own bulk action `RequestHandler`, you should extend `Colymba\BulkManager\BulkAction\Handler` which will expose 2 useful functions `getRecordIDList()` and `getRecords()` returning either an array with the selected records IDs or a `DataList` of the selected records.
Make sure to define the handler's `$url_segment`, from which the handler will be called and its relating `$allowed_actions` and `$url_handlers`. See `Handler`, `DeleteHandler` and `UnlinkHandler` for examples. Make sure to define the handler's `$url_segment`, from which the handler will be called and its relating `$allowed_actions` and `$url_handlers`. See `Handler`, `DeleteHandler` and `UnlinkHandler` for examples.
#### Front-end config #### Front-end config
Bulk action handler's front-end configuration is set via class properties `label`, `icon`, `buttonClasses`, `xhr` and `destructive`. See `Handler`, `DeleteHandler` and `UnlinkHandler` for reference and examples.
Bulk action handler's front-end configuration is set via class properties `label`, `icon`, `buttonClasses`, `xhr` and `destructive`. See `Handler`, `DeleteHandler` and `UnlinkHandler` for reference and examples.

View File

@ -19,7 +19,7 @@ class ArchiveHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'archive'; private static $url_segment = 'archive';
@ -42,14 +42,14 @@ class ArchiveHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Archive'; protected $label = 'Archive';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class ArchiveHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = 'font-icon-trash'; protected $buttonClasses = 'font-icon-trash';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = true; protected $destructive = true;
@ -100,13 +100,11 @@ class ArchiveHandler extends Handler
$response = new HTTPBulkToolsResponse(true, $this->gridField); $response = new HTTPBulkToolsResponse(true, $this->gridField);
try { try {
foreach ($records as $record) foreach ($records as $record) {
{
$done = $record->doArchive(); $done = $record->doArchive();
if ($done) if ($done) {
{
$response->addSuccessRecord($record); $response->addSuccessRecord($record);
}else{ } else {
$response->addFailedRecord($record, $done); $response->addFailedRecord($record, $done);
} }
} }

View File

@ -19,7 +19,7 @@ class DeleteHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'delete'; private static $url_segment = 'delete';
@ -42,14 +42,14 @@ class DeleteHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Delete'; protected $label = 'Delete';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class DeleteHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = 'font-icon-trash'; protected $buttonClasses = 'font-icon-trash';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = true; protected $destructive = true;

View File

@ -25,7 +25,7 @@ class EditHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'edit'; private static $url_segment = 'edit';
@ -54,14 +54,14 @@ class EditHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Edit'; protected $label = 'Edit';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -69,22 +69,22 @@ class EditHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = 'font-icon-edit'; protected $buttonClasses = 'font-icon-edit';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = false; protected $xhr = false;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = false; protected $destructive = false;
@ -108,7 +108,7 @@ class EditHandler extends Handler
*/ */
public function Link($action = null) public function Link($action = null)
{ {
return Controller::join_links(parent::Link(), $this->stat('url_segment'), $action); return Controller::join_links(parent::Link(), self::$url_segment, $action);
} }
/** /**
@ -130,7 +130,7 @@ class EditHandler extends Handler
FormAction::create('doSave', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.SAVE_BTN_LABEL', 'Save all')) FormAction::create('doSave', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.SAVE_BTN_LABEL', 'Save all'))
->setAttribute('id', 'bulkEditingSaveBtn') ->setAttribute('id', 'bulkEditingSaveBtn')
->addExtraClass('btn btn-success') ->addExtraClass('btn btn-success')
->setAttribute('data-icon', 'accept') ->setAttribute('data-icon', '! ')
->setUseButtonTag(true) ->setUseButtonTag(true)
); );
@ -138,10 +138,10 @@ class EditHandler extends Handler
FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel')) FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))
->setAttribute('id', 'bulkEditingUpdateCancelBtn') ->setAttribute('id', 'bulkEditingUpdateCancelBtn')
->addExtraClass('btn btn-danger cms-panel-link') ->addExtraClass('btn btn-danger cms-panel-link')
->setAttribute('data-icon', 'decline') ->setAttribute('data-icon', 'P ')
->setAttribute('href', $one_level_up->Link) ->setAttribute('href', $one_level_up->Link)
->setUseButtonTag(true) ->setUseButtonTag(true)
->setAttribute('src', '')//changes type to image so isn't hooked by default actions handlers ->setAttribute('src', '') //changes type to image so isn't hooked by default actions handlers
); );
$recordList = $this->getRecordIDList(); $recordList = $this->getRecordIDList();
@ -164,7 +164,7 @@ class EditHandler extends Handler
); );
$header = LiteralField::create( $header = LiteralField::create(
'bulkEditHeader', 'bulkEditHeader',
'<h1 id="bulkEditHeader">'.$headerText.'</h1>' '<h1 id="bulkEditHeader">' . $headerText . '</h1>'
); );
$recordsFieldList->push($header); $recordsFieldList->push($header);
@ -184,9 +184,9 @@ class EditHandler extends Handler
$record->getTitle(), $record->getTitle(),
$recordEditingFields $recordEditingFields
) )
->setHeadingLevel(4) ->setHeadingLevel(4)
->setAttribute('data-id', $id) ->setAttribute('data-id', $id)
->addExtraClass('bulkEditingFieldHolder'); ->addExtraClass('bulkEditingFieldHolder');
$recordsFieldList->push($toggleField); $recordsFieldList->push($toggleField);
} }
@ -206,7 +206,7 @@ class EditHandler extends Handler
//and add record ids GET var //and add record ids GET var
$bulkEditForm->setAttribute( $bulkEditForm->setAttribute(
'action', 'action',
$this->Link('bulkEditForm?records[]='.implode('&', $recordList)) $this->Link('bulkEditForm?records[]=' . implode('&', $recordList))
); );
return $bulkEditForm; return $bulkEditForm;

View File

@ -21,7 +21,7 @@ class Handler extends RequestHandler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = null; private static $url_segment = null;
@ -42,14 +42,14 @@ class Handler extends RequestHandler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Action'; protected $label = 'Action';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class Handler extends RequestHandler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = ''; protected $buttonClasses = '';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = false; protected $destructive = false;
@ -108,7 +108,7 @@ class Handler extends RequestHandler
/** /**
* Set if hanlder performs destructive actions * Set if hanlder performs destructive actions
* *
* @param boolean destructive If true, a warning will be shown on the front-end * @param boolean destructive If true, a warning will be shown on the front-end
* @return RequestHandler * @return RequestHandler
*/ */
@ -117,10 +117,10 @@ class Handler extends RequestHandler
$this->destructive = $destructive; $this->destructive = $destructive;
return $this; return $this;
} }
/** /**
* True if the hanlder performs destructive actions * True if the hanlder performs destructive actions
* *
* @return boolean * @return boolean
*/ */
public function getDestructive() public function getDestructive()
@ -130,11 +130,11 @@ class Handler extends RequestHandler
/** /**
* Set if handler is called via XHR * Set if handler is called via XHR
* *
* @param boolean xhr If true the handler will be called via an XHR from front-end * @param boolean xhr If true the handler will be called via an XHR from front-end
* @return RequestHandler * @return RequestHandler
*/ */
public function setXhr($xhr) public function setXhr($xhr)
{ {
$this->xhr = $xhr; $this->xhr = $xhr;

View File

@ -19,7 +19,7 @@ class PublishHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'publish'; private static $url_segment = 'publish';
@ -42,14 +42,14 @@ class PublishHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Publish'; protected $label = 'Publish';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class PublishHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = 'font-icon-rocket'; protected $buttonClasses = 'font-icon-rocket';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = false; protected $destructive = false;
@ -100,13 +100,11 @@ class PublishHandler extends Handler
$response = new HTTPBulkToolsResponse(false, $this->gridField); $response = new HTTPBulkToolsResponse(false, $this->gridField);
try { try {
foreach ($records as $record) foreach ($records as $record) {
{
$done = $record->publishRecursive(); $done = $record->publishRecursive();
if ($done) if ($done) {
{
$response->addSuccessRecord($record); $response->addSuccessRecord($record);
}else{ } else {
$response->addFailedRecord($record, $done); $response->addFailedRecord($record, $done);
} }
} }
@ -123,7 +121,7 @@ class PublishHandler extends Handler
$response->setStatusCode(500); $response->setStatusCode(500);
$response->setMessage($ex->getMessage()); $response->setMessage($ex->getMessage());
} }
return $response; return $response;
} }
} }

View File

@ -19,7 +19,7 @@ class UnPublishHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'unpublish'; private static $url_segment = 'unpublish';
@ -42,14 +42,14 @@ class UnPublishHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'UnPublish'; protected $label = 'UnPublish';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class UnPublishHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = ''; protected $buttonClasses = '';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = false; protected $destructive = false;
@ -98,15 +98,13 @@ class UnPublishHandler extends Handler
{ {
$records = $this->getRecords(); $records = $this->getRecords();
$response = new HTTPBulkToolsResponse(false, $this->gridField); $response = new HTTPBulkToolsResponse(false, $this->gridField);
try { try {
foreach ($records as $record) foreach ($records as $record) {
{
$done = $record->doUnpublish(); $done = $record->doUnpublish();
if ($done) if ($done) {
{
$response->addSuccessRecord($record); $response->addSuccessRecord($record);
}else{ } else {
$response->addFailedRecord($record, $done); $response->addFailedRecord($record, $done);
} }
} }

View File

@ -19,7 +19,7 @@ class UnlinkHandler extends Handler
/** /**
* URL segment used to call this handler * URL segment used to call this handler
* If none given, @BulkManager will fallback to the Unqualified class name * If none given, @BulkManager will fallback to the Unqualified class name
* *
* @var string * @var string
*/ */
private static $url_segment = 'unlink'; private static $url_segment = 'unlink';
@ -42,14 +42,14 @@ class UnlinkHandler extends Handler
/** /**
* Front-end label for this handler's action * Front-end label for this handler's action
* *
* @var string * @var string
*/ */
protected $label = 'Unlink'; protected $label = 'Unlink';
/** /**
* Front-end icon path for this handler's action. * Front-end icon path for this handler's action.
* *
* @var string * @var string
*/ */
protected $icon = ''; protected $icon = '';
@ -57,22 +57,22 @@ class UnlinkHandler extends Handler
/** /**
* Extra classes to add to the bulk action button for this handler * Extra classes to add to the bulk action button for this handler
* Can also be used to set the button font-icon e.g. font-icon-trash * Can also be used to set the button font-icon e.g. font-icon-trash
* *
* @var string * @var string
*/ */
protected $buttonClasses = 'font-icon-link-broken'; protected $buttonClasses = 'font-icon-link-broken';
/** /**
* Whether this handler should be called via an XHR from the front-end * Whether this handler should be called via an XHR from the front-end
* *
* @var boolean * @var boolean
*/ */
protected $xhr = true; protected $xhr = true;
/** /**
* Set to true is this handler will destroy any data. * Set to true is this handler will destroy any data.
* A warning and confirmation will be shown on the front-end. * A warning and confirmation will be shown on the front-end.
* *
* @var boolean * @var boolean
*/ */
protected $destructive = false; protected $destructive = false;

View File

@ -129,8 +129,7 @@ class BulkManager implements GridField_HTMLProvider, GridField_ColumnProvider, G
$handler = Injector::inst()->get($handlerClassName); $handler = Injector::inst()->get($handlerClassName);
$urlSegment = $handler->config()->get('url_segment'); $urlSegment = $handler->config()->get('url_segment');
if (!$urlSegment) if (!$urlSegment) {
{
$rc = new ReflectionClass($handlerClassName); $rc = new ReflectionClass($handlerClassName);
$urlSegment = $rc->getShortName(); $urlSegment = $rc->getShortName();
} }
@ -154,10 +153,8 @@ class BulkManager implements GridField_HTMLProvider, GridField_ColumnProvider, G
user_error("Provide either a class name or URL segment", E_USER_ERROR); user_error("Provide either a class name or URL segment", E_USER_ERROR);
} }
foreach ($this->config['actions'] as $url => $class) foreach ($this->config['actions'] as $url => $class) {
{ if ($handlerClassName === $class || $urlSegment === $url) {
if ($handlerClassName === $class || $urlSegment === $url)
{
unset($this->config['actions'][$url]); unset($this->config['actions'][$url]);
return $this; return $this;
} }
@ -290,7 +287,7 @@ class BulkManager implements GridField_HTMLProvider, GridField_ColumnProvider, G
->addExtraClass('bulkActionName no-change-track form-group--no-label') ->addExtraClass('bulkActionName no-change-track form-group--no-label')
->setAttribute('id', '') ->setAttribute('id', '')
->setEmptyString(_t('SilverStripe\Admin\LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...')); ->setEmptyString(_t('SilverStripe\Admin\LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...'));
$templateData = array( $templateData = array(
'Menu' => $dropDownActionsList->FieldHolder(), 'Menu' => $dropDownActionsList->FieldHolder(),

View File

@ -123,7 +123,7 @@ class HTTPBulkToolsResponse extends HTTPResponse
*/ */
public function addHeader($header, $value) public function addHeader($header, $value)
{ {
if($header === "content-type") { if ($header === "content-type") {
return $this; return $this;
} }
return parent::addHeader($header, $value); return parent::addHeader($header, $value);
@ -139,7 +139,7 @@ class HTTPBulkToolsResponse extends HTTPResponse
*/ */
public function removeHeader($header) public function removeHeader($header)
{ {
if($header === "content-type") { if ($header === "content-type") {
return $this; return $this;
} }
return parent::removeHeader($header); return parent::removeHeader($header);
@ -333,7 +333,7 @@ class HTTPBulkToolsResponse extends HTTPResponse
); );
foreach ($this->successRecords as $record) { foreach ($this->successRecords as $record) {
$data = array('id' => $record->ID, 'class' => str_replace('\\', '\\\\', $record->ClassName)); $data = array('id' => $record->ID, 'class' => str_replace('\\', '\\\\', $record->ClassName ?? ''));
if (!$this->removesRows) { if (!$this->removesRows) {
$data['row'] = $this->getRecordGridfieldRow($record); $data['row'] = $this->getRecordGridfieldRow($record);
} }

View File

@ -70,7 +70,7 @@ class BulkUploadHandler extends RequestHandler
* Add file ID to the Dataobject * Add file ID to the Dataobject
* Add DataObject to Gridfield list * Add DataObject to Gridfield list
* Publish DataObject if enabled * Publish DataObject if enabled
* *
* @param integer $fileID The newly uploaded/attached file ID * @param integer $fileID The newly uploaded/attached file ID
* *
* @return DataObject The new DataObject * @return DataObject The new DataObject
@ -86,7 +86,7 @@ class BulkUploadHandler extends RequestHandler
$fileRelationName = $this->component->getFileRelationName($this->gridField); $fileRelationName = $this->component->getFileRelationName($this->gridField);
$record->{"{$fileRelationName}ID"} = $fileID; $record->{"{$fileRelationName}ID"} = $fileID;
$record->write(); //HasManyList call write on record but not ManyManyList, so we call it here again $record->write(); //HasManyList call write on record but not ManyManyList, so we call it here again
$this->gridField->list->add($record); $this->gridField->list->add($record);
if ( if (
@ -111,9 +111,8 @@ class BulkUploadHandler extends RequestHandler
{ {
$assetAdmin = AssetAdmin::singleton(); $assetAdmin = AssetAdmin::singleton();
$uploadResponse = $assetAdmin->apiCreateFile($request); $uploadResponse = $assetAdmin->apiCreateFile($request);
if ($uploadResponse->getStatusCode() == 200) if ($uploadResponse->getStatusCode() == 200) {
{
$responseData = Convert::json2array($uploadResponse->getBody()); $responseData = Convert::json2array($uploadResponse->getBody());
$responseData = array_shift($responseData); $responseData = array_shift($responseData);
@ -121,7 +120,7 @@ class BulkUploadHandler extends RequestHandler
$bulkToolsResponse = new HTTPBulkToolsResponse(false, $this->gridField); $bulkToolsResponse = new HTTPBulkToolsResponse(false, $this->gridField);
$bulkToolsResponse->addSuccessRecord($record); $bulkToolsResponse->addSuccessRecord($record);
$responseData['bulkTools'] = json_decode($bulkToolsResponse->getBody() ?? ''); $responseData['bulkTools'] = json_decode($bulkToolsResponse->getBody() ?? '');
$uploadResponse->setBody(json_encode(array($responseData))); $uploadResponse->setBody(json_encode(array($responseData)));
} }

View File

@ -183,7 +183,8 @@ class BulkUploader implements GridField_HTMLProvider, GridField_URLHandler
$imageField = null; $imageField = null;
foreach ($hasOneFields as $field => $type) { foreach ($hasOneFields as $field => $type) {
if ($type === 'SilverStripe\\Assets\\Image' if (
$type === 'SilverStripe\\Assets\\Image'
|| $type === 'SilverStripe\\Assets\\File' || $type === 'SilverStripe\\Assets\\File'
|| is_subclass_of($type, 'SilverStripe\\Assets\\File') || is_subclass_of($type, 'SilverStripe\\Assets\\File')
) { ) {
@ -245,7 +246,7 @@ class BulkUploader implements GridField_HTMLProvider, GridField_URLHandler
$uploadField = BulkUploadField::create($gridField, $fieldName, '') $uploadField = BulkUploadField::create($gridField, $fieldName, '')
->setForm($gridField->getForm()) ->setForm($gridField->getForm())
->setRecord(DataObject::create()) // avoid UploadField to get auto-config from the Page (e.g fix allowedMaxFileNumber) ->setRecord(DataObject::create()) // avoid UploadField to get auto-config from the Page (e.g fix allowedMaxFileNumber)
; ;
//UploadField setup //UploadField setup
foreach ($this->ufSetup as $fn => $param) { foreach ($this->ufSetup as $fn => $param) {
@ -293,8 +294,8 @@ class BulkUploader implements GridField_HTMLProvider, GridField_URLHandler
'Colspan' => (count($gridField->getColumns() ?? [])), 'Colspan' => (count($gridField->getColumns() ?? [])),
'UploadField' => $uploadField->Field() // call ->Field() to get requirements in right order 'UploadField' => $uploadField->Field() // call ->Field() to get requirements in right order
)); ));
//This one is no longer needed since the javascript is now loaded at the top of the cms
Requirements::javascript('colymba/gridfield-bulk-editing-tools:client/dist/js/main.js'); //Requirements::javascript('colymba/gridfield-bulk-editing-tools:client/dist/js/main.js');
Requirements::css('colymba/gridfield-bulk-editing-tools:client/dist/styles/main.css'); Requirements::css('colymba/gridfield-bulk-editing-tools:client/dist/styles/main.css');
Requirements::add_i18n_javascript('colymba/gridfield-bulk-editing-tools:client/lang'); Requirements::add_i18n_javascript('colymba/gridfield-bulk-editing-tools:client/lang');