Bonjour à tous,
Je galère depuis plusieurs jours sur une fonctionnalité que je cherche à implémenter sur l'espace utilisateur l'ajout d'un avatar depuis une image.
Soit j'ai ce messagesoit l'upload / l'update ne fonctionne pas.Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
Déjà que je n'ai plus trop de cheveux sur la tête mais je continue à me les arracher.
Pour palier au message d'erreur j'ai implémenté l'interface \Serialize avec les functions requises mais là pas d'upload et quand j'y arrive en bidouillant pas d'update
Je vous partage mon code dites moi ce que vous en pensez :
User Entity
UserType
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459 <?php namespace App\Entity; use App\Repository\UserRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @ORM\Entity(repositoryClass=UserRepository::class) * @ORM\Table(name="`user`") * @UniqueEntity(fields={"username"}, message="Le nom d'utilisateur existe déjà") * @Vich\Uploadable */ class User implements UserInterface, PasswordAuthenticatedUserInterface { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=180, unique=true) * @Assert\NotBlank(message="le champs nom d'utilateur ne peut être vide") * @Assert\NotNull(message="le champs nom d'utilateur ne peut être vide") */ private $username; /** * @ORM\Column(type="json") * @Assert\NotNull(message="Veuillez spécifier au moins un rôle à l'utilisateur") */ private $roles = []; /** * @var string The hashed password * @ORM\Column(type="string") * @Assert\NotNull * @Assert\NotBlank(message="le mot de passe ne peut être vide") */ private $password; /** * @ORM\Column(type="string", length=255) * @Assert\NotNull(message="le prénom ne peut être vide") * @Assert\NotBlank(message="le prénom ne peut être vide") */ private $firstname; /** * @ORM\Column(type="string", length=255) * @Assert\NotNull(message="le nom ne peut être vide") * @Assert\NotBlank(message="le nom ne peut être vide") */ private $lastname; /** * @ORM\Column(type="datetime_immutable") */ private $createdAt; /** * @ORM\OneToMany(targetEntity=FileUpload::class, mappedBy="user", orphanRemoval=true) */ private $fileUploads; /** * @ORM\OneToMany(targetEntity=Attendance::class, mappedBy="user", cascade={"persist", "remove"}) */ private $attendances; /** * @ORM\OneToMany(targetEntity=Attendance::class, mappedBy="addedBy", cascade={"persist", "remove"}) */ private $attendanceOwner; /** * @ORM\Column(type="datetime_immutable", nullable=true) */ private $leaveAt; /** * @ORM\Column(type="string", length=255) */ private $gender; /** * @ORM\Column(type="text", nullable=true) */ private $signature; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $description; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $avatar; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="userAvatar", fileNameProperty="avatar") * * @var File|null */ private $imageFile; /** * If manually uploading a file (i.e. not using Symfony Form) ensure an instance * of 'UploadedFile' is injected into this setter to trigger the update. If this * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter * must be able to accept an instance of 'File' as the bundle will inject one here * during Doctrine hydration. * * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile */ public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } public function __construct() { $this->surveys = new ArrayCollection(); $this->categories = new ArrayCollection(); $this->fields = new ArrayCollection(); $this->fileUploads = new ArrayCollection(); $this->attendances = new ArrayCollection(); $this->attendanceOwner = new ArrayCollection(); } public function getId(): ?int { return $this->id; } /** * @deprecated since Symfony 5.3, use getUserIdentifier instead */ public function getUsername(): string { return (string) $this->username; } public function setUsername(string $username): self { $this->username = $username; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUserIdentifier(): string { return (string) $this->username; } /** * @see UserInterface */ public function getRoles(): array { $roles = $this->roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function setRoles(array $roles): self { $this->roles = $roles; return $this; } /** * @see PasswordAuthenticatedUserInterface */ public function getPassword(): string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } /** * Returning a salt is only needed, if you are not using a modern * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml. * * @see UserInterface */ public function getSalt(): ?string { return null; } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } public function getFirstname(): ?string { return $this->firstname; } public function setFirstname(string $firstname): self { $this->firstname = $firstname; return $this; } public function getLastname(): ?string { return $this->lastname; } public function setLastname(string $lastname): self { $this->lastname = $lastname; return $this; } public function getCreatedAt(): ?\DateTimeImmutable { return $this->createdAt; } public function setCreatedAt(\DateTimeImmutable $createdAt): self { $this->createdAt = $createdAt; return $this; } /** * @return Collection|FileUpload[] */ public function getFileUploads(): Collection { return $this->fileUploads; } public function addFileUpload(FileUpload $fileUpload): self { if (!$this->fileUploads->contains($fileUpload)) { $this->fileUploads[] = $fileUpload; $fileUpload->setUser($this); } return $this; } public function removeFileUpload(FileUpload $fileUpload): self { if ($this->fileUploads->removeElement($fileUpload)) { // set the owning side to null (unless already changed) if ($fileUpload->getUser() === $this) { $fileUpload->setUser(null); } } return $this; } /** * @return Collection|Attendance[] */ public function getAttendances(): Collection { return $this->attendances; } public function addAttendance(Attendance $attendance): self { if (!$this->attendances->contains($attendance)) { $this->attendances[] = $attendance; $attendance->setUser($this); } return $this; } public function removeAttendance(Attendance $attendance): self { if ($this->attendances->removeElement($attendance)) { // set the owning side to null (unless already changed) if ($attendance->getUser() === $this) { $attendance->setUser(null); } } return $this; } /** * @return Collection|Attendance[] */ public function getAttendanceOwner(): Collection { return $this->attendanceOwner; } public function addAttendanceOwner(Attendance $attendanceOwner): self { if (!$this->attendanceOwner->contains($attendanceOwner)) { $this->attendanceOwner[] = $attendanceOwner; $attendanceOwner->setAddedBy($this); } return $this; } public function removeAttendanceOwner(Attendance $attendanceOwner): self { if ($this->attendanceOwner->removeElement($attendanceOwner)) { // set the owning side to null (unless already changed) if ($attendanceOwner->getAddedBy() === $this) { $attendanceOwner->setAddedBy(null); } } return $this; } function __toString() { return $this->username; } public function getLeaveAt(): ?\DateTimeImmutable { return $this->leaveAt; } public function setLeaveAt(?\DateTimeImmutable $leaveAt): self { $this->leaveAt = $leaveAt; return $this; } public function haveRole($role) { return in_array($role, $this->getRoles()); } public function getGender(): ?string { return $this->gender; } public function setGender(string $gender): self { $this->gender = $gender; return $this; } public function getSignature(): ?string { return $this->signature; } public function setSignature(?string $signature): self { $this->signature = $signature; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): self { $this->description = $description; return $this; } public function getAvatar(): ?string { return $this->avatar; } public function setAvatar(?string $avatar): self { $this->avatar = $avatar; return $this; } }
UserController
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459 <?php namespace App\Entity; use App\Repository\UserRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @ORM\Entity(repositoryClass=UserRepository::class) * @ORM\Table(name="`user`") * @UniqueEntity(fields={"username"}, message="Le nom d'utilisateur existe déjà") * @Vich\Uploadable */ class User implements UserInterface, PasswordAuthenticatedUserInterface { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=180, unique=true) * @Assert\NotBlank(message="le champs nom d'utilateur ne peut être vide") * @Assert\NotNull(message="le champs nom d'utilateur ne peut être vide") */ private $username; /** * @ORM\Column(type="json") * @Assert\NotNull(message="Veuillez spécifier au moins un rôle à l'utilisateur") */ private $roles = []; /** * @var string The hashed password * @ORM\Column(type="string") * @Assert\NotNull * @Assert\NotBlank(message="le mot de passe ne peut être vide") */ private $password; /** * @ORM\Column(type="string", length=255) * @Assert\NotNull(message="le prénom ne peut être vide") * @Assert\NotBlank(message="le prénom ne peut être vide") */ private $firstname; /** * @ORM\Column(type="string", length=255) * @Assert\NotNull(message="le nom ne peut être vide") * @Assert\NotBlank(message="le nom ne peut être vide") */ private $lastname; /** * @ORM\Column(type="datetime_immutable") */ private $createdAt; /** * @ORM\OneToMany(targetEntity=FileUpload::class, mappedBy="user", orphanRemoval=true) */ private $fileUploads; /** * @ORM\OneToMany(targetEntity=Attendance::class, mappedBy="user", cascade={"persist", "remove"}) */ private $attendances; /** * @ORM\OneToMany(targetEntity=Attendance::class, mappedBy="addedBy", cascade={"persist", "remove"}) */ private $attendanceOwner; /** * @ORM\Column(type="datetime_immutable", nullable=true) */ private $leaveAt; /** * @ORM\Column(type="string", length=255) */ private $gender; /** * @ORM\Column(type="text", nullable=true) */ private $signature; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $description; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $avatar; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="userAvatar", fileNameProperty="avatar") * * @var File|null */ private $imageFile; /** * If manually uploading a file (i.e. not using Symfony Form) ensure an instance * of 'UploadedFile' is injected into this setter to trigger the update. If this * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter * must be able to accept an instance of 'File' as the bundle will inject one here * during Doctrine hydration. * * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile */ public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } public function __construct() { $this->surveys = new ArrayCollection(); $this->categories = new ArrayCollection(); $this->fields = new ArrayCollection(); $this->fileUploads = new ArrayCollection(); $this->attendances = new ArrayCollection(); $this->attendanceOwner = new ArrayCollection(); } public function getId(): ?int { return $this->id; } /** * @deprecated since Symfony 5.3, use getUserIdentifier instead */ public function getUsername(): string { return (string) $this->username; } public function setUsername(string $username): self { $this->username = $username; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUserIdentifier(): string { return (string) $this->username; } /** * @see UserInterface */ public function getRoles(): array { $roles = $this->roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function setRoles(array $roles): self { $this->roles = $roles; return $this; } /** * @see PasswordAuthenticatedUserInterface */ public function getPassword(): string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } /** * Returning a salt is only needed, if you are not using a modern * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml. * * @see UserInterface */ public function getSalt(): ?string { return null; } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } public function getFirstname(): ?string { return $this->firstname; } public function setFirstname(string $firstname): self { $this->firstname = $firstname; return $this; } public function getLastname(): ?string { return $this->lastname; } public function setLastname(string $lastname): self { $this->lastname = $lastname; return $this; } public function getCreatedAt(): ?\DateTimeImmutable { return $this->createdAt; } public function setCreatedAt(\DateTimeImmutable $createdAt): self { $this->createdAt = $createdAt; return $this; } /** * @return Collection|FileUpload[] */ public function getFileUploads(): Collection { return $this->fileUploads; } public function addFileUpload(FileUpload $fileUpload): self { if (!$this->fileUploads->contains($fileUpload)) { $this->fileUploads[] = $fileUpload; $fileUpload->setUser($this); } return $this; } public function removeFileUpload(FileUpload $fileUpload): self { if ($this->fileUploads->removeElement($fileUpload)) { // set the owning side to null (unless already changed) if ($fileUpload->getUser() === $this) { $fileUpload->setUser(null); } } return $this; } /** * @return Collection|Attendance[] */ public function getAttendances(): Collection { return $this->attendances; } public function addAttendance(Attendance $attendance): self { if (!$this->attendances->contains($attendance)) { $this->attendances[] = $attendance; $attendance->setUser($this); } return $this; } public function removeAttendance(Attendance $attendance): self { if ($this->attendances->removeElement($attendance)) { // set the owning side to null (unless already changed) if ($attendance->getUser() === $this) { $attendance->setUser(null); } } return $this; } /** * @return Collection|Attendance[] */ public function getAttendanceOwner(): Collection { return $this->attendanceOwner; } public function addAttendanceOwner(Attendance $attendanceOwner): self { if (!$this->attendanceOwner->contains($attendanceOwner)) { $this->attendanceOwner[] = $attendanceOwner; $attendanceOwner->setAddedBy($this); } return $this; } public function removeAttendanceOwner(Attendance $attendanceOwner): self { if ($this->attendanceOwner->removeElement($attendanceOwner)) { // set the owning side to null (unless already changed) if ($attendanceOwner->getAddedBy() === $this) { $attendanceOwner->setAddedBy(null); } } return $this; } function __toString() { return $this->username; } public function getLeaveAt(): ?\DateTimeImmutable { return $this->leaveAt; } public function setLeaveAt(?\DateTimeImmutable $leaveAt): self { $this->leaveAt = $leaveAt; return $this; } public function haveRole($role) { return in_array($role, $this->getRoles()); } public function getGender(): ?string { return $this->gender; } public function setGender(string $gender): self { $this->gender = $gender; return $this; } public function getSignature(): ?string { return $this->signature; } public function setSignature(?string $signature): self { $this->signature = $signature; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): self { $this->description = $description; return $this; } public function getAvatar(): ?string { return $this->avatar; } public function setAvatar(?string $avatar): self { $this->avatar = $avatar; return $this; } }
vichuploader.yaml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251 <?php namespace App\Controller; use App\Entity\Signature; use App\Entity\User; use App\Form\EditUserType; use App\Form\FileUploadType; use App\Form\UserType; use App\Repository\SignatureRepository; use App\Repository\UserRepository; use DateTimeImmutable; use Doctrine\ORM\EntityManagerInterface; use Faker\Provider\Image; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Console\SignalRegistry\SignalRegistry; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Security\Core\Security; use Vich\UploaderBundle\Form\Type\VichImageType; class UserController extends AbstractController { private $security; public function __construct(Security $security) { // Avoid calling getUser() in the constructor: auth may not // be complete yet. Instead, store the entire Security object. $this->security = $security; } /** * @Route("/admin/user/add", name="user_add") */ public function new(Request $request, EntityManagerInterface $em): Response { $form = $this->createForm(UserType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user = $form->getData(); $em->persist($user); $em->flush(); return $this->redirectToRoute("user_index"); } return $this->render("user/new.html.twig", [ "form" => $form->createView() ]); } /** * @Route("/profile/user/edit/{id<\d+>}", name="user_edit") */ public function edit(Request $request, EntityManagerInterface $em,User $user ): Response { $form = $this->createForm(UserType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user = $form->getData(); $em->persist($user); $em->flush(); return $this->redirectToRoute("user_view", ["id"=>$user->getId()]); } return $this->render("user/edit.html.twig", [ "form" => $form->createView(), "user"=>$user ]); } /** * @Route("/profile/user/{id<\d+>}", name="user_view") */ public function view(Request $request, User $user, EntityManagerInterface $em, UserPasswordHasherInterface $encoder): Response { if($this->security->getUser() == $user || in_array("ROLE_ADMIN", $this->security->getUser()->getRoles())){ $form = $this->createForm(UserType::class, $user); $form = $this->createForm(FileUploadType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { /** * @var FileUpload $task */ $task = $form->getData(); $user = $this->getUser(); $task->setUser($user); $em->persist($task); $em->flush(); return $this->render("user/view.html.twig", [ 'user' => $user, "form"=>$form->createView() ]); } return $this->render("user/view.html.twig", [ 'user' => $user, "form"=>$form->createView() ]); } return $this->render("user/view.html.twig", [ 'user' => $this->security->getUser() ]); } /** * @Route("/admin/users", name="user_index") */ public function index(UserRepository $userRepository): Response { $admins = array_filter( $userRepository->findBy([], ["lastname" => "ASC"]), function($user){ /** * @var User $user */ return $user->haveRole("ROLE_ADMIN"); }); $employees = array_filter( $userRepository->findBy([], ["lastname" => "ASC"]), function($user){ /** * @var User $user */ return $user->haveRole("ROLE_EMPLOYEE") && $user->getLeaveAt() == NULL; }); $haveLeave = array_filter( $userRepository->findBy([], ["leaveAt" => "DESC"]), function($user){ /** * @var User $user */ return $user->getLeaveAt() != NULL; }); return $this->render('user/index.html.twig', [ 'admins' => $admins, 'employees' => $employees,'haveLeave' => $haveLeave, ]); } /** * @Route("api", name="api") */ public function getWord(): JsonResponse { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < 6; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return new JsonResponse($randomString); } /** * @Route("/admin/user/delete/{id<\d+>}", name="user_delete") */ public function delete(User $user, EntityManagerInterface $em) { $em->remove($user); $em->flush(); return $this->redirectToRoute('user_index'); } /** * @Route("/admin/user/haveLeave/{id<\d+>}", name="user_leave") */ public function leave(User $user, EntityManagerInterface $em) { // $em->remove($user); $user ->setLeaveAt(new DateTimeImmutable()) ->setRoles([]); $em->flush(); return $this->redirectToRoute('user_index'); } /** * @Route("/admin/user/haveNotLeave/{id<\d+>}", name="user_not_leave") */ public function notLeave(User $user, EntityManagerInterface $em) { // $em->remove($user); $user ->setLeaveAt(NULL) ->setRoles(["ROLE_EMPLOYEE"]); $em->flush(); return $this->redirectToRoute('user_index'); } /** * @Route("/{id<\d+>}", name="notAvailable") */ public function notAvailable(User $user) { return $this->render('user/notAvailable.html.twig', ["user"=>$user]); } // /** // * @Route("/profile/user/signature", name="signature_add", methods={"POST"}) // */ // public function signatureAdd(EntityManagerInterface $em, Request $request, SignatureRepository $signatureRepository) :JsonResponse // { // /** // * @var User $user // */ // $user = $this->security->getUser(); // $file = $request->request->get('signature'); // if ($file) { // $oldSignature = $signatureRepository->findOneBy(['user' => $user]); // if ($oldSignature) { // $signature = $oldSignature; // if(file_exists("assets/img/user/".$oldSignature->getImageName())) // { unlink("assets/img/user/".$oldSignature->getImageName());} // $em->remove($signature); // $em->flush(); // } // $file = str_replace('data:image/png;base64,', '', $file); // $file = str_replace(' ', '+', $file); // $fileData = base64_decode($file); // $fileName = $user->getUserIdentifier() . ".png"; // file_put_contents("assets/img/user/signature".$fileName, $fileData); // $signature->setImageName($fileName); // $signature->setUser($user); // $em->persist($signature); // $em->flush(); // return new JsonResponse(['status'=>'success', 'filename'=>$fileName]); // } // return new JsonResponse(['status'=>'error']); // } }
Code yaml : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14 vich_uploader: db_driver: orm mappings: fileUpload: uri_prefix: /assets/vichFiles upload_destination: "%kernel.project_dir%/public/assets/vichFiles" namer: Vich\UploaderBundle\Naming\SmartUniqueNamer userAvatar: uri_prefix: /assets/user upload_destination: "%kernel.project_dir%/public/assets/img/user" namer: Vich\UploaderBundle\Naming\SmartUniqueNamer delete_on_remove: true delete_on_update: true
Au cas où mon subscriber
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 <?php namespace App\Subscriber; use App\Entity\Attendance; use App\Entity\Avatar; use DateTimeImmutable; use App\Entity\Field; use App\Entity\Category; use App\Entity\Contact; use App\Entity\FileCategory; use App\Entity\FileUpload; use App\Entity\Survey; use App\Entity\User; use App\Repository\UserRepository; use Doctrine\ORM\Events; use Doctrine\Common\EventSubscriber; use Symfony\Component\Security\Core\Security; use Doctrine\Persistence\Event\LifecycleEventArgs; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\PasswordHasher\PasswordHasherInterface; class CreateAndUpdateSubscriber implements EventSubscriber { protected $security; public function __construct(Security $security, UserPasswordHasherInterface $passwordHasher, UserRepository $userRepository) { $this->passwordHasher = $passwordHasher; $this->security = $security; $this->userRepository = $userRepository; date_default_timezone_set('Europe/Paris'); } public function getSubscribedEvents() { return [ Events::prePersist, Events::preUpdate, ]; } public function preUpdate(LifecycleEventArgs $event) { $entity = $event->getObject(); if (!$entity instanceof User && !$entity instanceof Avatar) { $date = new DateTimeImmutable(); $entity->setUpdatedAt($date); } } public function prePersist(LifecycleEventArgs $event) { $entity = $event->getObject(); // if($entity instanceof Avatar){ // return; // } $date = new DateTimeImmutable(); if ($entity instanceof Attendance || $entity instanceof FileCategory ) { return; } if (!$entity instanceof FileUpload ) { $entity->setCreatedAt($date); } if($entity instanceof Contact){ return; } if (!$entity instanceof User) { $entity->setUpdatedAt($date); } else { $plainPwd = $entity->getPassword(); $hashedPwd = $this->passwordHasher->hashPassword( $entity, $plainPwd ); $entity->setPassword($hashedPwd) ; } } }
Merci beaucoup de votre aide
Partager