Magento Custom Admin Module with a Image File - php

I am trying to create an admin module in Magento.
Step 1:
which contains the following fields
Step 2 : Filled some values and a Image
Step 3 : When i am trying to Save this Item, the item is saved Successfully but image is not showing here. But actually that images is copied in my Magento Media folder.
Step 4 : After the item saved successfully it is showing like this
But Actually i want it to show something like this
Here is My Code Please Find it.
_prepareForm() - fieldset code :
$fieldset->addField('image', 'file', array(
'label' => Mage::helper('modulename')->__('Image'),
'name' => 'image',
'note' => '(*.jpg, *.png, *.gif)',
));
_prepareForm() :
<?php
class Namespace_ModuleName_Block_Adminhtml_Measurement_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
?>
saveAction() :
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('modulename/modulename');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
if(isset($_FILES['image']['name']) and (file_exists($_FILES['image']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(false);
// setAllowRenameFiles(true) -> move your file in a folder the magento way
// setAllowRenameFiles(true) -> move your file directly in the $path folder
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . '/modulename_images/' ;
$uploader->save($path, $model->getId().'.jpg');
$model->setImage($model->getId().'.jpg');
$model->save();
}catch(Exception $e) {
print_r($e);
die;
}
}
else {
if(isset($data['image']['delete']) && $data['image']['delete'] == 1)
$data['image_main'] = '';
else
unset($data['image']);
}
// Mage::getModel('modulename/flatrates')->saveMultipleFlatrates($data, $model->getId(),$this->getRequest()->getParam('cat_id'));
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('modulename')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('modulename')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Anything wrong i did here ?
any ideas ?
If any spell mistakes i am really sorry.

In order to get the image preview, you have to use the image field type, not file, like this (look at second parameter):
$fieldset->addField('image', 'image', array(
'label' => Mage::helper('modulename')->__('Image'),
'name' => 'image',
'note' => '(*.jpg, *.png, *.gif)',
));

This is because of you have store your image in Subdirectory of media folder so you have to setvalue() of your image field before display..
like in EditAction() add this code here is my field name profile_pic
if($model->getProfilePic())
{
$model->setProfilePic('testimonial/'.$model->getProfilePic());
}
OR you can use helper to preview that image

Related

Image update and remove old image on Laravel

Trying to implement update article in my update controller it seems works, but the problem is when I only want to update the post without uploading an image the old always getting remove which is it shouldn't.
here's my store function
public function store(Post $post)
{
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'New ariticle has been posted');
}
}
here's my validation
private function validateRequest()
{
return request()->validate([
'title'=> 'required',
'content' => 'required',
'image' => 'sometimes|image|max:5000',
]);
}
here's my update function
public function update(Post $post)
{
File::delete(public_path('storage/'.$post->image));
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'This post has
been Edited');
}
}
I've tried to add File::delete to my storeImage function and delete it from my update function, it fix the problem but the old image is not removed from directory
private function storeImage($post)
{
if (request()->has('image')){
File::delete(public_path('storage/'.$post->image))
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}
Ok since I use model binding in my controller I don't have to find the id right?
so I change my update function which is basically Akhtar munir suggested, and turn out to be something like this. The image update work, it also remove the old image when I update it. But I have found another issue, the problem is when I edit article and title it didn't change like when I update it, I hope you can take look at this is this correct?
public function update(Post $post){
$this->validateRequest();
if(request()->hasFile('image') && request('image') != ''){
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$post->update([
'title' => request()->title,
'content' => request()->content,
'image' => $image,
]);
}
}
This is what I have done in one of my method. It may help you.
public function update(Request $request, $id)
{
if (UserDocument::where('id',$id)->exists()) {
$this->validateUserDocument($request);
if ($request->hasFile('doc_file') && $request->doc_file != '') {
$doc = UserDocument::where('id',$id)->first();
// dd($doc);
$file_path = storage_path().'/app/'.$doc['doc_file'];
//You can also check existance of the file in storage.
if(Storage::exists($file_path)) {
unlink($file_path); //delete from storage
// Storage::delete($file_path); //Or you can do it as well
}
$file = $request->file('doc_file')->store('documents'); //new file path
$doc->update([
'title' => $request->title,
'doc_file' => $file //new file path updated
]);
session()->flash('success','Document updated successfully!');
return redirect()->route('userdocs');
}
session()->flash('error','Empty file can not be updated!');
return redirect()->back();
}
session()->flash('error','Record not found!');
return redirect()->back();
}
In this code, I just simply want to clearify to you that I have stored image path in database, first I have retrieved that path and with that path I have found image in my local storage, delete it first and then update it with the new one. But make sure to store image path in database in both cases ofcourse with insert and update.
So finally you can also optimize your code like this, it will do the same thing as you expect, whether image and all data or only title and content.
public function update(Post $post){
$this->validateRequest();
$data = [
'title' => request()->title,
'content' => request()->content
];
if (request()->hasFile('image') && request('image') != '') {
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$data['image'] = $image;
//$post->update($data);
}
$post->update($data);
}
Try this one
private function storeImage($post)
{
if (request()->hasFile('image')){
$image_path = "/storage/".'prev_img_name'; // prev image path
if(File::exists($image_path)) {
File::delete($image_path);
}
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}

Magento - Upload Image in Back Office

I'm trying to upload an image in Sales Rules in Magento,
I follow this tutorial :
https://wiki.magento.com/display/m1wiki/How+to+create+an+image+or+video+uploader+for+the+Magento+Admin+Panel
My fields must be in native SalesRules Magento module , so I made overloading following files:
Mage_Adminhtml_Block_Promo_Quote_Edit_Form
protected function _prepareForm()
{
$form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post','enctype' => 'multipart/form-data'));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Main
I add my field in _prepareForm() function
$fieldset->addField('image_promo', 'image', array(
'label' => Mage::helper('salesrule')->__('Image'),
'required' => false,
'name' => 'image_promo',
));
and in this file, I change my return:
From
return parent::_prepareForm();
To
return Mage_Adminhtml_Block_Widget_Form::_prepareForm();
And finally I'm overloading this file :
Mage_Adminhtml_Promo_QuoteController and I'm adding to saveAction() function :
if(isset($_FILES['image_promo']['name']) and (file_exists($_FILES['image_promo']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('image_promo');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(false);
// setAllowRenameFiles(true) -> move your file in a folder the magento way
// setAllowRenameFiles(true) -> move your file directly in the $path folder
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['image_promo']['name']);
$data['image_promo'] = $_FILES['image_promo']['name'];
}catch(Exception $e) {
Mage::logException($e);
}
}else {
if(isset($data['image_promo']['delete']) && $data['image_promo']['delete'] == 1)
$data['image_main'] = '';
else
unset($data['image_promo']);
}
When I try to save without upload any files, magento work properly, but when i have an image, i not pass through my saveAction, and i'm being redirected on Dashboard ...
I'm trying to had an hidden form_key by this way in my Main.php (Second file)
$fieldset->addField('form_key', 'hidden', array(
'value' => Mage::getSingleton('core/session')->getFormKey(),
'name' => 'form_key',
));
But this doesn't change anything !
Any idea ?

cakePHP 3.0 uploading images

I want to upload images in my cakephp 3.0 app. But I get the error message:
Notice (8): Undefined index: Images [APP/Controller/ImagesController.php, line 55]
Are there already some examples for uploading files (multiple files at once) in cakePHP 3.0? Because I can only find examples for cakePHP 2.x !
I think I need to add a custom validation method in my ImagesTable.php? But I can't get it to work.
ImagesTable
public function initialize(array $config) {
$validator
->requirePresence('image_path', 'create')
->notEmpty('image_path')
->add('processImageUpload', 'custom', [
'rule' => 'processImageUpload'
])
}
public function processImageUpload($check = array()) {
if(!is_uploaded_file($check['image_path']['tmp_name'])){
return FALSE;
}
if (!move_uploaded_file($check['image_path']['tmp_name'], WWW_ROOT . 'img' . DS . 'images' . DS . $check['image_path']['name'])){
return FALSE;
}
$this->data[$this->alias]['image_path'] = 'images' . DS . $check['image_path']['name'];
return TRUE;
}
ImagesController
public function add()
{
$image = $this->Images->newEntity();
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
$data = $this->request->data['Images'];
//var_dump($this->request->data);
if(!$data['image_path']['name']){
unset($data['image_path']);
}
// var_dump($this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$images = $this->Images->Images->find('list', ['limit' => 200]);
$projects = $this->Images->Projects->find('list', ['limit' => 200]);
$this->set(compact('image', 'images', 'projects'));
$this->set('_serialize', ['image']);
}
Image add.ctp
<?php
echo $this->Form->input('image_path', [
'label' => 'Image',
'type' => 'file'
]
);
?>
Image Entity
protected $_accessible = [
'image_path' => true,
];
In your view file, add like this, in my case Users/dashboard.ctp
<div class="ChImg">
<?php
echo $this->Form->create($particularRecord, ['enctype' => 'multipart/form-data']);
echo $this->Form->input('upload', ['type' => 'file']);
echo $this->Form->button('Update Details', ['class' => 'btn btn-lg btn-success1 btn-block padding-t-b-15']);
echo $this->Form->end();
?>
</div>
In your controller add like this, In my case UsersController
if (!empty($this->request->data)) {
if (!empty($this->request->data['upload']['name'])) {
$file = $this->request->data['upload']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
$setNewFileName = time() . "_" . rand(000000, 999999);
//only process if the extension is valid
if (in_array($ext, $arr_ext)) {
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/upload/avatar/' . $setNewFileName . '.' . $ext);
//prepare the filename for database entry
$imageFileName = $setNewFileName . '.' . $ext;
}
}
$getFormvalue = $this->Users->patchEntity($particularRecord, $this->request->data);
if (!empty($this->request->data['upload']['name'])) {
$getFormvalue->avatar = $imageFileName;
}
if ($this->Users->save($getFormvalue)) {
$this->Flash->success('Your profile has been sucessfully updated.');
return $this->redirect(['controller' => 'Users', 'action' => 'dashboard']);
} else {
$this->Flash->error('Records not be saved. Please, try again.');
}
}
Before using this, create a folder in webroot named upload/avatar.
Note: The input('Name Here'), is used in
$this->request->data['upload']['name']
you can print it if you want to see the array result.
Its works like a charm in CakePHP 3.x
Now that everyone makes advertisement for his plugins here, let me do this as well. I've checked the Uploadable behavior linked in the other question, it's pretty simple and half done it seems.
If you want a complete solution that is made to scale on enterprise level check FileStorage out. It has some features I haven't seen in any other implementations yet like taking care of ensuring your won't run into file system limitations in the case you get really many files. It works together with Imagine to process the images. You can use each alone or in combination, this follows SoC.
It is completely event based, you can change everything by implementing your own event listeners. It will require some intermediate level of experience with CakePHP.
There is a quick start guide to see how easy it is to implement it. The following code is taken from it, it's a complete example, please see the quick start guide, it's more detailed.
class Products extends Table {
public function initialize() {
parent::initialize();
$this->hasMany('Images', [
'className' => 'ProductImages',
'foreignKey' => 'foreign_key',
'conditions' => [
'Documents.model' => 'ProductImage'
]
]);
$this->hasMany('Documents', [
'className' => 'FileStorage.FileStorage',
'foreignKey' => 'foreign_key',
'conditions' => [
'Documents.model' => 'ProductDocument'
]
]);
}
}
class ProductsController extends ApController {
// Upload an image
public function upload($productId = null) {
if (!$this->request->is('get')) {
if ($this->Products->Images->upload($productId, $this->request->data)) {
$this->Session->set(__('Upload successful!');
}
}
}
}
class ProductImagesTable extends ImageStorageTable {
public function uploadImage($productId, $data) {
$data['adapter'] = 'Local';
$data['model'] = 'ProductImage',
$data['foreign_key'] = $productId;
$entity = $this->newEntity($data);
return $this->save($data);
}
public function uploadDocument($productId, $data) {
$data['adapter'] = 'Local';
$data['model'] = 'ProductDocument',
$data['foreign_key'] = $productId;
$entity = $this->newEntity($data);
return $this->save($data);
}
}
Maybe the following would help. It's a behavior who helps you to upload files very easy!
http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/
Let me know if you struggle.
Greetz
/*Path to Images folder*/
$dir = WWW_ROOT . 'img' .DS. 'thumbnail';
/*Explode the name and ext*/
$f = explode('.',$data['image']['name']);
$ext = '.'.end($f);
/*Generate a Name in my case i use ID & slug*/
$filename = strtolower($id."-".$slug);
/*Associate the name to the extension */
$image = $filename.$ext;
/*Initialize you object and update you table in my case videos*/
$Videos->image = $image;
if ($this->Videos->save($Videos)) {
/*Save image in the thumbnail folders and replace if exist */
move_uploaded_file($data['image']['tmp_name'],$dir.DS.$filename.'_o'.$ext);
unlink($dir.DS.$filename.'_o'.$ext);
}
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use Cake\Network\Exception\InternalErrorException;
use Cake\Utility\Text;
/**
* Upload component
*/
class UploadRegCompanyComponent extends Component
{
public $max_files = 1;
public function send( $data )
{
if ( !empty( $data ) )
{
if ( count( $data ) > $this->max_files )
{
throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
}
foreach ($data as $file)
{
$filename = $file['name'];
$file_tmp_name = $file['tmp_name'];
$dir = WWW_ROOT.'img'.DS.'uploads/reg_companies';
$allowed = array('png', 'jpg', 'jpeg');
if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) )
{
throw new InternalErrorException("Error Processing Request.", 1);
}
elseif( is_uploaded_file( $file_tmp_name ) )
{
move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid().'-'.$filename);
}
}
}
}
}
We're using https://github.com/josegonzalez/cakephp-upload with great success in our production app, and has done so for quite some time.
Has awesome support for using "Flysystem" (https://flysystem.thephpleague.com/) as well - which is abstractions from specific file system(s) - so moving from normal local file system to S3 is a no-brainer, or Dropbox or whatever place you want :-)
You can find related (high quality) plugins on file uploading right here: https://github.com/FriendsOfCake/awesome-cakephp#files - I've used "Proffer" with success as well, and it's by no means "almost done" or anything alike - both has all my recommendations and is in my eyes production ready!

magento custom admin module edit data field not retrieve data

I am creating custom admin module where grid, edit, new, delete work as same as product grid. Everything working fine but when i click on grid row to edit item it redirects correctly but the text field does't contains data. currently i am having one field called name my editAction as follows:
public function editAction()
{
$id = $this->getRequest()->getParam('id', null);
$model = Mage::getModel('fondation/fondation');
if ($id) {
$model->load((int) $id);
if ($model->getId()) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if ($data) {
$model->setData($data)->setId($id);
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('fondation')->__('Example does not exist')); $this->_redirect('*/*/');
}
}
Mage::register('fondation_data', $model);
$this->loadLayout();
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
}
form Class
class Npm_Fondation_Block_Adminhtml_Fondation_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('fondation_form', array('legend'=>Mage::helper('fondation')->__('Item information')));
$fieldset->addField('Name', 'text', array(
'label' => Mage::helper('fondation')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
));
if (Mage::getSingleton('adminhtml/session')->getFondationData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getFondationData());
Mage::getSingleton('adminhtml/session')->setFondationData(null);
} elseif (Mage::registry('fondation_data')) {
$form->setValues(Mage::registry('fondation_data')->getData());
}
return parent::_prepareForm();
}
}

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 :)

Categories