Drupal 8, add an image field from a BuildForm with preview - drupal-forms

I created a custom form from a buildForm function. In this form, I would like add an image field.
I can do that via this code :
$form['main']['image'] = array(
'#type' => 'text_format',
'#title' => t('image'),
'#default_value' => array(10),
);
I can upload and remove the image from my form. However, when I upload an image, I haven't this preview.
I mean, when I create a content via the Drupal UI. I can add a preconfigured "image" field. When I upload an image via this "image" field, I have a preview of the image.
And here, when I create the field element programmatically, I haven't a preview of the image when I upload her.
How use api Drupal for have the preview of the image when I upload her via my "image" field ?

So here is how I got my form to display the thumbnail image. What I basically did was take the code in ImageWidget::process, put it in a theme preprocessor and set the #theme property of the element to image_widget.
Your image element in your form class should look like this:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
**'#theme' => 'image_widget',**
**'#preview_image_style' => 'medium',**
'#upload_location' => 'public://profile-pictures',
'#required' => TRUE,
];
In your name_of_default_theme.theme file, you need the following:
function name_of_default_theme_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
The solution works well, but the image module is missing a class with the #FormElement annotation. That is why the element isn't rendered properly.

Can you try with managed_file type?
'#type' => 'managed_file'

First some clarifications, then some observations and then the code that worked for me.
Clarifications:
I am using Drupal 9, but the solution proposed below may work also
for Drupal 8.
By "default temporary directory" I mean the directory defined in the following settings
file
[DrupalrootDirectory]/sites/default/settings.php
using
$settings['file_temp_path'] = '/The/Absolute/Path/To/Your/Temporary/Directory';
or defined by your operating system and that you can check in the Drupal administration
menu:
[YourSiteWebAddress]/admin/config/media/file-system
When something is written inside square brackets [], like this, [DrupalrootDirectory], it means that you should replace it with the actual name in your system, Drupal installation or custom module/file, without the square brackets.
Observations:
No need to create apriory any directories inside the default
temporary directory. They will be created automatically.
When you click the Remove button (which appears automatically as soon you upload a file in your custom form), the image file and the thumbnail files are deleted from the default temporary directory.
It does not matter if you define your default temporary directory inside the default site location,
e.g.,
[DrupalrootDirectory]/sites/default/files
or outside it, for example,
[DrupalrootDirectory]/sites/other/files
In my case, I defined it to:
[DrupalrootDirectory]/sites/default/files/temp
No need to make changes to .htaccess (in Apache server) file inside the default temporary directory or
inside
[DrupalrootDirectory]/sites/default/files
Keep them as Drupal created them.
No need to change file rights to "777" inside the default temporary directory, "775" is enough.
Check that your Drupal installation is actually creating thumbnails for images uploaded using the
administration menu:
[YourSiteWebAddress]/admin/content/media
when using the "Add media" link
[YourSiteWebAddress]/media/add/image
No need to make any other changes inside Drupal settings
file
[DrupalrootDirectory]/sites/default/settings.php
The code that worked for me:
It is based in the code published above by "Je Suis Alrick". But his code was not working for me, neither I could not find in which part of his code the thumbnail image was actually created. In my search for it, this post helped
Generate programmatically image styles with Drupal 8
So, here is the final code:
In your custom module, in the custom form file, most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/src/Form/[NameOfYourCustomForm].php
you add the element to be used to upload the image file:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#required' => TRUE,
];
So far, the same as in the code of "Je Suis Alrick", except that I deleted the definition for '#upload_location', so the default temporary directory will be used avoiding security complaints.
The important part here is:
the definition of the '#theme', which may be any name, but in this case is 'image_widget';
and the definition of '#preview_image_style', which must be the machine name of one of the image styles defined in your Drupal installation, that you can check in your administration
menu
[YourSiteWebAddress]/admin/config/media/image-styles
For this case the style 'medium' will be used, which is one of the image styles created by default by Drupal.
Then, in the module file of your custom module, named [NameOfYourCustomModule].module and most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/
You will need to paste the following code:
<?php
use Drupal\image\Entity\ImageStyle;
function [NameOfYourCustomModule]_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['width']['#value']) && isset($element['height']['#value'])) {
$file_variables['width'] = $element['width']['#value'];
$file_variables['height'] = $element['height']['#value'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
You should note that at the end of the name of the function, the name of the theme 'image_widget' is included, which tells Drupal to process your form element using the defined above function: [NameOfYourCustomModule]_preprocess_image_widget
What have I added?
The line at the
top:
use Drupal\image\Entity\ImageStyle;
And the following four lines that actually create the image thumbnail inside the default temporary directory:
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
With the addition of these five lines I got it working!

Nice answer thx, only change I'd make is using Token for upload location, and Bytes for file upload size, although I guess it depends on the use case. Something like the below (stripped out most of the code for the sake of simplicity.
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\Utility\Token;
class SampleForm extends FormBase
{
protected $currentUser;
protected $token;
public function __construct(AccountProxyInterface $current_user, Token $token) {
$this->currentUser = $current_user;
$this->token = $token;
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('current_user'),
$container->get('token')
);
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['sample_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => file_upload_max_size() / pow(Bytes::KILOBYTE, 2) . 'M',
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#upload_location' => $this->token->replace('private://[date:custom:Y]-[date:custom:m]'),
'#required' => TRUE,
];
return $form;
}
}

Theme it to work on multiple file upload. From #Je Suis Alrick answer above.
function themename_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
foreach ($element['#files'] as $file) {
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'][] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}

Related

Returning user input after AJAX call in Drupal 7 hook_form_FORM_ID_alter

I am using the hook_form_FORM_ID_alter in Drupal 7 to create a custom form so that the user can enter and edit data which is then attached to a custom node type.
For a new node the default number of input boxes in a group is 10, this can then be added to in groups of 5. When the node is reloaded for editing the saved data is used to create the form with whatever number of inputs have been saved previously and also the ability to add more fields in the same manner as required.
I have managed to get both the initial version of the form and the editing version to work using the following code however when the 'add five' button is pressed and the AJAX called (in both cases), any values which have been entered without saving are removed.
<?php
/**
* Implements hook_form_FORM_ID_alter().
*/
function entries_form_form_entries_node_form_alter(&$form, &$form_state, $form_id) {
$node = $form['#node'];
// fieldset
$form["section"] = array(
'#type' => 'fieldset',
'#title'=> 'Section 1',
);
$form["section"]["termwrapper"] = array(
"#type" => 'container',
"#attributes" => array(
"id" => 'groupWrapper',
),
);
$form["section"]["termwrapper"]["terms"]["#tree"] = TRUE;
if(!isset($form_state['fired'])){
$form_state['terms'] = $node->entries_form['term'];
}
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#value' => $values,
);
}
$form['section']['addFive_button'] = array(
'#type' => 'submit',
'#value' => t('+5'),
'#submit' => array('entries_form_add_five_submit'),
'#ajax' => array(
'callback' => 'entries_form_commands_add_callback',
'wrapper' => 'groupWrapper',
),
'#prefix' => "<div class='clear'></div>",
);
dpm($form_state);
}
function entries_form_commands_add_callback($form, $form_state) {
return $form["section"]["termwrapper"];
}
function entries_form_add_five_submit($form, &$form_state){
$form_state['rebuild'] = TRUE;
$form_state['fired'] = 1;
$values = $form_state['values'];
$form_state['terms'] = $values['terms'];
$numterms = count($values['terms']);
$addfivearray = array_fill($numterms,5,'');
$form_state['terms'] = array_merge($values['terms'],$addfivearray);
}
/**
* Implements hook_node_submit().
*/
function entries_form_node_submit($node, $form, &$form_state) {
$values = $form_state['values'];
$node->entries_form['term'] = $values['term'];
}
/**
* Implements hook_node_prepare().
*/
function entries_form_node_prepare($node) {
if (empty($node->entries_form)){
$node->entries_form['term'] = array_fill(0, 10, '');
}
}
/**
* Implements hook_node_load().
*/
function entries_form_node_load($nodes, $types) {
if($types[0] == 'entries'){
$result = db_query('SELECT * FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)))->fetchAllAssoc('nid');
foreach ($nodes as &$node) {
$node->entries_form['term'] = json_decode($result[$node->nid]->term);
}
}
}
/**
* Implements hook_node_insert().
*/
function entries_form_node_insert($node) {
if (isset($node->entries_form)) {
db_insert('mytable')
->fields(array(
'nid' => $node->nid,
'term' => json_encode($node->entries_form['term']),
))
->execute();
}
}
How can I keep the values which have been typed in and retain the ajax functionality?
Any help or pointers much appreciated. This is my first dip into Drupal so I'm sure there is something which hopefully is quite obvious that I'm missing.
Ok, I think I finally have the answer.
Within the foreach that builds the form input boxes I had set '#value' => $values, when it seems that '#default_value' => $values, should have been set instead.
The updated section of the code that is now working for me is as follows
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#default_value' => $values,
);
}
Seems to be as simple as that. Hope this helps someone else.

