Search code examples
formscakephpcakephp-3.0modeless

Is there a way to call modeless form in pages using cakephp3


as what I read online it will only be available for like this http://localhost/xxxxx/contact then the form will display

but I want it to display in many pages like contact us, or about us page

when i call this pages I want the form appear in the content?

Template

index.ctp

<?= $this->Form->create($contact); ?>
<?= $this->Form->input('name'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('body'); ?>
<?= $this->Form->button('Submit'); ?>
<?= $this->Form->end(); ?>

ContactController.php

<?php
// In a controller
namespace App\Controller;

use App\Controller\AppController;
use App\Form\ContactForm;

class ContactController extends AppController
{
public function index()
{
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$this->Flash->success('Your message has been sent; we\'ll get back to you soon!');
$this->request->data['name'] = null;
$this->request->data['email'] = null;
$this->request->data['body'] = null;
} else {
$this->Flash->error('There was a problem submitting your form.');
}
}
$this->set('contact', $contact);
}
}

?>

ContactForm.php

<?php
namespace App\Form;

use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
use Cake\Mailer\Email;

class ContactForm extends Form
{

protected function _buildSchema(Schema $schema)
{
return $schema->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('body', ['type' => 'text']);
}

protected function _buildValidator(Validator $validator)
{
return $validator->add('name', 'length', [
'rule' => ['minLength', 10],
'message' => 'Please enter your name'
])->add('email', 'format', [
'rule' => 'email',
'message' => 'Please enter a valid email address',
])->add('body', 'length', [
'rule' => ['minLength', 25],
'message' => 'Please enter your message text',
]);
}

protected function _execute(array $data)
{
// Send an email.
    return true;
}
}

Solution

  • You can fixed it by moving the contact template form into the element so that it will be available in any pages.

    inside element in the contact folder, form below must be present

    <legend><?= __('Our Form') ?></legend>
        <fieldset>
            <?php
            echo $this->Form->input('name');
            echo $this->Form->input('email');
            echo $this->Form->input('body');
            ?>
        </fieldset>
        <?= $this->Form->button(__('Submit')) ?>
        <?= $this->Form->end(); ?>
    

    then in your pages

    you can just call

    <?php 
       echo $this->element('contact/index');
     ?> 
    

    assuming you created index.ctp inside contact folder in element

    Hope it solved your problem.