I explain the problem, the user fills out the form and if he presses f5 or refreshes the page, the data he has just entered is re-inserted exactly the same, one of the options would be to validate that the id is not repeated, but in this case it is not valid since it is an autoincrement.
View
<div class="col-md-6">
<?php
echo $this->Form->create('Need', array('class' => '', 'id' => 'msform'));
?>
<label class="lang" key="h1NeedForm">Aprovechemos el tiempo y comencemos</label>
<?php
echo $this->Form->input('client', array('label' => array('text' => "¿Para que marca vamos a trabahar?",
'key' => 'lblClient', 'class' => 'lang'), 'placeholder' => 'Dinos el nombre de tu empresa',
'class' => 'validador txtClient lang', 'key' => 'txtClient'));
echo $this->Form->input('need', array('label' => array('text' => "Escríbenos acerca de tu necesidad",
'key' => 'lblNeed', 'class' => 'lang'), 'placeholder' => 'Agradecemos nos detalles muy bien la necesidad, '
. 'es nuestro punto de partida para generar ideas quer fortalezcan la estrategia para resolverla.',
'rows' => '4', 'class' => 'validador txtNeed lang', 'key' => 'txtNeed', 'style' => 'resize: none;'));
echo $this->Form->input('objective', array('label' => array('text' => "¿Cuál es el objetivo?",
'key' => 'lblObjective', 'class' => 'lang'), 'placeholder' => 'Que se quiere alcanzar con la'
. 'solución de la necesidad, ¿Adquirir usuario? ¿Mejorar ventas? ¿Posicionar la marca? ... entre otros.'
. ' Agradecemos nos detalles muy bien el objetivo.', 'rows' => '4',
'class' => 'validador txtObjective lang', 'key' => 'txtObjective', 'style' => 'resize: none;'));
?>
<?php
$options = array(
'class' => 'lang',
'label' => 'Enviar y continuar',
'key' => 'btnFormNeed'
);
echo $this->Form->end($options);
?>
</div>
Controller
public function home() {
if ($this->request->is('post'))
{
if(!empty($this->request->data))
{
$this->Flash->error(__("Emty"));
$this->loadModel('Need');
$this->Need->create();
if ($this->Need->save($this->request->data)) {
$this->Need->save(array(
'date' => date("Y/m/d")
));
//$this->request->data = array(); este código me lo sugirieron pero no hacia absolutamente nada
return false;
}
}
else{
$this->Flash->error(__("No empty"));
}
}
else {
$this->Flash->error(__("Sino post"));
}
}
Previously I had this code in the controller inside the home function and it always entered through the post
//return false;
//
/*unset($post);
if($this->request->is('redirect')){
$this->Flash->error(__("redirect"));
return false;
}
else if($this->request->is('get')){
$this->Flash->error(__("get"));
return false;
}
else if($this->request->is('post')){
$this->Flash->error(__("post")); //siempre entraba p
return false;
}*/
//
Full ModelNeed.php
App::uses('AppModel', 'Model');
class Need extends AppModel {
public $validate = array(
'client' => array(
'rule' => 'notBlank'
),
'date' => array(
'rule' => 'notBlank'
),
'id' => array(
'rule' => 'notBlank'
),
'need' => array(
'rule' => 'notBlank'
),
'objective' => array(
'rule' => 'notBlank'
),
'process' => array(
'rule' => 'notBlank'
)
);
}
routes.php
Router::connect('/Practica', array('controller' => 'pages', 'action' => 'home', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';
I'm going to share the routes, the controller function, the model, the form, and an image of the repeated data in the database.
I was researching on the internet and I saw that the same thing happened in Laravel, that the form was forwarded, but for cake I did not find a solution but I know there must be one, I am working on version 2.x but next week I will migrate my data to the 3.x
Thanks for all the help given.
PS: I have attached all the controller and the deafult, although I don't think they will interfere, I am going to paste them in case they serve to answer my problem.
pagecontroller.php
<?php
/**
* Static content controller.
*
* This file will render views from views/pages/
*
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @package app.Controller
* @since CakePHP(tm) v 0.2.9
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AppController', 'Controller');
/**
* Static content controller
*
* Override this controller by placing a copy in controllers directory of an application
*
* @package app.Controller
* @link https://book.cakephp.org/2.0/en/controllers/pages-controller.html
*/
class PagesController extends AppController {
/**
* This controller does not use a model
*
* @var array
*/
public $helpers = array('Html', 'Form', 'Flash', 'Js' => array('Jquery'));
public $components = array('Flash', 'RequestHandler');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function prueba(){
return "hola";
}
public function home() {
//return false;
//
/*unset($post);
if($this->request->is('redirect')){
$this->Flash->error(__("redirect"));
return false;
}
else if($this->request->is('get')){
$this->Flash->error(__("get"));
return false;
}
else if($this->request->is('post')){
$this->Flash->error(__("post"));
return false;
}*/
//
//return false;
if ($this->request->is('post'))
{
if(!empty($this->request->data))
{
$this->Flash->error(__("Emty"));
$this->loadModel('Need');
$this->Need->create();
if ($this->Need->save($this->request->data)) {
$this->Need->save(array(
'date' => date("Y/m/d")
));
return false;
}
}
else{
$this->Flash->error(__("No empty"));
}
}
else {
$this->Flash->error(__("Sino post"));
}
}
public function fullClient() {
if ($this->request->is('post')) {
// $information = $this->data['Cliente']['informacio'];
$client = $this->data['Client']['cliente'];
$user = $this->data['Client']['usuario'];
$password = $this->data['Client']['clave'];
$password = password_hash($password, PASSWORD_DEFAULT);
//$posicion_coincidencia = strrpos($cadena_de_texto, $cadena_buscada, -20);
// $this->Flash->error(__($hola));
$this->loadModel('Client');
$consult = $this->Client->find('count', array(
'fields' => array('usuario'),
'conditions' => array('usuario LIKE ' => $user)));
// $aaa= $aaa['Client'];
if ($consult == 0) {
$this->Client->create();
if ($this->Client->save($this->request->data)) {
$this->Client->save(array(
'rol' => 'Cliente',
'clave' => $password
));
$consult = $this->Client->find('all', array(
'fields' => array('usuario'),
'conditions' => array('usuario LIKE ' => $user)));
$id_client = $consult[0];
$this->loadModel('Need');
$data = array(
array('procesos_id' => 11112,
'clientes_id' => $id_client['Client']['usuario'],
'fecha' => date("Y/m/d")),
);
$this->Need->saveMany($data);
$this->Need->save();
//$this->loadModel('Need');
// $this->Need->create();
// $this->Need->save($data);
$this->Flash->error(__('Your informatio was save'));
return $this->request->data;
}
$this->Flash->error(__('Your informatio wasn`t save'));
} else {
$this->Flash->success(__("El nombre de usuario que elgiste ya existe"));
}
}
}
public $uses = array();
/**
* Displays a view
*
* @return CakeResponse|null
* @throws ForbiddenException When a directory traversal attempt.
* @throws NotFoundException When the view file could not be found
* or MissingViewException in debug mode.
*/
public function display() {
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
if (in_array('..', $path, true) || in_array('.', $path, true)) {
throw new ForbiddenException();
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
try {
$this->render(implode('/', $path));
} catch (MissingViewException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
}
Default.ctp
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
$cakeDescription = __d('cake_dev', 'Seadog Creative Labs');
$cakeVersion = __d('cake_dev', 'CakePHP %s', Configure::version());
?>
<!DOCTYPE html>
<!--<html oncontextmenu="return false"> -->
<html>
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo $cakeDescription ?>:
<?php echo $this->fetch('title'); ?>
</title>
<?php
echo $this->Html->meta('icon', '/favicon.ico', ['type' => 'image/ico']);
echo $this->Html->meta(['name' => 'robots', 'content' => 'noindex']);
echo $this->Html->meta(['name' => 'googlebot', 'content' => 'noindex']);
echo $this->Html->meta(['http-equiv' => 'Pragma', 'content' => 'no-cache']);
echo $this->Html->css('navigatePage');
echo $this->Html->css('myStyle');
echo $this->Html->css('bootstrap.min'); //problema
echo $this->Html->css('bootstrap-datepicker3'); //problema
// echo $this->Html->css('reset.min');
// echo $this->Html->css('bootstrap-formhelpers.min');
echo $this->Html->css('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/css/bootstrap-select.min.css');
echo $this->Html->css('https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css');
// echo $this->Html->css('jquery.timepicker.min');
echo $this->Js->writeBuffer();
echo $this->fetch('css');
echo $this->fetch('script');
?>
</head>
<body>
<div id="container">
<div id="header">
<div class="circle" style="cursor: default;">
<ul class="navbar-right">
<li>
<a class="active linkBrowserHome"><span></span></a>
</li>
<li>
<a class="linkBrowserNeeds"><span></span></a>
</li>
<li>
<a class="linkBrowserStrategies"><span></span></a>
</li>
<li>
<a class="linkBrowserTools"><span></span></a>
</li>
<li>
<a class="linkBrowserExecution"><span></span></a>
</li>
<li>
<a class="linkBrowserResults"><span></span></a>
</li>
</ul>
</div>
<br>
<div class="navbar-header">
<a class="navbar-brand" href="#">
<?php
echo $this->Html->image('cont-.png', array('alt' => '',
"width" => "100", "height" => "25", 'title' => 'h'));
?>
</a>
</div>
<div class="navbar-collapse navbar-ex1-collapse in" style="height: auto;">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle glyphicon glyphicon-list-alt" data-toggle="dropdown">
<b class="caret"></b>
</a>
<ul class="dropdown-menu" style="cursor: pointer;">
<li><a class="linkMenuHome" key="linkHome">Laboratorio estratégico</a></li>
<li><a class="linkMenuNeeds" key="linkNeeds">Descubrir necesidades</a></li>
<li><a class="linkMenuStrategies" key="linkStrategies">Definir estrategias</a></li>
<li><a class="linkMenuTools" key="linkTools">Herramientas</a></li>
<li><a class="linkMenuExecution" key="linkExecution">Ejecución</a></li>
<li><a class="linkMenuResults" key="linkResults">Resultados</a></li>
<li class=""></li>
<li><a class="linkMenuExplore lang" key="linkExplore">Explora resultados</a></li>
<li class=""></li>
<li><a class="linkMenuTeam lang" key="linkTeam">Equipo</a></li>
<li class="divider"></li>
<li><a class="linkMenuContact lang" key="linkContact">Contáctenos</a></li>
</ul>
</li>
</ul>
</div>
<br>
</div>
<div id="content">
<?php
$here = $this->request->here(true);
if (strpos($here, "?") !== false) {
$hola = explode('?', $here);
$hola[1] = str_replace('=', '', $hola[1]);
if (strpos($hola[1], 'publicidad') !== false) {
echo "publicidad";
} else if (strpos($hola[1], 'marca') !== false) {
echo "Marca";
} else if (strpos($hola[1], 'experiencia') !== false) {
echo "Experiencia de usuario";
}
} else {
echo "";
}
?>
<?php echo $this->Flash->render(); ?>
<?php echo $this->fetch('content'); ?>
<select class="selectpicker" data-width="fit">
<option data-content='<span class="flag-icon flag-icon-co" value="es"></span> Español'>Español</option>
<option data-content='<span class="flag-icon flag-icon-us" value="en"></span> English'>English</option>
</select>
<?php // echo $this->Html->script('jquery.timepicker.min'); ?>
<?php echo $this->Html->script('jquery-3.3.1'); ?>
<?php echo $this->Html->script('bootstrap.min'); ?>
<?php // echo $this->Html->script('bootstrap-datepicker.min'); ?>
<?php echo $this->Html->script('myScript'); ?>
<?php // echo $this->Html->script('jquery.easing.min'); ?>
<?php //echo $this->Html->script('bootstrap-formhelpers.min'); ?>
<?php echo $this->Html->script('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/js/bootstrap-select.min.js'); ?>
<?php echo $this->Html->script('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/js/bootstrap-select.min.js'); ?>
</div>
<div id="footer">
<div class="form-inline row">
<div class="form-group col-xs-6 col-sm-3 col-md-3">
<br/>
<?php // echo $this->Html->link($cakeDescription, '#'); ?>
<ul id="menu" class="navlist">
<li class="contenedor">
Social network:
</li>
<li onclick="window.open('https://www.facebook.com', '_blank');" class="contenedor">
<img src="https://www.google.com/s2/favicons?domain=https://facebook.com" title="Facebook" class="imagen"/>
</li>
<li onclick="window.open('https://www.instagram.com', '_blank');" class="contenedor">
<img src="https://www.google.com/s2/favicons?domain=https://instagram.com" title="Instagram" class="imagen"/>
</li>
<li onclick="window.open('https://www.linkedin.com', '_blank');" class="contenedor">
<img src="https://www.google.com/s2/favicons?domain=https://linkedin.com" title="Linkedin" class="imagen"/>
</li>
</ul>
</div>
<div class="form-group col-xs-6 col-sm-3 col-md-3">
<br/>
<a class="tip">
<label>
Designed by
</label>
<span class="by">
Leader:
Brand:
Communication:
Development:
</span>
</a>
</div>
<div class="form-group col-xs-6 col-sm-3 col-md-3">
</div>
</div>
</div>
</div>
<?php echo $this->element('sql_dump'); //muestra consultas sql ?>
</body>
</html>
Instead of returning
false
, you can do aredirect
so that the request returns to beGET
and the form is not sent again when reloading the pageThis is called POST/REDIRECT/GET (PRG)