How to change the name of an image that is generated by CodeIgniter Captcha?

I am using CodeIgniter Captcha Helper to generate captcha images for my website. It is working perfectly fine. But the only problem is that it generates a random name for the captcha image. How can I change the name of the image that is generated by CodeIgniter Captcha Helper? I have used the following code for generating my captcha.
$this->load->helper('captcha');
$keyword = $this->generate_random_keyword();
$vals = array(
'word' => $keyword,
'img_path' => './captcha/',
'img_url' => base_url() . '/captcha/',
'img_width' => '150',
'img_height' => '35',
'border' => 0,
'font_path' => './fonts/texb.ttf',
'expiration' => 3600
);
$captcha = create_captcha($vals);
CodeIgniter/system/helpers/captcha_helper.php line 231
$img_name = $now.'.jpg';
You can modify it directly (probably not a good idea as updates may overwrite). Or you could create your own helper by copying the original, modifying and putting it in application/helpers.
If you want to customize the name via parameter, something like this should do it:
// line 42
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '', $captcha_filename = '')
then
// line 231
if ($captcha_filename != '')
{
$img_name = $captcha_filename.'.jpg';
}
else
{
$img_name = $now.'.jpg';
}
Be aware, though, that this example may overwrite existing captcha's in the same directory if you set $captcha_filename.
So, copy captcha_helper.php into application/helpers, make the changes on line 42 and 231 (or just 231), save, and you should be good.

