{"id":3902,"date":"2021-01-25T04:14:26","date_gmt":"2021-01-25T04:14:26","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=3902"},"modified":"2021-01-25T05:46:53","modified_gmt":"2021-01-25T05:46:53","slug":"model-less-forms-in-cakephp","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/","title":{"rendered":"Model-less Forms in CakePHP"},"content":{"rendered":"<p>The class used is Cake\\Form\\Form.<\/p>\n<p>Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times when you\u2019ll need to validate user input and then perform an action if the data is valid.<\/p>\n<p>Let&#8217;s discuss it with the Contact Form example. <\/p>\n<h2>Creating the Form<\/h2>\n<p>Generally, when using the Form class you\u2019ll want to use a subclass to define your form. This makes testing easier and lets you re-use your form. Forms are put into src\/Form and usually have Formed as a class suffix. For example, a simple contact form would look like this:<br \/>\n<code><em>\/\/ in src\/Form\/ContactForm.php<\/em><br \/>\nnamespace App\\Form;<br \/>\nuse Cake\\Form\\Form;<br \/>\nuse Cake\\Form\\Schema;<br \/>\nuse Cake\\Validation\\Validator;<br \/>\nclass ContactForm extends Form<br \/>\n{<br \/>\n    protected function _buildSchema(Schema $schema)<br \/>\n    {<br \/>\n        return $schema->addField('name', 'string')<br \/>\n            ->addField('email', ['type' => 'string'])<br \/>\n            ->addField('body', ['type' => 'text']);<br \/>\n    }<br \/>\n    protected function validationDefault(Validator $validator)<br \/>\n    {<br \/>\n        $validator->add('name', 'length', [<br \/>\n                'rule' => ['minLength', 10],<br \/>\n                'message' => 'A name is required'<br \/>\n            ])->add('email', 'format', [<br \/>\n                'rule' => 'email',<br \/>\n                'message' => 'A valid email address is required',<br \/>\n            ]);<\/p>\n<p>        return $validator;<br \/>\n    }<\/p>\n<p>    protected function _execute(array $data)<br \/>\n    {<br \/>\n        \/\/ Send an email.<br \/>\n        return true;<br \/>\n    }<br \/>\n}<\/code><\/p>\n<p>In the above example, we see the 3 methods that form provides:<\/p>\n<p><strong>_buildSchema<\/strong> &#8211; is used to define the schema data that is used by FormHelper to create an HTML form. You can define field type, length, and precision.<br \/>\n<strong>validationDefault<\/strong> &#8211; Gets a Cake\\Validation\\Validator instance that you can attach validators to.<br \/>\n<strong>_execute<\/strong> &#8211;  lets you define the behavior you want to happen when execute() is called and the data is valid.<\/p>\n<h3>Processing Request Data<\/h3>\n<p>Once you\u2019ve defined your form, you can use it in your controller to process and validate request data:<br \/>\n<code>\/\/ In a controller<br \/>\nnamespace App\\Controller;<br \/>\nuse App\\Controller\\AppController;<br \/>\nuse App\\Form\\ContactForm;<br \/>\nclass ContactController extends AppController<br \/>\n{<br \/>\n    public function index()<br \/>\n    {<br \/>\n        $contact = new ContactForm();<br \/>\n        if ($this->request->is('post')) {<br \/>\n            if ($contact->execute($this->request->getData())) {<br \/>\n                $this->Flash->success('We will get back to you soon.');<br \/>\n            } else {<br \/>\n                $this->Flash->error('There was a problem submitting your form.');<br \/>\n            }<br \/>\n        }<br \/>\n        $this->set('contact', $contact);<br \/>\n    }<br \/>\n}<\/code><\/p>\n<p>In the above example, we use the execute() method to run our form\u2019s _execute() method only when the data is valid, and set flash messages accordingly. We could have also used the validate() method to only validate the request data:<\/p>\n<p><code><em>$isValid = $form->validate($this->request->getData());<\/em><\/code><\/p>\n<h3>Setting Form Values<\/h3>\n<p>You can set default values for modeless forms using the setData() method. <a href=\"https:\/\/studysection.com\/blog\/how-to-access-html-elements-values-in-js-code-for-lightning-web-component-lwc\/\">Values<\/a> set with this method will overwrite existing data in the form object:<br \/>\n<code>\/\/ In a controller<br \/>\nnamespace App\\Controller;<br \/>\nuse App\\Controller\\AppController;<br \/>\nuse App\\Form\\ContactForm;<br \/>\nclass ContactController extends AppController<br \/>\n{<br \/>\n    public function index()<br \/>\n    {<br \/>\n        $contact = new ContactForm();<br \/>\n        if ($this->request->is('post')) {<br \/>\n            if ($contact->execute($this->request->getData())) {<br \/>\n                $this->Flash->success('We will get back to you soon.');<br \/>\n            } else {<br \/>\n                $this->Flash->error('There was a problem submitting your form.');<br \/>\n            }<br \/>\n        }<br \/>\n        if ($this->request->is('get')) {<br \/>\n            $contact->setData([<br \/>\n                'name' => 'John Doe',<br \/>\n                'email' => 'john.doe@example.com'<br \/>\n            ]);<br \/>\n        }<br \/>\n        $this->set('contact', $contact);<br \/>\n    }<br \/>\n}<\/code><\/p>\n<p>Values should only be defined if the request method is GET, otherwise, you will overwrite your previous POST Data which might have validation errors that need corrections.<\/p>\n<p><strong>Getting the Form Errors<\/strong><br \/>\n<code><em>$errors = $form->getErrors();<\/em><\/code><\/p>\n<h3>Invalidating individual Form Fields from Controller<\/h3>\n<p>It is possible to invalidate individual fields from the controller without the use of the Validator class. The most common use case for this is when the validation is done on a remote server. In such a case, you must manually invalidate the fields accordingly to the feedback from the remote server:<br \/>\n<code>\/\/ in src\/Form\/ContactForm.php<br \/>\npublic function setErrors($errors)<br \/>\n{<br \/>\n    $this->_errors = $errors;<br \/>\n}<\/code><br \/>\nAccording to how the validator class would have returned the errors, $errors must be in this format:<br \/>\n<code>[\"fieldName\" => [\"validatorName\" => \"The error message to display\"]]<\/code><\/p>\n<p>Now you will be able to invalidate form fields by setting the fieldName, then set the error messages:<br \/>\n<code>\/\/ In a controller<br \/>\n$contact = new ContactForm();<br \/>\n$contact->setErrors([\"email\" => [\"_required\" => \"Your email is required\"]]);<\/code><\/p>\n<p>Proceed to Create HTML with FormHelper to see the results.<br \/>\nOnce you\u2019ve created a Form class, you\u2019ll likely want to create an HTML form for it. FormHelper understands Form objects just like ORM entities:<\/p>\n<p><code>echo $this->Form->create($contact);<br \/>\necho $this->Form->control('name');<br \/>\necho $this->Form->control('email');<br \/>\necho $this->Form->control('body');<br \/>\necho $this->Form->button('Submit');<br \/>\necho $this->Form->end();<\/code><\/p>\n<p><small><em>If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level <a href=\"https:\/\/www.studysection.com\/cakephp-3.x-foundation\">PHP Certification Exams<\/a> are offered by StudySection along with other programming certification exams. <\/em><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The class used is Cake\\Form\\Form. Most of the time you will have forms backed by ORM entities and ORM tables<\/p>\n","protected":false},"author":1,"featured_media":3903,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[591,620],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>StudySection Blog - Model-less Forms in CakePHP<\/title>\n<meta name=\"description\" content=\"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"StudySection Blog - Model-less Forms in CakePHP\" \/>\n<meta property=\"og:description\" content=\"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2021-01-25T04:14:26+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-01-25T05:46:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/01\/cakephp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"300\" \/>\n\t<meta property=\"og:image:height\" content=\"200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Model-less Forms in CakePHP\",\"datePublished\":\"2021-01-25T04:14:26+00:00\",\"dateModified\":\"2021-01-25T05:46:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\"},\"wordCount\":485,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"keywords\":[\"Cakephp\",\"Model-less\"],\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\",\"url\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\",\"name\":\"StudySection Blog - Model-less Forms in CakePHP\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2021-01-25T04:14:26+00:00\",\"dateModified\":\"2021-01-25T05:46:53+00:00\",\"description\":\"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Model-less Forms in CakePHP\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"StudySection Blog - Model-less Forms in CakePHP","description":"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/","og_locale":"en_US","og_type":"article","og_title":"StudySection Blog - Model-less Forms in CakePHP","og_description":"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.","og_url":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2021-01-25T04:14:26+00:00","article_modified_time":"2021-01-25T05:46:53+00:00","og_image":[{"width":300,"height":200,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/01\/cakephp.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Model-less Forms in CakePHP","datePublished":"2021-01-25T04:14:26+00:00","dateModified":"2021-01-25T05:46:53+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/"},"wordCount":485,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"keywords":["Cakephp","Model-less"],"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/","url":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/","name":"StudySection Blog - Model-less Forms in CakePHP","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2021-01-25T04:14:26+00:00","dateModified":"2021-01-25T05:46:53+00:00","description":"Most of the time you will have forms backed by ORM entities and ORM tables or other persistent stores, but there are times need to validate.","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/model-less-forms-in-cakephp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Model-less Forms in CakePHP"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":175,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3902"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=3902"}],"version-history":[{"count":5,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3902\/revisions"}],"predecessor-version":[{"id":3908,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/3902\/revisions\/3908"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/3903"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=3902"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=3902"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=3902"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}