1
1
<?php namespace Jacob \LogBook \FormWidgets ;
2
2
3
3
use Backend \Classes \FormWidgetBase ;
4
+ use Illuminate \Routing \Redirector ;
5
+ use Jacob \LogBook \Classes \Entities \Changes ;
6
+ use Jacob \Logbook \Models \Log ;
4
7
5
8
/**
6
9
* LogBook Form Widget
@@ -23,6 +26,12 @@ class LogBook extends FormWidgetBase
23
26
/** @var array|string|null */
24
27
public $ showLogRelations = null ;
25
28
29
+ /** @var bool $showUndoChangeButton */
30
+ public $ showUndoChangesButton = true ;
31
+
32
+ /** @var bool $refreshFromAfterUndo */
33
+ public $ refreshFormAfterUndo = true ;
34
+
26
35
/**
27
36
* @inheritDoc
28
37
*/
@@ -32,6 +41,8 @@ public function init()
32
41
'limitPerPage ' ,
33
42
'startPage ' ,
34
43
'showLogRelations ' ,
44
+ 'showUndoChangesButton ' ,
45
+ 'refreshFormAfterUndo ' ,
35
46
]);
36
47
}
37
48
@@ -60,6 +71,7 @@ public function prepareVars()
60
71
61
72
$ this ->vars ['name ' ] = $ this ->formField ->getName ();
62
73
$ this ->vars ['model ' ] = $ this ->model ;
74
+ $ this ->vars ['showUndoChangesButton ' ] = $ this ->showUndoChangesButton ;
63
75
}
64
76
65
77
/**
@@ -81,7 +93,7 @@ public function prepareLogs()
81
93
*/
82
94
public function onLogBookChangePage ()
83
95
{
84
- $ page = (int )post ('page ' );
96
+ $ page = (int )post ('page ' , 1 );
85
97
$ this ->prepareVars ();
86
98
$ this ->vars ['logs ' ] = $ this ->model ->getLogsFromLogBook (
87
99
$ this ->limitPerPage ,
@@ -94,6 +106,45 @@ public function onLogBookChangePage()
94
106
];
95
107
}
96
108
109
+ /**
110
+ * Undo change from logbook
111
+ *
112
+ * @return mixed
113
+ * @throws \Exception
114
+ */
115
+ public function onLogBookUndoChange ()
116
+ {
117
+ $ id = post ('id ' , null );
118
+
119
+ /** @var Log $log */
120
+ $ log = Log::find ($ id );
121
+
122
+ if (!$ log || ($ log ->getAttribute ('changes ' )['type ' ] ?? null ) !== Changes::TYPE_UPDATED ) {
123
+ return $ this ->onLogBookChangePage ();
124
+ }
125
+
126
+ /** @var \Model $modelInstance */
127
+ $ modelInstance = app ($ log ->getAttribute ('model ' ));
128
+
129
+ /** @var \Model $changedModel */
130
+ $ changedModel = $ modelInstance ->find ($ log ->getAttribute ('model_key ' ));
131
+
132
+ /** @var array $changedAttribute */
133
+ foreach ($ log ->getAttribute ('changes ' )['changedAttributes ' ] ?? [] as $ changedAttribute ) {
134
+ $ changedModel ->setAttribute ($ changedAttribute ['column ' ], $ changedAttribute ['old ' ]);
135
+ }
136
+
137
+ $ changedModel ->save ();
138
+
139
+ if ($ this ->refreshFormAfterUndo ) {
140
+ /** @var Redirector $redirect */
141
+ $ redirect = resolve (Redirector::class);
142
+ return $ redirect ->refresh ();
143
+ }
144
+
145
+ return $ this ->onLogBookChangePage ();
146
+ }
147
+
97
148
/**
98
149
* @param mixed $value
99
150
* @return null|string
0 commit comments