codeigniter update image not reuploading

I'm running over this problem which I was trying for the last few hours
I'm having an image upload with some details to store in db.
I store the details and image path, working like a charm. Now comes the edit part.
I'm trying to check if the input file is empty, if so update just the details, else delete the image and reupload new image. The problem is this:
If the input file is empty it updates everything no problem, if is not empty it is updating the details, but the image is the same, doesn't get deleted or reuploaded.
here is the code
$image_input = $this->input->post('image');
if(isset($image_input) && !empty($image_input))
{
$this->db->where('id', $id);
$img = $this->db->get('menus_category', 1);
if($img->num_rows() > 0)
{
$row = $img->row();
$original_image = $row->image;
$desktop_image = $row->desk_img;
$mobile_image = $row->mob_img;
$thumb_image = $row->thumb;
$unlink_image = unlink('./uploads/menus/' . $original_image);
$unlink_desk = unlink('./uploads/menus/desk/' . $desktop_image);
$unlink_mob = unlink('./uploads/menus/mobile/' . $mobile_image);
$unlink_thumb = unlink('./uploads/menus/thumbs/' . $thumb_image);
if($unlink_desk && $unlink_image && $unlink_mob && $unlink_thumb)
{
$config = array(
'upload_path' => './uploads/menus',
'allowed_types' => 'gif|jpg|jpeg|png',
'max_size' => '15000'
);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$image_data = $this->upload->data();
$this->load->library('image_lib');
// thumb resize
$thumbnail = 'thumb_' . $image_data['file_name'];
$thumb = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'thumbs/' . $thumbnail,
'maintain_ratio' => TRUE,
'width' => '90',
'height' => '90'
);
$this->image_lib->initialize($thumb);
$this->image_lib->resize();
$this->image_lib->clear();
// mobile resize
$mob = 'mob_' . $image_data['file_name'];
$thumb_mob = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'mobile/' . $mob,
'maintain_ratio' => FALSE,
'width' => '290',
'height' => '83'
);
$this->image_lib->initialize($thumb_mob);
$this->image_lib->resize();
$this->image_lib->clear();
// desktop resize
$desk = 'desk_' . $image_data['file_name'];
$thumb_desk = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'desk/' . $desk,
'maintain_ratio' => FALSE,
'width' => '700',
'height' => '200'
);
$this->image_lib->initialize($thumb_desk);
$this->image_lib->resize();
$this->image_lib->clear();
// insert path and details to database
$data = array(
'title' => $input['title'],
'slug' => $this->_check_slug($input['title']),
'description' => $input['description'],
'image' => $image_data['file_name'],
'desk_img' => $desk,
'mob_img' => $mob,
'thumb' => $thumbnail
);
$this->db->where('id', $id);
return $this->db->update('menus_category', $data);
}
else
{
echo $this->image_lib->display_errors();
}
}
}
}
else
{
$data2 = array(
'title' => $input['title'],
'slug' => $this->_check_slug($input['slug']),
'description' => $input['description']
);
$this->db->where('id', $id);
return $this->db->update('menus_category', $data2);
}
Note: the else statement works fine, but the first if the problem. Now I changed the if to just if(isset($image_input)) ... and if file input is not empty is reuploading the picture and updating the details fine, but if I update only the details with no picture, it is deleting the picture that is already uploaded and is not updating. (I think this is the problem but I can't figure out how to fix it).
If you will to give me some help or to put me on right direction I will be thankful.
Thanks guys
First, this would be a comment asking a question, but I don't have enough reputation do add one just yet...
If you could post your HTML form, that would be helpful, but without that...
1) I assume the form you are submitting has enctype="multipart/form-data" in the opening tag.
2) On line 2 of your code here, $this->input->post('image'), is 'image' from a form input of type file? If so, your statement won't work as 'image' is part of the $_FILES array and not $_POST anymore. Meaning when you go to check it, it is always going to be empty (or non-existent).
To verify that your form is submitting the way you think it is, do this just before the first line in the code you have in your post:
var_dump($_POST);
var_dump($_FILES);
exit; // don't let anything run after the dumps.
let me know if that puts you in the right direction or not.

