|
3 | 3 | namespace AppBundle\Controller; |
4 | 4 |
|
5 | 5 | use AppBundle\Entity\Widget; |
| 6 | +use AppBundle\Form\Type\WidgetType; |
6 | 7 | use AppBundle\Repository\WidgetRepository; |
7 | 8 | use FOS\RestBundle\View\View; |
8 | 9 | use FOS\RestBundle\Controller\Annotations; |
@@ -68,4 +69,77 @@ public function cgetAction( |
68 | 69 | { |
69 | 70 | return $widgetRepository->findAll(); |
70 | 71 | } |
| 72 | + |
| 73 | + |
| 74 | + /** |
| 75 | + * Create new Widget from the submitted data |
| 76 | + * |
| 77 | + * @Annotations\Post(path="/widget") |
| 78 | + */ |
| 79 | + public function postAction(Request $request) |
| 80 | + { |
| 81 | + // creates a Widget with the `createdAt` property already set |
| 82 | + $widget = $this->get('crv.factory.widget')->create(); |
| 83 | + |
| 84 | + $form = $this->createForm(WidgetType::class, $widget, [ |
| 85 | + 'csrf_protection' => false, |
| 86 | + ]); |
| 87 | + |
| 88 | + $form->submit($request->request->all(), false); |
| 89 | + |
| 90 | + if (!$form->isValid()) { |
| 91 | + return $form; |
| 92 | + } |
| 93 | + |
| 94 | + $widget = $form->getData(); |
| 95 | + |
| 96 | + $em = $this->getDoctrine()->getManager(); |
| 97 | + $em->persist($widget); |
| 98 | + $em->flush(); |
| 99 | + |
| 100 | + $routeOptions = [ |
| 101 | + 'id' => $widget->getId(), |
| 102 | + '_format' => $request->get('_format'), |
| 103 | + ]; |
| 104 | + |
| 105 | + return $this->routeRedirectView('get_widget', $routeOptions, Response::HTTP_CREATED); |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Update existing Widget from the submitted data |
| 110 | + * |
| 111 | + * @Annotations\Put(path="/widget/{id}") |
| 112 | + */ |
| 113 | + public function putAction(Request $request, int $id) |
| 114 | + { |
| 115 | + // getRepo() being a private method to return |
| 116 | + // whatever repo we have configured |
| 117 | + $widget = $this->getRepo()->find($id); |
| 118 | + |
| 119 | + $form = $this->createForm(WidgetType::class, $widget, [ |
| 120 | + 'csrf_protection' => false, |
| 121 | + ]); |
| 122 | + |
| 123 | + $form->submit($request->request->all(), false); |
| 124 | + |
| 125 | + if (!$form->isValid()) { |
| 126 | + return $form; |
| 127 | + } |
| 128 | + |
| 129 | + $widget = $form->getData(); |
| 130 | + |
| 131 | + // a manual process |
| 132 | + $widget->setUpdatedAt(); |
| 133 | + |
| 134 | + $em = $this->getDoctrine()->getManager(); |
| 135 | + $em->flush(); |
| 136 | + |
| 137 | + $routeOptions = [ |
| 138 | + 'id' => $widget->getId(), |
| 139 | + '_format' => $request->get('_format'), |
| 140 | + ]; |
| 141 | + |
| 142 | + return $this->routeRedirectView('get_widget', $routeOptions, Response::HTTP_NO_CONTENT); |
| 143 | + } |
| 144 | + |
71 | 145 | } |
0 commit comments