Cake php ajax layout cache - php

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!

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

unexpected end of file [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I had an unexpected end of file error but I checked my code and I didn't find any sign of this error! So can you tell me what may be the cause of this problem! Here is my file's code that contains the error (this is a project done with cakephp):
<?php
App::uses('AppController', 'Controller');
class AdminsController extends AppController {
public function login($id = null)
{
$this->layout='login';
if ($this->request->is('post')) {
$user=$this->request->data['Admin']['r'];
if ($user == 'Administrator')
{
$Admin=$this->request->data['Admin']['login'];
$mdp=$this->request->data['Admin']['motpasse'];
$Admins=$this->Admin->find('count',array('conditions'=>array('Admin.login'=>$Admin,'Admin.motpasse'=>$mdp)));
if ($Admins ==1)
{sleep(2);
CakeSession::write('admin','admin' );
CakeSession::write('nom',$Admin);
$this->redirect(array('action' => 'index'));
}else {?><script type="text/javascript">
confirm('M.Admin Login ou Mot de passe incorrect');
</script><?}
}
if ($user == 'Commercial')
{
App::Import('Model', 'Commercial');
$Admin=$this->request->data['Admin']['login'];
$mdp=$this->request->data['Admin']['motpasse'];
$category = new Commercial();
$categories = $category->find('count',array('conditions'=>array('Commercial.login'=>$Admin,'Commercial.motpasse'=>$mdp)));
if ($categories ==1)
{
CakeSession::write('admin','com' );
CakeSession::write('nom',$Admin);
$this->redirect(array('controller' => 'Commercials', 'action' => ''));
}
}
}
}
public function logout($id = null)
{
$this->Session->destroy();
$this->redirect(array('action' => 'login'));
}
public function index() {
$admin=CakeSession::read('admin');
if(($admin<>'admin')&&($admin<>'com'))
{$this->redirect(array('controller' => 'Admin', 'action' => 'login'));}
if($admin=='com')
{$this->layout='Commercials';}
$this->Admin->recursive = 0;
$this->set('admins', $this->paginate());
}
public function view($id = null) {
$admin=CakeSession::read('admin');
if(($admin<>'admin')&&($admin<>'com'))
{$this->redirect(array('controller' => 'Admin', 'action' => 'login'));}
if($admin=='com')
{$this->layout='Commercials';}
if (!$this->Admin->exists($id)) {
throw new NotFoundException(__('Invalid admin'));
}
$options = array('conditions' => array('Admin.' . $this->Admin->primaryKey => $id));
$this->set('admin', $this->Admin->find('first', $options));
}
public function add() {
$admin=CakeSession::read('admin');
if(($admin<>'admin')&&($admin<>'com'))
{$this->redirect(array('controller' => 'Admin', 'action' => 'login'));}
if($admin=='com')
{$this->layout='Commercials';}
if ($this->request->is('post')) {
$this->Admin->create();
if ($this->Admin->save($this->request->data)) {
$this->Session->setFlash(__('The admin has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
}
}
$questionnaires = $this->Admin->Questionnaire->find('list');
$this->set(compact('questionnaires'));
}
public function delete($id = null) {
$admin=CakeSession::read('admin');
if(($admin<>'admin')&&($admin<>'com'))
{$this->redirect(array('controller' => 'Admin', 'action' => 'login'));}
if($admin=='com')
{$this->layout='Commercials';}
$this->Admin->id = $id;
if (!$this->Admin->exists()) {
throw new NotFoundException(__('Invalid admin'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Admin->delete()) {
$this->Session->setFlash(__('Admin deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Admin was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
?>
This is the error that shows up:
And have a look here:
if ($Admins ==1)
{sleep(2);
CakeSession::write('admin','admin' );
CakeSession::write('nom',$Admin);
$this->redirect(array('action' => 'index'));
}else {?><script type="text/javascript">
confirm('M.Admin Login ou Mot de passe incorrect');
</script><? } // look at here
?>
that should be:
if ($Admins ==1)
{sleep(2);
CakeSession::write('admin','admin' );
CakeSession::write('nom',$Admin);
$this->redirect(array('action' => 'index'));
}else {?><script type="text/javascript">
confirm('M.Admin Login ou Mot de passe incorrect');
</script><?php } // your little mistake was here
?>
Did you notice you were missing php there.

The request has been black-holed

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'];

CakePHP 2.0, Submit form redirect not rendering properly

Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)

CakePHP 2.x Translate Behavior Not Saving to i18n Table

I've followed the instructions in the manual for setting up Translate Behavior with CakePHP 2.1, as well as this question here on Stack. I am not getting any errors, but my translated posts are not saving to my i18n table.
Here is my PostModel.php:
class Post extends AppModel {
public $title = 'Post';
public $name = 'Post';
public $body = 'Post';
public $actAs = array(
'Translate' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation'
)
);
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
And here are my add and edit functions in PostsController.php:
public function add() {
if ($this->request->is('post')) {
$this->Post->locale = 'fre';
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.', true));
$this->redirect(array('action' => 'admin'));
} else {
$this->Session->setFlash(__('Unable to add your post.', true));
}
}
}
public function edit($id = null) {
$this->Post->id = $id;
if ($this->request->is('get'))
{
$this->Post->locale = 'fre';
$this->request->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->request->data))
{
$this->Post->locale = 'fre';
$this->Session->setFlash(__('Your post has been updated.', true));
$this->redirect(array('action' => 'admin'));
}
else
{
$this->Session->setFlash(__('Unable to update your post.', true));
}
}
}
I initialized the i18n table using Console. Should I drop the table and try reinitializing? Not sure why there would be a problem there.
More reusable solution is to add to your AppModel:
class AppModel extends Model {
public $actsAs = array('Containable');
/**
* Converts structure of translated content by TranslateBehavior to be compatible
* when saving model
*
* #link http://rafal-filipek.blogspot.com/2009/01/translatebehavior-i-formularze-w.html
*/
public function afterFind($results, $primary = false) {
if (isset($this->Behaviors->Translate)) {
foreach ($this->Behaviors->Translate->settings[$this->alias] as $value) {
foreach ($results as $index => $row) {
if (array_key_exists($value, $row)) {
foreach($row[$value] as $locale) {
if (isset($results[$index][$this->alias][$locale['field']])) {
if (!is_array($results[$index][$this->alias][$locale['field']])) {
$results[$index][$this->alias][$locale['field']] = array();
}
$results[$index][$this->alias][$locale['field']][$locale['locale']] = $locale['content'];
}
}
}
}
}
}
return $results;
}
}
This code automatically converts what returns TranslateBehavior to be able to create multi-language form like:
echo $this->Form->input('Category.name.eng');
echo $this->Form->input('Category.name.deu');
echo $this->Form->input('Category.name.pol');
Tested on CakePHP 2.3. And I discovered that now Model->saveAssociated() is required instead of Model->save().
Try to add this in your form on add.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('Post.title.fre');
echo $this->Form->input('Post.body.fre');
//Something more...
echo $this->Form->end(__('Submit'));
?>
in your edit.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('id');
echo $this->Form->input('Post.title.fre', array('value'=>$this->request->data['titleTranslation'][0]['content'));
echo $this->Form->input('Post.body.fre', array('value'=>$this->request->data['bodyTranslation'][0]['content'));
//Something more...
echo $this->Form->end(__('Submit'));
?>
assuming index of data['titleTranslation'][0] is in French, to easily see an array in the view I recommend to use DebugKit https://github.com/cakephp/debug_kit
I hope this will help
Use saveMany instedof save. it's working fine for me.
For those who have the same problem: the correct variable is $actsAs, not $actAs.

Categories