Symfony 1.4 sfWidgetFormInputFileEditable customization

I am using the sfWidgetFormInputFileEditable widget for my users to upload images.
I would like to see if there's a way to alter the way it works be default. When a user is adding a "new" object, I would like for it to show a generic picture, and when it's an "edit" then it can show the existing pic. I tried writing a PHP conditional statement but that's not working for me because when it's a "new" item I can't pull the parameter "getPicture1" because it doesn't exist.
My widget currently:
$this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
'label' => ' ',
'file_src' => '/uploads/car/'.$this->getObject()->getPicture1(),
'is_image' => true,
'edit_mode' => true,
'template' => '<div>%file%<br />%input%</div>',
));
You have two options (the second one is more easy).
First option: create your own sfWidgetFormInputFileEditable and extends the original.
In a file lib/widget/myWidgetFormInputFileEditable.class.php:
class myWidgetFormInputFileEditable extends sfWidgetFormInputFileEditable
{
protected function getFileAsTag($attributes)
{
if ($this->getOption('is_image'))
{
if (false !== $src = $this->getOption('file_src'))
{
// check if the given src is empty of image (like check if it has a .jpg at the end)
if ('/uploads/car/' === $src)
{
$src = '/uploads/car/default_image.jpg';
}
$this->renderTag('img', array_merge(array('src' => $src), $attributes))
}
}
else
{
return $this->getOption('file_src');
}
}
}
Then you need to call it:
$this->widgetSchema['picture1'] = new myWidgetFormInputFileEditable(array(
'label' => ' ',
'file_src' => '/uploads/car/'.$this->getObject()->getPicture1(),
'is_image' => true,
'edit_mode' => true,
'template' => '<div>%file%<br />%input%</div>',
));
Second option: check if the object is new then use the default image.
$file_src = $this->getObject()->getPicture1();
if ($this->getObject()->isNew())
{
$file_src = 'default_image.jpg';
}
$this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
'label' => ' ',
'file_src' => '/uploads/car/'.$file_src,
'is_image' => true,
'edit_mode' => true,
'template' => '<div>%file%<br />%input%</div>',
));

