Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. public function actionMyControllerAction()
  2. {
  3. $this->requirePostRequest();
  4.  
  5. // Build a model of the data you are submitting
  6. $model = new MyModel();
  7. $model->someOptionalAttribute = Craft::$app->getRequest()->getBodyParam('someOptionalAttribute');
  8.  
  9. // The `getRequiredBodyParam` method can help validate required fields
  10. $model->someRequiredAttribute = Craft::$app->getRequest()->getRequiredBodyParam('someRequiredAttribute');
  11.  
  12. // After you prepare the model, hand things off to a service
  13. // to validate and/or save things to the database
  14. // The "saveThisModel" method can run any additional
  15. // validation you need to run, add errors to the model,
  16. // and return `false` if validation fails
  17. if (!Plugin::getInstance()->myService->saveThisModel($model)) {
  18.  
  19. Craft::$app->getSession()->setError(Craft::t('my-plugin', 'Unable to save item.'));
  20.  
  21. // This is where you name the thing you are returning to your template with errors.
  22. // In this example, the 'myModel' variable would be available to your submitted template
  23. Craft::$app->getUrlManager()->setRouteParams([
  24. 'myModel' => $model
  25. ]);
  26.  
  27. return null;
  28. }
  29.  
  30. Craft::$app->getSession()->setNotice(Craft::t('my-plugin', 'Item saved.'));
  31.  
  32. // Redirects to wherever the submitted 'redirect' input points to
  33. return $this->redirectToPostedUrl();
  34. }
  35.  
  36. {{ dump(myModel.getErrors()) }}
  37.  
  38. {{ dump(myModel.getError('someOptionalAttribute')) }}
  39.  
  40. {{ forms.textField({
  41. label: "Title"|t('app'),
  42. siteId: category.siteId,
  43. id: 'title',
  44. name: 'title',
  45. value: category.title,
  46. errors: category.getErrors('title'),
  47. required: true,
  48. maxlength: 255
  49. }) }}
  50.  
  51. if (!Craft::$app->getElements()->saveElement($category)) {
  52.  
  53. // ...
  54.  
  55. Craft::$app->getSession()->setError(Craft::t('app', 'Couldn’t save category.'));
  56.  
  57. // Send the category back to the template
  58. Craft::$app->getUrlManager()->setRouteParams([
  59. 'category' => $category
  60. ]);
  61.  
  62. return null;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement