I get the contents of my form to write to the database. My code is as follows:
View (index.ctp):
<div class="modal fade" id="test_modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Create Customer</h1>
</div>
<div class="modal-body">
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('type');
echo $this->Form->input('name');
echo $this->Form->input('company');
echo $this->Form->input('phone');
echo $this->Form->input('mobile');
echo $this->Form->input('email');
echo $this->Form->input('vatNumber');
echo $this->Form->input('mainAddressLine1');
echo $this->Form->input('mainAddressLine2');
echo $this->Form->input('mainAddressTown');
echo $this->Form->input('mainAddressCounty');
echo $this->Form->input('mainAddressPostCode');
echo $this->Form->input('mainAddressCountry');
echo $this->Form->input('notes', array('rows' => '5'));
echo $this->Form->end('Save Customer');
?>
</div>
</div>
Controller (ContactController.php)
class ContactsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->set('contacts', $this->Contact->find('all'));
}
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid contact'));
}
$contact = $this->Contact->findById($id);
if (!$contact) {
throw new NotFoundException(__('Invalid contact'));
}
$this->set('contact', $contact);
}
public function add() {
if ($this->request->is('post')) {
$this->Contact->create();
if ($this->Contact->save($this->request->data)) {
$this->Session->setFlash('Your contact has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your contact.');
}
}
}
}
Model (Contact.php)
class Contact extends AppModel {
}
Any help appreciated.
Regards,
Stephen
If your view file is index.ctp, that means that by default the logic thta is handled for it is in the index() method of your Controller. That method only sets a variable. I'm assuming you're mixing up the view/action. Try adding your form in the add.ctp view instead and call the contacts/add URI.
Alternatively you can override the view to be rendered by adding a $this->render call to your add() method:
public function add() {
$this->autoRender = false;
// Rest of your logic
$this->render('index');
}
That way the contacts/add URI will serve the index.ctp view instead of add.ctp.
Related
I started using cakePHP 4 a while ago and my website is quite done. But i have some trouble creating a contact Form. I did as instructed on the cookbook > Modelless Forms, Validation and Forms but i do not get it right (for me the cookbook is really hard to understand sometimes).
When i press my button to send the form, the same page appears with filled fields but no validation or error messages are shown. I am sure i forgot something to send these information from the controller and something to get these data from the controller but ... i cant find what exactly i need. Also i do not exactly understand what i have to fill in the ContactController "$this->request->is('get')"i hope someone of you can help me out of there. Maybe i just have a big board in front of my head...
here is my code (the templatecode is just a excerpt)
src/Controller/ContactController.php
<?php
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->getData())) {
$this->Flash->success('We will get back to you soon.');
} else {
$this->Flash->error('There was a problem submitting your form.');
$contact->setErrors(['name' => ['_required' => 'at least 5 signs'],['email' => ['_required' => 'Your email is required']]);
}
}
if ($this->request->is('get')) {
$contact->setData([
'name' => 'John Doe',
'email' => 'john.doe#example.com'
]);
}
$this->set('contact', $contact);
}
}
src/Form/ContactForm.php
<?php
/* https://book.cakephp.org/4/en/core-libraries/form.html */
namespace App\Form;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
class ContactForm extends Form
{
protected function _buildSchema(Schema $schema): Schema
{
return $schema->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('subject', ['type' => 'string'])
->addField('message', ['type' => 'text']);
}
public function validationDefault(Validator $validator): Validator
{
$validator->minLength('name', 5)
->email('email')
->notEmptyString('subject', 'Please fill this field')
->notEmptyString('text', 'Please fill this field')
return $validator;
}
protected function _execute(array $data): bool
{
print_r('TESTING OK');
return true;
}
public function setErrors($errors)
{
$this->_errors = $errors;
}
}
templates/Pages/contact.php (used with ready HTML Templates for the style)
...
<?php echo $this->Form->create($contact); ?>
<div class="row gtr-50 gtr-uniform">
<div class="col-6 col-12-mobilep">
<?php echo $this->Form->control('name',['label' => false,'placeholder'=>$translation['Name'],'templates' => ['inputContainer' => '{{content}}']]);?>
</div>
<div class="col-6 col-12-mobilep">
<?php echo $this->Form->control('email',['label' => false,'placeholder'=>$translation['Email'],'templates' => ['inputContainer' => '{{content}}']]);?>
</div>
<div class="col-12">
<?php echo $this->Form->control('subject',['label' => false,'placeholder'=>$translation['Betreff'],'templates' => ['inputContainer' => '{{content}}']]);?>
</div>
<div class="col-12">
<?php echo $this->Form->textarea('message',['label' => false,'placeholder'=>$translation['Bitte gebe deine Nachricht ein'],'rows'=>'6']); ?>
</div>
<div class="col-12">
<ul class="actions special">
<li><?php echo $this->Form->submit($translation['Nachricht senden']); ?></li>
</ul>
</div>
</div>
<?php echo $this->Form->end(); ?>
...
Thanks a lot
I have a this
**Fatal_Error:
Error: Unsupported operand types
File: C:\wamp\www\newsletter\lib\Cake\View\Helper\FlashHelper.php
Line: 90**
every time I clicked the submit button. here's my code..
**AddsController.php //Controller**
<?php
class AddsController extends AppController {
public $helpers = array('Html','Form','Session');
public $components=array('Session');
public function index() {
if($this->request->is('post'))
{
$this->Add->create();
$this->Add->save($this->request->data);
$this->Session->setFlash('Success');
return $this->redirect(array('action'=>'index'));
}
}
}
?>
**Add.php //Model/**
<?php
App::uses('AppModel' , 'Model');
class Add extends AppModel
{
public $name = "Add";
public $useTable = 'request';
public $primaryket = 'id';
public $useDbConfig = 'default';
}
?>
**index.ctp //View/Adds/index.ctp**
<?php
echo $this->Form->create('add');
echo $this->Form->input('email');
echo $this->Form->submit('submit');
echo $this->Form->end();
?>
dbname: exercise; table: request;
goal: all inputted data must be in the db.
Thank you in advance!
Use FlashHelper to set yor flash messages, not Session->flash
https://book.cakephp.org/2.0/en/core-libraries/helpers/flash.html
// In your Controller
public $helpers = array('Html','Form','Session','Flash');
$this->Flash->set('The user has been saved.', array(
'element' => 'success'
));
My problem is that i dont know save() function of cakephp insert null values in posts table !
When I try to add a post: http://i.stack.imgur.com/fhRVn.png
After redirecting the inserted data is null: http://i.stack.imgur.com/YstBb.png
My PostsController.php is:
App::uses('AppController', 'Controller');
class PostsController extends AppController{
public $components = array('Session');
public $helpers = array('Html', 'Form');
public function index() {
$this -> set('posts', $this->Post->find('all'));
}
public function view($id = null){
if(!$id){
throw new NotFoundException(_('il faut choisir un post'));
}
$post=$this->Post->findById($id);
if(!$post){
throw new NotFoundException(_('invalide Post !'));
}
$this->set('post',$post);
} // fin de "view"
public function add(){
if($this->request->is('post'))
{
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
//debug($this->Post->validate);
}//fin d'ajout
} // fin de "appcontroller"
My Post.php model file is:
class Post extends appModel {
//public $name='Post';
public $validate = array(
'title' => array('rule' => 'notEmpty'),
'body' => array('rule' => 'notEmpty')
);
}
My view form post is:
echo $this->Form->create('post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');
in your view maybe your problem that you Model is Post not post
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');
I don't see anything wrong with my code. But it does not save data:
<?php
class ProductsController extends AppController{
var $name = 'Products';
//var $helpers = array('Form');
//var $scaffold;
function index(){
$this->Product->recursive = 1;
$products = $this->Product->find('all');
$this->set('products',$products);
//pr($products);
}
function add(){
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
if(!empty($this->data)){
if($this->Product->save($this->data)){
$this->Session->setFlash('Saved');
}
}
}
}
?>
it flashes "Saved" but nothing is being inserted in my table. What could possibly be wrong when it should be functioning properly. :(
Below is my add.ctp model:
<h2>ADD</h2>
<?php echo $this->Form->create('Product',array('action'=>'add')); ?>
<?php
echo $form->input('ProductName');
echo $form->input('categories');
echo $form->end('DONE');
?>
You have to use the create() method before to save
function add(){
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
if(!empty($this->data)){
$this->Product->create();
if($this->Product->save($this->data)){
$this->Session->setFlash('Saved');
}
}
}
i use this controller to login and logout users, and i want to display welcome message and the login username with logout link the problem is when i try to login this message apear to me
Notice (8): Undefined variable: results [APP\views\users\login.ctp, line 4]
users_controller.php
<?php
# /controllers/users_controller.php
# please note that not all code is shown...
uses('sanitize');
class UsersController extends AppController {
var $name = 'Users';
// Include the Email Component so we can send some out :)
var $components = array('Email','Auth','Recaptcha');
var $helpers = array('Recaptcha');
// Allow users to access the following action when not logged in
function beforeFilter () {
$this->Auth->allow('register','activate','logout','login');
$this->Auth->autoRedirect = false;
}
function login() {
// Check for incoming login request.
if ($this->data) {
// Use the AuthComponent's login action
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
// Check to see if the User's account isn't active
if ($results['User']['active'] == 0) {
// Uh Oh!
$this->Session->setFlash('Your account has not been activated yet!');
$this->Auth->logout();
$this->data['User']['password'] = null;
//if not active user
}else {
$this->set('users', $results);
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
users/login.ctp
<?php if ($this->Session->read('Auth.User')):?>
<?php
echo "Welcome".'<br />' ;
echo $results;
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User');?>
<fieldset>
<legend><?php echo ('Please enter your username and password'); ?></legend>
<?php
echo $form->input('username');
echo $form->input('password');
?>
</fieldset>
<?php echo $form->end(('Login'));?>
</div>
<?php endif; ?>
You have to pass the data from your controller to the view by using the set method: $this->set('results', $results);. See also http://book.cakephp.org/view/977/Controller-Methods#Interacting-with-Views-978
AppController.php
function beforeFilter(){
$this->set('username', $this->_usersUsername());
}
function _usersUsername(){
$users_username = NULL;
if($this->Auth->user()){
$users_username = $this->Auth->user('username');
}
return $users_username;
}
view.ctp
<?php if(isset($username)) :?>
hello <?php echo $username; ?>! Welcome back.
<?php endif; ?>