Magento custom image upload doesn't work

I need to create an image upload field for posts in Magento Blog Module (AW blog).
Therefore, each post needs to contain an image.
I edited the following files:
/home/clients/websites/w_gale/public_html/gale/app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php
added fieldset like this:
$fieldset->addField('fileinputname', 'image', array(
'label' => Mage::helper('blog')->__('Upload image'),
'required' => false,
'name' => 'fileinputname',
'required' => true,
'style' => 'height:100px;border:2px solid #999;',
));
on top of this file, in the right place, I defined form like this:
$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',
)
);
In Blogcontroller.php I added the following code, just bellow the if ($data = $this->getRequest()->getPost()) { line
if(isset($_FILES['fileinputname']['name']) && (file_exists($_FILES['fileinputname']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('fileinputname');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['fileinputname']['name']);
$data['imageurl'] = $_FILES['fileinputname']['name'];
} catch(Exception $e) {
}
} else {
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
$data['imageurl'] = '';
else
unset($data['fileinputname']);
}
However, the upload doesn't work. What am I doing wrong?
I added a special row in appropriate field in a database.
The frontend section displays the database value when I enter it manually.
Thanks
This code of method from data helper which uploads image. You need implement method getBaseDir() (which returns dir where you wish store your uploaded files) by yourself.
/**
* Upload image and return uploaded image file name or false
*
* #throws Mage_Core_Exception
* #param string $scope the request key for file
* #return bool|string
*/
public function uploadImage($scope)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addValidator('ImageSize', true, $this->_imageSize);
$adapter->addValidator('Size', true, $this->_maxFileSize);
if ($adapter->isUploaded($scope)) {
// validate image
if (!$adapter->isValid($scope)) {
Mage::throwException(Mage::helper('mycompany_mymodule')->__('Uploaded image is not valid'));
}
$upload = new Varien_File_Uploader($scope);
$upload->setAllowCreateFolders(true);
$upload->setAllowedExtensions(array('jpg', 'gif', 'png'));
$upload->setAllowRenameFiles(true);
$upload->setFilesDispersion(false);
if ($upload->save($this->getBaseDir())) {
return $upload->getUploadedFileName();
}
}
return false;
}
You're using the right code. I solved the problem by using the right MYSQL data type. When I changed the data type from 'text' to 'varchar(255)' it solved the problem
And ... make sure that you add the following code:
$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',
)
);
in /app/code/community/AW/Blog/Block/Manage/Blog/Edit/Form.php
NOT: app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php

Resources