when i am upload multiple images i found The request has been black-holed
Error: The requested address '/admins/uploadimage1' was not found on this server.
my contoller function
public function uploadimage1()
{
if($this->request->is('post'))
{
$a=$this->data['Admins']['imgs'];
print_r($a);
}
}
view file
<?php echo $this->Form->create('Admins',array('controller'=>'Admins','action'=>'uploadimage1', 'type'=>'file', 'accept-charset'=>'utf-8'));?>
<table width="95%">
<tr><td><b>Image Title</b></td><td><?php echo $this->Form->input('title', array('type' => 'text', 'class'=>'input-block-level','placeholder'=>'Image Title' ,'label'=>false )); ?></td></tr>
<tr><td></td><td>
<?php echo $this->Form->input('imgs.',array('type'=>'file', 'label'=>false, 'multiple')); ?></td></tr>
<tr><td></td><td><?php echo $this->Html->image('../img/adminimages/upload.jpg', array('id'=>'blah','height'=>'100px','width'=>'100px')); ?></td></tr>
<tr><td></td><td>
<?php
foreach ($Retailers as $Retailer)
{
$r_id=$Retailer['Retailer']['id'];
echo $this->Form->input('r_id', array('type'=>'hidden','value'=>$r_id)); }?>
<?php echo $this->Form->submit('Submit',array('class' => 'button')); ?></td></tr></table>
<?php echo $this->Form->end();
my controller
<?php
App::uses('AppController', 'Controller');
class AdminsController extends AppController
{
public $name='Storelocators/Admins';
/**
* This controller does not use a model
*
* #var array
*/
public $uses = array('Admin','Retailer','Gallery');
public function beforeFilter() {
$this->Security->unlockActions = ('uploadimage1');
$this->Auth->allow('login','logout','signup','abhi');
}
public function beforeRender() {
parent::beforeRender();
}
public function index()
{
$this->layout='admin';
}
public function signup()
{
$this->layout='admin';
if($this->request->is('post'))
{
$admin_data=array (
'username'=>$this->data['Admins']['username'],
'email'=>$this->data['Admins']['email'],
'type'=>'Admin',
'password'=>$this->Auth->password($this->data['Admins']['password']));
$this->Admin->save($admin_data);
$this->Session->setFlash(__('Your are successfully Sign up.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
public function login(){
$this->layout='admin';
if($this->request->is('post')){
if($this->Auth->login()){
$name = $this->Auth->user('username');
$this->Session->write('a', $name);
$this->redirect($this->Auth->redirect());
}
else{
$this->Session->setFlash(__("Your email/password combination was incorrect.", true));
$this->redirect($this->referer());
}
}
}
public function logout(){
$this->Session->delete('a');
$this->layout = false;
$this->autoRender = false;
$this->Session->setFlash(__('You have logout successfully.', true), 'default', array('class' => 'message success'));
$this->redirect($this->Auth->logout());
}
public function form()
{
$this->layout='admin';
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']) && !empty($this->data['Admins']['imgs1']['name']) )
{
$file=$this->data['Admins']['imgs'];
$file1=$this->data['Admins']['imgs1'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/UploadImages/' .$date1.'_'.$file['name'] );
move_uploaded_file($file1['tmp_name'], WWW_ROOT . 'img/adminimages/UploadImages/' .$date1.'_'.$file1['name'] );
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$n1 = $this->request->data['Admins']['imgs1'] = $file1['name'];
$date=date('d/m/Y');
$days1=$this->data['Admins']['days'];
$day=implode(",",$days1);
$r_type1=$this->data['Admins']['r_type'];
$r_types=implode(",",$r_type1);
$my_data=array(
'name'=>ucfirst($this->data['Admins']['name']),
'address'=>ucfirst($this->data['Admins']['address']),
'province'=>ucfirst($this->data['Admins']['province']),
'region'=>ucfirst($this->data['Admins']['region']),
'city'=>ucfirst($this->data['Admins']['city']),
'nation'=>ucfirst($this->data['Admins']['nation']),
'r_type'=>$r_types,
'open_hours'=>$this->data['Admins']['hours1'].','.$this->data['Admins']['hours2'],
'days'=>$day,
'description'=>ucfirst($this->data['Admins']['description']),
'logo_image'=>$date1.'_'.$n,
'main_image'=>$date1.'_'.$n1,
'status'=>'Active',
'create_date'=>$date
);
$this->Retailer->save($my_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect(array('controller'=>'Admins','action'=>'uploadimage'));
}
}
}
}
public function addname()
{
$this->layout='admin';
}
public function tabel()
{
$this->layout='admin';
$this->set('Retailers' , $this->Retailer->find('all'));
}
public function uploadimage()
{
$this->layout='admin';
$this->set('Retailers', $this->Retailer->find('all', array('order'=>array('Retailer.id DESC'),'limit'=>'1')));
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']))
{
$file=$this->data['Admins']['imgs'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/GalleryImages/' .$date1.'_'.$file['name'] );
$date=date('d/m/Y');
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$gal_data=array(
'r_id'=>$this->data['Admins']['r_id'],
'image'=>$date1.'_'.$n,
'title'=>ucfirst($this->data['Admins']['title']),
'create_date'=>$date);
$this->Gallery->save($gal_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
}
}
public function addimage($id)
{
$this->layout='admin';
$ir=$this->Retailer->findById($id);
if($ir['Retailer']['status']=='Active')
{
$this->set('Gs',$this->Gallery->find('all', array('conditions'=>array('Gallery.r_id'=>$id))));
//print_r($Gs);
//print_r($Gallerys);
//exit();
if(!empty($id))
{
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']))
{
$file=$this->data['Admins']['imgs'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/GalleryImages/' .$date1.'_'.$file['name'] );
$date=date('d/m/Y');
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$gal_data=array(
'r_id'=>$id,
'image'=>$date1.'_'.$n,
'title'=>ucfirst($this->data['Admins']['title']),
'create_date'=>$date);
$this->Gallery->save($gal_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
}
}
}
else
{
$this->Session->setFlash(__('First Active this Retailer', true));
$this->redirect($this->referer());
}
}
public function uploadimage1()
{
if($this->request->is('post'))
{
$a=$this->data['Admins']['imgs'];
print_r($a);
}
}
public function updatestatus($id)
{
$urs=$this->Retailer->findById($id);
if($urs['Retailer']['status']=='Active')
{
$this->Retailer->updateAll(array('Retailer.status' => '"De-Active"'), array('Retailer.id' => $id));
$this->redirect(array('controller'=>'Admins', 'action'=>'tabel'));
}
else
{
$this->Retailer->updateAll(array('Retailer.status' => '"Active"'), array('Retailer.id' => $id));
$this->redirect(array('controller'=>'Admins', 'action'=>'tabel'));
}
}
public function gallery()
{
$this->layout='admin';
//$this->set('Gs',$this->Gallery->find('all'));
//$this->set('Gs',$this->Gallery->find('all', array('joins' => array(array('table' => 'retailers','alias' => 'Re','type' => 'inner','foreignKey' => true,'conditions'=> array('Re.id = Gallery.r_id'))))));
$this->Set('Gs',$this->Gallery->find('all',array('fields'=> array('*','*'), 'joins'=> array( array('table'=>'retailers', 'type'=>'inner','conditions'=>array('Gallery.r_id=retailers.id','retailers.status'=>'Active'))))));
// print_r($Gs);
// $db =& ConnectionManager::getDataSource('default');
// $db->showLog();
// exit();
}
} ?>
This is my controller.
Its not a issue on multiple upload. Its showing bcz of Security Component. You can bypass this by adding $this->Security->unlockActions = array('your actions');
Add this code to your controller.....
public function beforeFilter(){
$this->Security->unlockActions = array('action_name');
}
You have to change the Security config.
Right:
$this->Security->config('unlockedActions', 'action_name');
Wrong:
$this->Security->unlockedActions = ['action_name'];
Related
I have a CakePHP app that I am trying to upgrade from 1.3 to 2.7.5 and I can hit the log in page but when I go to log in, it doesn't do anything, no errors, just basically refreshes the page. I am really confused why this is happening and would greatly appreciate any help I could get. I did post another question about this but deleted it because it did not provide enough of the code to solve the problem. I have included the AppController as well as the Users controller below.
AppController.php
?php
class AppController extends Controller {
var $components = array('Auth', 'Session', 'RequestHandler');
var $uses = array('Tour');
function beforeFilter() {
$this->setLayout();
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'find_home');
$this->Auth->autoRedirect = false;
if ($this->Session->check('Auth.User.userid')) {
$tour = $this->Tour->findByUserid($this->Session->read('Auth.User.userid'));
$user = $this->Auth->user();
$tour = $this->Tour->findByUserid($user['User']['userid']);
$user['Tour'] = $tour['Tour'];
$this->set('user', $user);
}else if (isset($_GET['token'])) {
$tour = $this->Tour->read(null, $_GET['token']);
if ($tour) {
$tour['Tour']['sessionmodified'] = date('Y-m-d H:i:s');
$this->Tour->save($tour);
$this->set('user', $tour);
}
}
}
private function setLayout() {
if (array_key_exists('prefix', $this->params)) {
if ($this->params['prefix'] == 'admin') {
$this->layout = 'admin';
}else if ($this->params['prefix'] == 'teacher') {
$this->layout = 'teacher';
}
}
}
}
?>
UserController.php
function login() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete all old tokens
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
// Create a new token
$this->Tour->create();
$this->Tour->save(array('token' => md5(rand()), 'userid' => $this->Auth->user('userid')));
// Update login count
$user = $this->User->read(null, $this->Auth->user('userid'));
$user['User']['logincount']++;
$this->User->saveField('logincount', $user['User']['logincount']);
// Update last login time
$this->User->saveField('lastlogin', date('Y-m-d h:m:s'));
$this->redirect($this->find_home());
}
}
function logout() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete any tours
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
}
$this->redirect($this->Auth->logout());
}
function index() {
$this->layout = false;
$this->autoRender = false;
Configure::write('debug', 0);
ini_set('soap.wsdl_cache_enabled', '0');
$server = new SoapServer('http://' . $_SERVER['HTTP_HOST'] . $this->webroot . 'users/wsdl');
$server->setClass('User');
$server->handle();
}
i'm beginner in yii and in the Yii Application Development CookBook(2nd edition) on pages 105 to 113 when i'm running this codes, add button does not work, While everything is in accordance with the text of the book, where is problem? please help me.
Some code easily run but others like this are not.
controller is:
<?php
class TodoController extends Controller
{
public function actionIndex()
{
$task = new Task();
$this->render('index', array(
'task' => $task,
));
}
public function actionTask()
{
$req = Yii::app()->request;
if($req->isPostRequest) {
$this->handlePost($req->getPost('id'),
$req->getPost('Task'));
}
elseif($req->isPutRequest) {
$this->handlePut($req->getPut('Task'));
}
elseif($req->isDeleteRequest) {
$this->handleDelete($req->getDelete('id'));
}
else {
$this->handleGet($req->getParam('id'));
}
}
private function handleGet($id)
{
if($id) {
$task = $this->loadModel($id);
$this->sendResponse($task->attributes);
}
else {
$data = array();
$tasks = Task::model()->findAll(array('order' => 'id'));
foreach($tasks as $task) {
$data[] = $task->attributes;
}
$this->sendResponse($data);
}
}
private function handlePut($data)
{
$task = new Task();
$this->saveTask($task, $data);
}
private function handlePost($id, $data)
{
$task = $this->loadModel($id);
$this->saveTask($task, $data);
}
private function saveTask($task, $data)
{
if(!is_array($data)){
$this->sendResponse(array(), 400, array('No data
provided.'));
}
// $task->setAttributes($data);
$task->attributes = $data;
if($task->save()) {
$this->sendResponse($task->attributes);
} else {
$errors = array();
foreach($task->errors as $fieldErrors) {
foreach($fieldErrors as $error) {
$errors[] = $error;
}
}
$this->sendResponse(array(), 400, $errors);
}
}
private function handleDelete($id)
{
$task = $this->loadModel($id);
if($task->delete()) {
$this->sendResponse('OK');
}
else {
$this->sendResponse(array(), 500, array('Unable to
delete task.'));
}
}
private function loadModel($id)
{
$task = Task::model()->findByPk($id);
if(!$task) {
$this->sendResponse(array(), 404, array('Task not
found.'));
}
return $task;
}
private function sendResponse($data, $responseCode = 200,
$errors = array())
{
$messages = array(
200 => 'OK',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Internal Server Error',
);
if(in_array($responseCode, array_keys($messages))) {
header("HTTP/1.0 $responseCode ".$messages[$responseCode],
true, $responseCode);
}
echo json_encode(array(
'errors' => $errors,
'data' => $data,
));
Yii::app()->end();
}
}
?>
and view is:
<?php
Yii::app()->clientScript->registerPackage('todo');
$options = json_encode(array(
'taskEndpoint' => $this->createUrl('todo/task'),
));
Yii::app()->clientScript->registerScript('todo', "todo.
init($options);", CClientScript::POS_READY);
?>
<div class="todo-index">
<div class="status"></div>
<div class="tasks"></div>
<div class="new-task">
<?php echo CHtml::beginForm()?>
<?php echo CHtml::activeTextField($task, 'title')?>
<?php echo CHtml::submitButton('Add')?>
<?php echo CHtml::endForm()?>
</div>
</div>
<script id="template-task" type="text/x-dot-template">
<div class="task{{? it.done==1}} done{{?}}" data-id="{{!it.
id}}">
<input type="checkbox"{{? it.done==1}}checked {{?}}/>
<input type="text" value="{{!it.title}}" />
Remove
</div>
</script>
I want when click on the add button, task added.
I have this code:
if (strtolower($_POST['skype']) == "yummy")
echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or
$_POST['IGN'] == '' or
$_POST['pass'] == '' or
!isset($_POST['rules']) or
!isset($_POST['group']) or
strlen($_POST['pass']) <= 7)
{
redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
exit;
}
However, I would like to start reporting specific errors. For example, this is how I would do it with if statements:
...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" );
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" );
...
However that's big, messy and inefficient. What would a solution to this be?
You could use associative array like this.
function redir($var){
echo $var;
}
$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');
redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);
Create Request class for parsing data from post and get, the class helps you with validation of undefined, empty fields and Report class which helps you with throwing errors.
Here is the very simple Request class:
class Request {
protected $items = array(
'get' => array(),
'post' => array()
);
public function __construct(){
$this->items['post'] = $_POST;
$this->items['get'] = $_GET;
}
public function isPost(){
return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
}
public function isGet(){
return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
}
public function getPost($name){
return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null;
}
public function get($name){
return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
}
}
And Report class:
Class Report {
protected static $instance;
private $messages = array();
private function __construct(){}
public function getInstance(){
if(!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function addReport($message){
$this->messages[] = $message;
}
public function hasReports(){
return (!empty($this->messages)) ? true : false;
}
public function getReports(){
return $this->messages;
}
//this is not so cleaned .... it must be in template but for example
public function throwReports(){
if(!empty($this->messages)){
foreach($this->messages as $message){
echo $message."<br />";
}
}
}
}
So and how to use is for your problem:
$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
if(!$request->getPost("icq")){
$report->addMessage("you dont enter ICQ");
}
if(!$request->getPost("skype")){
$report->addMessage("you dont enter SKYPE");
}
//....etc
//if we have some reports throw it.
if($report->hasReports()){
$reports->throwReports();
}
}
The report class you can combine with sessions and throw errors after redirect, just update the class to saving reports to session instead of $messages, and after redirect if u will be have messages throw it and clear at the same time.
how about
$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
redir(...);
exit;
}
}
Perhaps something like that (reusable, but lengthy):
// validation parameters
$validation = array(
'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
'IGN' => array('check' => 'not_empty', 'error' => 'IGN empty'),
'pass' => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
'group' => array('check' => 'set', 'error' => 'group unset'),
'rules' => array('check' => 'set', 'error' => 'group unset')
);
// validation class
class Validator {
private $params;
private $check_methods = array('not_empty', 'size', 'set');
public function __construct($params){
$this->params = $params;
}
private function not_empty($array, $key){
return $array[$key] == '';
}
private function size($array, $key ,$s){
return strlen($array[$key]) < $s;
}
private function set($array, $key){
return isset($array[$key]);
}
private handle_error($err, $msg){
if ($err) {
// log, redirect etc.
}
}
public function validate($data){
foreach($params as $key => $value){
if (in_array($value['check'], $this->check_methods)){
$params = $value['params'];
array_unshift($params, $data, $key);
$this->handler_error(call_user_func_array(array($this,$value['check']),
$params),
$value['error']);
}
}
}
};
// usage
$validator = new Validator($validation);
$validator->validate($_POST);
Just expand the class with new checks, special log function etc.
Warning: untested code.
This is how I do error reporting now:
$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
if ($current == '' || $current == null) {
//The error should be stored in a session, but the question asked for URL storage
redir('/apply/?fail='.urlencode($errors[$current]));
}
}
After any ajax request all subsequent non ajax request is returning with ajax layout instead of default layout.
Obs:
Ocurrs only on production enviroment.
Configure::write('Cache.disable', true); // Don't have any effect!
Cake Version 2.4.4
After 20 ~ 30 seconds the layout (default) is rendered.
config/core.php is identical.
I don't no why , and i loose 8 hours on that, any tip?
The controller (But any ajax on any controller cause the problem:
<?php
App::uses('AppController', 'Controller');
class NewslettersController extends AppController
{
public $paginate = array(
'limit' => 20,
'paramType' => 'querystring',
'order' => array(
'Newsletter.created' => 'DESC'
)
);
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow(array('add','push'));
}
public function admin_index()
{
$this->set('dataGrid', $this->paginate('Newsletter'));
}
public function admin_view($id = null)
{
$this->Newsletter->id = $id;
$result = $this->Newsletter->read();
if (!$result) {
$this->setFlashMessage('Cadastro não encontrado', 'error', array('action' => 'index'));
return false;
}
$this->set('dataGrid', $result);
}
public function admin_delete($id = null)
{
$this->Newsletter->id = $id;
if (!$this->Newsletter->exists()) {
$this->Session->setFlash('O item solicitado não foi encontrado!', 'alert_error');
$this->setFlashMessage('O item solicitado não foi encontrado!', 'error', array('action' => 'index'));
}
try {
if ($this->Newsletter->delete($id, false)) {
$this->setFlashMessage('Item excluído com sucesso!', 'success', array('action' => 'index'));
}
} catch (Exception $e) {
$this->setFlashMessage('Não foi possivel excluir este item pois existem itens atrelados a ele', 'error', array('action' => 'index'));
}
}
public function admin_search()
{
$this->autoRender = false;
$conditions = null;
if (isset($this->request->query['search']) && !empty($this->request->query['search'])) {
$conditions[] = array(
'OR' => array(
'Newsletter.name LIKE' => '%' . $this->request->query['search'] . '%',
'Newsletter.email LIKE' => '%' . $this->request->query['search'] . '%',
)
);
$this->paginate['conditions'] = $conditions;
$this->set('dataGrid', $this->paginate());
$this->render('admin_index');
}
}
//######################
//# FRONTEND #
//######################
public function push()
{
if($this->Newsletter->save($this->request->data))
{
$response = array("result"=>true,"id"=>$this->Newsletter->id);
}
else
{
$response = array("result"=>false,"errors"=>$this->Newsletter->validationErrors);
}
return new CakeResponse(array("body" => json_encode($response),"type" => "json"));
}
}
?>
You have to differentiate the layout for ajax in the method, please the following changes I made in the above code:
...
class NewslettersController extends AppController
{
public layout = 'default';
...
public function push() // if this is ajax function
{
$this->layout = 'ajax'; //put this for ajax functions only
....
}
...
}
Hope it helps!
I may well be missing something quite obvious, but I'm still a bit lost. The actual database interaction seems to be the catch. I mean, the table is created on installation, but actually sending the information doesn't seem to work as it triggers the validation regardless of what I enter. If I turn off the field requirements, the database fails to receive the information entirely.
From the controller:
class Admin extends Admin_Controller
{
private $show_validation_rules = array(
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'trim|max_length[100]|required'
),
array(
'field' => 'location',
'label' => 'Location',
'rules' => 'trim|max_length[300]'
),
array(
'field' => 'support',
'label' => 'Support',
'rules' => 'trim|required'
)
);
public function __construct()
{
parent::__construct();
$this->load->model('shows_m');
$this->load->library('form_validation');
$this->lang->load('shows');
$this->load->helper('html');
$this->template->set_partial('shortcuts', 'admin/partials/shortcuts');
}
public function index()
{
$view_data = array();
$view_data['shows'] = $this->shows_m->get_all();
$this->template->build('admin/index', $view_data);
}
public function create()
{
$shows = $this->shows_m->get_all();
$this->form_validation->set_rules($this->show_validation_rules);
if ( $this->form_validation->run() )
{
if ($this->shows_m->insert_show($this->input->post()))
{
$this->session->set_flashdata('success', lang('shows.create_success'));
redirect('admin/shows/index');
} else {
$this->session->set_flashdata('error', lang('shows.create_error'));
redirect('admin/shows/create');
}
}
foreach($this->show_validation_rules as $rule)
{
$shows[$rule['field']] = $this->input->post($rule['field']);
}
$view_data = array(
'shows' => $shows
);
$this->template->build('admin/create', $view_data);
}
public function edit($id)
{
$this->form_validation->set_rules($this->show_validation_rules);
$show = $this->shows_m->get($id);
if ( empty($show) )
{
$this->session->set_flashdata('error', lang('shows.exists_error'));
redirect('admin/shows');
}
if ( $this->form_validation->run() )
{
if ( $this->shows_m->update_entry($id, $this->input->post()) === TRUE )
{
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows/');
}
else
{
$this->session->set_flashdata('success', lang('shows.update_success'));
redirect('admin/shows/edit/' . $id);
}
} else {
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows/edit/' . $id);
}
else
{
$this->session->set_flashdata('error', lang('shows.update_error'));
redirect('admin/shows/edit/' . $id);
}
}
}
foreach($this->show_validation_rules as $rule)
{
if ($this->input->post($rule['field']))
{
$show[$rule['field']] = $this->input->post($rule['field']);
}
}
$view_data = array(
'shows' => $show
);
$this->template->build('admin/edit', $view_data);
}
public function delete($id = NULL)
{
$id_array = array();
if ( $this->input->post() )
{
$id_array = $this->input->post()['action_to'];
}
else
{
if ( $id !== NULL )
{
$id_array[0] = $id;
}
}
if ( empty($id_array) )
{
$this->session->set_flashdata('error', lang('shows.id_error'));
redirect('admin/shows');
}
foreach ( $id_array as $id)
{
$show = $this->shows_m->get($id);
if ( !empty($show) )
{
if ( $this->shows_m->delete($id) == FALSE )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows');
}
}
}
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows');
}
}
From the details.php file
public function install()
{
$this->dbforge->drop_table('shows');
$shows = "
CREATE TABLE ".$this->db->dbprefix('shows')." (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` varchar(100) NOT NULL,
`location` varchar(300) NOT NULL,
`support` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
";
if($this->db->query($shows))
{
return TRUE;
}
}
The intent of the module is, in short to output the date of the show, the location and any supporting bands and other info by inserting a tag produced by the module in to the pertinent page on the site.
I'm inclined to think it should be quite simple and that I'm missing something obvious, but who knows. If I am, feel free to yell at me, I'd appreciate it.
Edit:
Code for the model
class Shows_m extends MY_Model {
public function get_all($limit = NULL)
{
$this->db->order_by("id", "desc");
if (isset($limit)){ $this->db->limit($limit); }
$results = $this->db->get('shows');
$result = $results->result_array();
return $result;
}
public function get($id)
{
$results = $this->db->get_where('shows', array('id' => $id));
$result = $results->row_array();
return $result;
}
public function insert_show($input)
{
$to_insert = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
}
public function update_entry($id, $input)
{
$new_data = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if (isset ($input['delete']) )
{
if($this->delete($id))
{
return TRUE;
} else {
return FALSE;
}
} else {
$this->db->where('id', $id);
if ($this->db->update('shows', $new_data))
{
return TRUE;
} else {
return FALSE;
}
}
}
public function delete($id)
{
if ($this->db->delete('shows', array('id' => $id)))
{
return TRUE;
} else {
return FALSE;
}
}
}
It might be your insert in the model
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
Try instead:
$this->db->insert('shows',$to_insert);
$query_result = $this->db->insert_id();
if($query_result){
return TRUE;
}else{
return FALSE;
}
I don't think insert returns anything.
At any rate, it doesn't sound like validation is the problem. The query isn't getting to the db. If the above isn't the issue, try just echoing out the POST data; make sure it's getting to the model (make sure the HTML is as expected--input names and such).