@@ -11,34 +11,47 @@ trait Buttons
1111 // ------------
1212
1313 /**
14- * Reorder buttons to the CRUD table view.
14+ * Order the CRUD buttons. If certain button names are missing from the given order array
15+ * they will be pushed to the end of the button collection.
16+ *
1517 *
1618 * @param string $stack Stack where the buttons belongs. Options: top, line, bottom.
17- * @param array $buttons Name of the buttons. ['update', 'delete', 'show']
19+ * @param array $order Ordered name of the buttons. ['update', 'delete', 'show']
1820 */
19- public function reorderButtons ( $ stack , $ buttons )
21+ public function orderButtons ( string $ stack , array $ order )
2022 {
21- $ newBtns = collect ([]);
22-
23- $ this ->buttons ()->each (function ($ btn ) use ($ stack , $ newBtns ) {
24- if ($ btn ->stack != $ stack ) {
25- $ newBtns ->push ($ btn );
23+ $ newButtons = collect ([]);
24+ $ otherButtons = collect ([]);
25+
26+ // we get the buttons that belong to the specified stack
27+ $ stackButtons = $ this ->buttons ()->reject (function ($ item ) use ($ stack , $ otherButtons ) {
28+ if ($ item ->stack != $ stack ) {
29+ // if the button does not belong to this stack we just add it for merging later
30+ $ otherButtons ->push ($ item );
31+ return true ;
2632 }
33+ return false ;
2734 });
2835
29- collect ($ buttons )->each (function ($ btnKey ) use ($ newBtns ) {
30- $ btnInstance = $ this ->buttons ()->filter (function ($ btn ) use ($ btnKey ) {
31- return $ btn ->name == $ btnKey ;
32- })->first ();
33-
34- if (! $ btnInstance ) {
35- abort (500 , 'Sorry, button cannot be found ' );
36+ // we parse the ordered buttons
37+ collect ($ order )->each (function ($ btnKey ) use ($ newButtons , $ stackButtons ) {
38+ if (!$ button = $ stackButtons ->where ('name ' , $ btnKey )->first ()) {
39+ abort (500 , 'Button name [« ' . $ btnKey . '»] not found. ' );
3640 }
37-
38- $ newBtns ->push ($ btnInstance );
41+ $ newButtons ->push ($ button );
3942 });
4043
41- $ this ->setOperationSetting ('buttons ' , $ newBtns );
44+ // if the ordered buttons are less than the total number of buttons in the stack
45+ // we add the remaining buttons to the end of the ordered ones
46+ if (count ($ newButtons ) < count ($ stackButtons )) {
47+ foreach ($ stackButtons as $ button ) {
48+ if (!$ newButtons ->where ('name ' , $ button ->name )->first ()) {
49+ $ newButtons ->push ($ button );
50+ }
51+ }
52+ }
53+
54+ $ this ->setOperationSetting ('buttons ' , $ newButtons ->merge ($ otherButtons ));
4255 }
4356
4457 /**
0 commit comments