delete uploaded image in custom module - magento

UPDATE
I'm updating the question as I solved one of the problem in this question. The original question is below the line.
I'm now able to see the preview of the image as the problem was with the below code
$fieldset->addField('banner', 'image', array(
'label' => Mage::helper('designer')->__('Banner'),
'required' => false,
'name' => 'banner',
));
where instead of image, file was written for the type of field. But now the problem is, I'm unable to delete the previous image. I do check the delete image checkbox but the file still remains there. Why its not deleting?
I'd created a module with module creator and able to save images. But when the next time I do want to edit the record it does not show the preview of the uploaded image or the delete checkbox.
Do I need to write additional code in my adminhtml tab form?

In your saveAction of you controller you need to check if the delete image checkbox is checked.
Eg.
if (isset($_FILES['checkcsv']['name']) && $_FILES['checkcsv']['name'] != '') {
try {
...
$uploader->save($path, $logoName);
save path to database
} catch (Exception $e) {
}
}
else if((isset($data['banner']['delete']) && $data['banner']['delete'] == 1)){
//can also delete file from fs
unlink(Mage::getBaseDir('media') . DS . $data['banner']['value']);
//set path to null and save to database
$data['banner'] = '';
}

Below code write in your save action of your controller
if (isset($data['image']['delete'])) {
Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
}
$image = Mage::helper('your_helper')->uploadBannerImage();
if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
$data['image'] = $image;
} else {
unset($data['image']);
}
Write below code in your helper
public function deleteImageFile($image) {
if (!$image) {
return;
}
try {
$img_path = Mage::getBaseDir('media'). "/" . $image;
if (!file_exists($img_path)) {
return;
}
unlink($img_path);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
Replace your_helper to your actual helper class

Related

How to restrict user to add input duplicate data into database using codeigniter

I'd One text_box(txtname) & Add button in View . I've to restrict user to add already existing(duplicate) data in a database . after clicking on Add button. what changes should I've to do in Model & controller.
I tried to copy+ paste my model & controller code but due to some restrictions of website i'm not getting able to display code. please kindly suggest me what should I've to do ?
try this i hope it will help you.
first of all get data by textAddItem
//controller save data function
//get txtAdditem
$txtAddItem = $this->modelname->method_name($this->input->post('textAddItem'));
if (count($txtAddItem) > 0) {
//already existed
}
else{
$data=array(
$name=>$this->input->post('textAddItem')
);
return $query=$this->db->insert('tbl_category',$data);
}
//modele
function method_name($textAddItem) {
return $this->db->where('cat_name', $textAddItem)
->get('tbl_category')->row_array();
}
First, check the cat_name in the DB before inserting in the controller
Controller
public function function_name(){
$this->load->model('CrudModel');
$data = array('cat_name' => $name);
$if_exists = $this->CrudModel->check_category($data);
if($if_exists > 0){
//Already Exists
}else{
//New insertion
}
}
Model
public function check_category($data){
return $this->db->get_where('tbl_cateogry', $data)->num_rows();
}
public function insertMenurecord()
{
$this->load->model('CrudModel');
$this->form_validation->set_rules('txtMenuItem', 'Menu','required|is_unique[tbl_menumaster.menu_name]');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('msg','&nbsp&nbsp&nbsp Inserted record already exist');
redirect('Welcome/displayMasterMenu');
}
else
{
$this->CrudModel->saveMenudata();
$this->session->set_flashdata('msg','You have successfully Inserted record');
redirect('Welcome/displayMasterMenu');
}
}

Move Image to another Path from a clicked link; Codeigniter

The idea is to move an image selected by the current user to another path that's also in the database. Here is the Controller:
public function makeProfile() {
if (isset($_GET['makeProfile']));
$data['user_id']= $this->session->userdata['user_id'];
$fileName = ('uploads/'.$fileName);
if($this->images_model->makeProfile($data, $fileName)) {
echo "Success";
$msg = 'File successfully moved to profile';
redirect(site_url().'main/');
}else{
echo "Failure";
The Model:
Public function makeProfile ($data, $fileName) {
return $this->db->get_where('images', ['user_id' => $this->session->userdata('user_id')])->row();
move_uploaded_file('uploads/'.$fileName, 'uploads/profile/'.$fileName);
if($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
The VIEW:
<a class="profile" href="<?= base_url('main/makeProfile') ?>">Make Profile</a>
I’m probably going about this all wrong, but hoping someone here might steer me in the right direction. Thanks in advance for any and all input!
Function makeProfile in the model has an issue. You are getting the record and then returning it back. The code below is not executing
Public function makeProfile ($data, $fileName) {
$fileName= $this->db->get_where('images', ['user_id' => $this->session->userdata('user_id')])->row()->image;
// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('uploads/'.$fileName, 'uploads/profile/'.$fileName));
if($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
Quoting a couple of relevant sentences from its manual page :
Makes a copy of the file source to dest.
If the destination file already exists, it will be overwritten.

extend larasap/fb post method

I'm trying to extend the functionality of a method from this package:
https://github.com/toolkito/laravel-social-auto-posting
Because the usage from mine controller is so simple, and others package makes a big mess even for basic operation like the one I need to achieve!
Goal: -posting text over a fb page with some tags of users that have allready puted a like to the same page.
So I Start from this call:
SendTo::Facebook(
‘link’,
[
‘link’ => ‘https://github.com/toolkito/laravel-social-auto-posting',
‘message’ => ‘Laravel social auto posting’
]
);
If I simply cut the link part, the message part can be my text of the post, and all works easy.
If I try to add user's tag on the 'message' part with the notation:
#[userId]
thats not works and the tag part is cutted and only the text is showed:
If I send 'text'=>'some text #[mineuserid] more text''
only
'some text more text'
is showed on the wall.
So I move to copy and extend the methods.
If I well understand from fb documentation I can tags user with the field tags but needs to be specified even the field places (in that case if I well understand my page's id)
So I start to explore into package, and trying to mods over sends link of the package:
public static function Facebook($type, $data)
{
switch ($type) {
case 'link':
$message = isset($data['message']) ? $data['message'] : '';
$result = FacebookApi::sendLink($data['link'], $data['message']);
break;
case 'postolo':
$message = isset($data['message']) ? $data['message'] :'';
$tags =isset($data['tags']) ? $data['tags'] : '';
$places =isset($data['places']) ? $data['places'] : '';
$result = FacebookApi::sendPostolo( $message, $tags,$places);
break;
Mine part is "postolo"
Then I found sendLink:
public static function sendLink($link, $message = '')
{
self::initialize();
$data = compact('link', 'message');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
If I foolishly copy this and adapts it to my needs is something like:
public static function sendPostolo($link, $message = '',$tags='',$places='')
{
self::initialize();
$data = compact( 'tags','message','places');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
But at the end the method $fb->post() not works as espect to me, and just publishs the first data of my array $data = compact( 'tags','message','places'); so in that case 'tags' and not as tags but predictably as plain text...
this is post() on fb package:
public function post($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
{
return $this->sendRequest(
'POST',
$endpoint,
$params,
$accessToken,
$eTag,
$graphVersion
);
}

How do I split my HABTM tags?

I want to take a field in the add form of the Post, explode it at the spaces, and save each word as a Tag, which HasAndBelongsToMany Post. So, for each unrecognized tag, it will create a new one, but if the Tag already exists, it will only create a new reference in the posts_tags tables. I've tried using saveAll, saveAssociated, and few foreach hacks, and I am not exactly sure where it went wrong, but I cannot figure out how to save the associate data. Any sort of outline of how to get the tag data from the form to the database would be appreciated.
//in model
public function parseTags($data) {
$str = $data['Tag'][0]['title'];
$tags = explode('',$str);
for ($i=0; $i<count($tags); $i++) {
$data['Tag'][$i]['title'] = $tags[$i];
}
return $data;
}
//in view
echo $this->Form->input('Tag.0.title',array('label'=>'Tags'));
//in controller
public function add() {
if ($this->request->is('post')) {
$this->Question->create();
$this->request->data['Question']['user_id'] = $this->Auth->user('id');
$this->request->data = $this->Question->parseTags($this->request->data);
if ($this->Question->saveAll($this->request->data)) {
$this->Session->setFlash(__('The question has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.'));
}
}
$users = $this->Question->User->find('list');
$this->set(compact('users'));
}
You must first check if Tag saved before or not, if not saved, You can save it. So before you save your model ,all of your tags is saved before.
something like this:
/* $tag_list is exploded tags*/
foreach ($tag_list as $tag) {
$res = $this->Tag->find('first', array('conditions' => array('Tag.name' => $tag)));
if ($res != array()) {
$tag_info[] = $res['Tag']['id'];
} else {
$this->Tag->create();
$this->Tag->save(array('Tag.name' => $tag));
$tag_info[] = sprintf($this->Tag->getLastInsertID());
}
}
$this->model->data['Tag']['Tag'] = $tag_info;

Magento saving multiselect in controller?

$fieldset->addField('brand_id', 'multiselect', array(
'label' => Mage::helper('expertbrand')->__('Merk:'),
'name' => 'brand_id[]',
'values' => $aOptionsMerk,
));
I have this multiselect box with some 600 options. I would like to know how to save this in the controller?
I have tried everything and worked on this problem for 3 days now. Also on the internet I cannot find a correct anwser to this problem. Hoping someone here is able to help me because I'd really like to know!
My controller code:
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('filename');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
// Set the file upload mode
// false -> get the file directly in the specified folder
// true -> get the file in the product like folders
// (file.jpg will go in something like /media/f/i/file.jpg)
$uploader->setFilesDispersion(false);
// We set media as the upload dir
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['filename']['name'] );
} catch (Exception $e) {
}
//this way the name is saved in DB
$data['filename'] = $_FILES['filename']['name'];
}
/*
$brands=$data['brand_id'];
$t=count($brands);
$inhoud="";
$i=1;
foreach ($brands as $brand){
if ($t == $i){
$inhoud.=$brand;
} else {
$inhoud.=$brand." , ";
}
$i++;
}
//echo $inhoud;
// $br=array('brand_id');
$br=$inhoud;
$data['brand_id']=$br;
*/
//hier moet de loop komen
$id= $data['expert_id'];
$db1 = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $db1->query("SELECT name FROM expert where expert_id=$id");
$rows = $result->fetch(PDO::FETCH_ASSOC);
$data['name']=$rows['name'];
//$data['brand_id']=$_POST['brand_id'];
$model = Mage::getModel('expertbrand/expertbrand');
$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();
//hier is het einde van de loop..
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('expertbrand')->__('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('expertbrand')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
How should I save the optionsArray that is sent through the $_POST? Thanks in advance.
Add this to your saveAction in your Controller to convert the data to a string:
foreach ($data as $key => $value)
{
if (is_array($value))
{
$data[$key] = implode(',',$this->getRequest()->getParam($key));
}
}
To start:
You've declared the input as "brand_id[]", so you are looking for $data['brand_id'], which should be an array. In the commented code, you appear to use that data, but your current code only looks for $data['expert_id'], which doesn't seem to be the same thing.
Even if you change that line to $data['brand_id'], keep in mind that it is an array, so you'll need to be cognizant of that in queries.
You've got a bunch of logic in the controller that doesn't belong there. In an MVC app (of which Magento is a canonical example), most of that SQL logic (as well as the createdtime/updatedtime stuff) belongs in the model (probably expertbrand/expertbrand).
It's not clear how you defined expertbrand/expertbrand. Is this an EAV model? What is its definition? This is most likely the root of your problem, as you have to tell Magento about your EAV model for it to save like that.
Please fix those things (and clarify on the model code) and we can debug further if necessary.
Thanks,
Joe
its clear to me that the data is sent in an array. In order to fix that i created function that rewrites the array.
$brands=$data['brand_id'];
$t=count($brands);
$inhoud="";
$i=1;
foreach ($brands as $brand){
if ($t == $i){
$inhoud.=$brand;
}
else {
$inhoud.=$brand." , ";
}
$i++;
}
//echo $inhoud;
// $br=array('brand_id');
$br=$inhoud;
$data['brand_id']=$br;
the DATA saved in the database would look something like this:
104 , 106 , 107 , 108
i do this cos i read somewhere that this was necessary to do so.
How ever when i open my edit field the only one which shows :
selected="selected" is the brand with the value 108 (the last one)
this is a problem because i need all 4 of them to be shown as selected.
Has this something to do in the way how i save this data ...not sure if the data should be saved as an array to show all selected="selected" fields in the edit
by the way the expert_id is something else and not an issue here i know the sql should be somewhere else but since i am still learning magento this was a quick a dirty method to fix a problem i had earlier...
all i want to know is how to store the array to show all values as an selected="selected" field in the edit form...Txs....
Ok i fixed the problem the data should be saved as
106,108,114,99
now everything is selected in the edit field strange nothing of this is to be found here on the internet hopefully it will be helpfull to other people dealing with the same problem

Resources