[ 'class' => AccessControl::class, 'rules' => [ [ 'allow' => true, 'roles' => ['@'], 'matchCallback' => function ($rule, $action) { return $this->getUserModule() ->getAuthorizationChecker() ->isGrantedAsProducer($this->getUserCurrent()); } ] ], ], ]; } public function actionIndex() { return $this->render('index', [ 'dataProvider' => $this->getAccessoryModule()->getRepository() ->queryAccessories()->getDataProvider(20), ]); } public function actionCreate() { $accessoryModule = $this->getAccessoryModule(); $accessoryModel = $accessoryModule->getBuilder()->instanciateAccessory($this->getProducerCurrent()); if ($accessoryModel->load(\Yii::$app->request->post()) && $accessoryModel->validate()) { $accessory = $accessoryModule->getManager()->createAccessory( $this->getProducerCurrent(), $accessoryModel->getName(), $accessoryModel->getQuantity() ); $this->afterSave($accessory, $accessoryModel->getSelectedProductsIds()); $this->setFlash('success', "Accessoire ajouté"); return $this->redirectAfterSave('accessory', $accessory->getId()); } return $this->render('create', [ 'accessory' => $this->initFormModel($accessoryModel), 'productsArray' => $this->findProducts() ]); } /** * @throws NotFoundHttpException */ public function actionUpdate(int $id) { $accessory = $this->findAccessory($id); if ($accessory->load(\Yii::$app->request->post()) && $accessory->validate() && $accessory->save()) { $this->afterSave($accessory, $accessory->getSelectedProductsIds()); return $this->redirectAfterSave('accessory', $accessory->getId()); } return $this->render('update', [ 'accessory' => $this->initFormModel($accessory), 'productsArray' => $this->findProducts() ]); } /** * @throws \Throwable * @throws StaleObjectException * @throws NotFoundHttpException */ public function actionDelete(int $id): Response { $accessory = $this->findAccessory($id); if($accessory->delete()) { $this->setFlash('success', "Accessoire supprimé"); } return $this->redirect('index'); } public function afterSave(Accessory $accessory, $selectedProductsIdsArray): void { if(!is_array($selectedProductsIdsArray)) { $selectedProductsIdsArray = []; } $this->getAccessoryModule()->getManager()->manageProducts($accessory, $selectedProductsIdsArray); } public function findProducts(): array { return $this->getProductModule()->getRepository()->findProducts(true); } /** * @throws NotFoundHttpException */ protected function findAccessory($id): Accessory { if (($accessory = $this->getAccessoryModule()->getRepository()->findOneAccessoryById($id)) !== null) { return $accessory; } else { throw new NotFoundHttpException("L'accessoire n'a pas été trouvé."); } } public function initFormModel(Accessory $accessoryModel) { $this->getAccessoryModule()->getBuilder()->initSelectedProductsIds($accessoryModel); return $accessoryModel; } }