Kohana 3.2 Upload Exception - kohana

I'm using Kohana 3.2.
I have a category form with two upload fields: one is image, and one is banner. In my controller i got:
try{
$model_category->save();
}catch(ORM_Validation_Exception $e){
$errors = $e->errors('forms');
//echo Debug::vars($errors);
}catch (Exception $e){
$upload_errors = $e->getMessage();
}
Rules for my images in the model:
'photo' => array(
array('Upload::valid'),
array('Upload::type', array(array(':value'),array('jpeg', 'jpg', 'png', 'gif'))),
array('Upload::size', array(array(':value'), array('500000')))
),
'banner' => array(
//array(array($this, 'validate_photo'), array(':validation', ':field', ':value', 500, 100)),
array('Upload::valid'),
array('Upload::type', array(array(':value'),array('jpeg', 'jpg', 'png', 'gif'))),
array('Upload::size', array(array(':value'), array('5000000')))
),
I got into such problem: if i leave a required field, for example "name" and upload an txt file to force both exceptions occur, it can only catch the ORM_Validation_Exception. So my question is how to merge the two error array. And very important, how can i know if it's an exeception for the image field or the banner field.
I have been trying over for days but end up with nothing. Please help me out!

You can use Validation class to validate your uploads and then if validation is ok - save the model.
Something like:
$validate_image = Validation::factory($_FILES);
$validate_image->rule($name, 'Upload::valid');
$validate_image->rule($name, 'Upload::type', array($_FILES['image'], array('jpeg', 'jpg', 'png', 'gif')));
$validate_image->rule($name, 'Upload::size', array($_FILES[$name], '500000'));
$validate_banner = Validation::factory($_FILES);
$validate_banner->rule($name, 'Upload::valid');
$validate_banner->rule($name, 'Upload::type', array($_FILES[$name], array('jpeg', 'jpg', 'png', 'gif')));
$validate_banner->rule($name, 'Upload::size', array($_FILES[$name], '500000'));
if ($validate_image->check() && $validate_banner->check()) {
$model_category->save();
}

Related

How to crop image after upload Cloudinary?

How i can to crop image after upload and send edited response ulr to frontent?
I will be grateful for the answer
MY CODE:
const stream = cloudinary.uploader.upload_stream(
{
folder,
},
(error: UploadApiErrorResponse | undefined, result: UploadApiResponse | undefined): void => {
console.log(error, result)
if (result) {
resolve({
url: result.url,
size: Math.round(result.bytes / 1024),
height: result.height,
width: result.width,
})
} else {
reject(error)
}
}
)
streamifier.createReadStream(buffer).pipe(stream)
The most common method of integrating Cloudinary is that you upload the original file to your Cloudinary account and store the Upload API response to your database which contains the details for the image: https://cloudinary.com/documentation/image_upload_api_reference#sample_response
If you don't want to store the entire response, you should store at least the fields needed to create a URL for that image later: https://cloudinary.com/documentation/image_transformations#transformation_url_structure
(Which are public_id, resource_type, type, format, and timestamp) though strictly speaking, most of those are optional if your assets are images of type 'upload' - certainly you need the public_id though.
Then, in your frontend code, when adding the image to your page or to your application, you add transformation parameters when building the URL, asking that the image is returned with transformations applied to match it to where/how you're using the image.
A common option is to set the width and height to exactly match the image tag or image view, then apply automatic cropping if the aspect ratio of the original doesn't match, with the crop selection being automatic: https://cloudinary.com/documentation/resizing_and_cropping
A Javascript example to add those parameters, if the image should be 500x500 is:
cloudinary.url( public_id,
{
resource_type: 'image', //these are the defaults and can be ommitted
type: 'upload', //these are the defaults and can be ommitted
height: 500,
width: 500,
crop: 'lfill', // try to fill the requested width and height without scaling up, crop if needed
gravity: 'auto', // select which area to keep automatically
fetch_format: 'auto',
quality: 'auto',
format: 'jpg', // sets the file extension on the URL, and will convert to that format if needed, and no fetch_format was set to override that
});
The resulting URL will be something like: http://res.cloudinary.com/demo/image/upload/c_lfill,f_auto,g_auto,h_500,q_auto,w_500/sample.jpg

Adding WooCommerce Attribute via PHP code

I could see a lots of question on adding woocommerce product attribute. But doing so, I could see those added attributes in this screen
wp-admin/edit.php?post_type=product&page=product_attributes
My question is how can we add the attributes via PHP code to so that it appears in this above specified woocommerce attribute screen ? My intention is to make these attributes visible under 'Layered Navs' widget to filter out.
Following code will create the attribute programmatically which will be visible on the product_attributes page in the backend.
global $wpdb;
$insert = $wpdb->insert(
$wpdb->prefix . 'woocommerce_attribute_taxonomies',
array(
'attribute_label' => 'name',
'attribute_name' => 'slug',
'attribute_type' => 'type',
'attribute_orderby' => 'order_by',
'attribute_public' => 1
),
array( '%s', '%s', '%s', '%s', '%d' )
);
if ( is_wp_error( $insert ) ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 );
}
// Clear transients
delete_transient( 'wc_attribute_taxonomies' );
Change name, slug etc with the relevant values.

Yii CGrid View view all after search

I need some help, I've been figuring this for almost an hour and still can't find a way to fix this.
I have a search form to filter data from my CGridView, and I also need a button to view all the records after I finish using search, but I can't figure how to do it. Here's my code for jquery refresh button:
Yii::app()->clientScript->registerScript('initRefresh',<<<JS
$('#refresh-button').on('click',function() {
$('#app-asset-categories-grid').yiiGridView('update');
return false;
});
JS
,CClientScript::POS_READY);
Here's my code for jquery search form:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#app-asset-categories-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
And finally, my grid:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'id'=>'app-asset-categories-grid',
'columns' => array(
'category_id',
'label',
'description',
'add_date',
'modification_date',
array(
'name'=>'Status',
'filter'=>array('1'=>'Active', '0'=>'Inactive'),
'value'=>'($data->status=="1")?"Active":"Inactive"'
),
array(
'name'=>'Deletion Status',
'filter'=>array('1'=>'Deactivate','0'=>'Active'),
'value'=>'($data->deletion_status=="1")?"Deactivated":"Activated"'
),
array(
'class'=>'CButtonColumn',
),
),
));
I just wanted a refresh button to display all the data again after I use my search form. I need your help guys, thanks.
You need to handle update action in model and set pagination parameter false. An example how to do it:
Add hidden field in search form _search.php
<?php echo CHtml::hiddenField('show_all', 0, array("id"=>"show_all")); ?>
Then handle it in model's search() function (your grid uses it to get data)
like this:
$criteria=new CDbCriteria;
// some criterias
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination' => (isset($_GET["show_all"]) && $_GET["show_all"])?false:array(), // add this line
));
Then set update hidden field when you need it.
$('#refresh-button').on('click',function() {
$('#show_all').val(1); // set it to show all
$('#app-asset-categories-grid').yiiGridView('update');
$('#show_all').val(0); // set to 0 for searching with pagination
return false;
});
Thats it.

Drupal 6 File Handling

I am handling file upload field in a form using Drupal 6 form APIs. The file field is marked as required.
I am doing all the right steps in order to save and rename files in proper locations.
upload form
$form = array();
....
$form['image'] = array(
'#type' => 'file',
'#title' => t('Upload photo'),
'#size' => 30,
'#required' => TRUE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
...
form validate handler
$image_field = 'image';
if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$image_field])) {
$file = file_save_upload($image_field);
if (!$file) {
form_set_error($image_field, t('Error uploading file'));
return;
}
$files_dir = file_directory_path();
$contest_dir = 'contest';
if(!file_exists($files_dir . '/' . $contest_dir) || !is_dir($files_dir . '/' . $contest_dir))
mkdir($files_dir . '/' . $contest_dir);
//HOW TO PASS $file OBJECT TO SUBMIT HANDLER
$form_state['values'][$image_field] = $file;
file_move($form_state['values'][$image_field], $files_dir."/" . $contest_dir . "/contest-". $values['email']. "-" . $file->filename);
}
else {
form_set_error($image_field, 'Error uploading file.');
return;
}
On submiting form
Form always reports an error Upload photo field is required. although files are getting uploaded. How to deal with this issue?
How to pass file information to submit handler?
your handler is wrong. You never should touch $_FILES or $_POST variables in drupal, instead you should only use the drupal tools. Said that, the implementation you should is like that:
function my_form_handler(&$form,&$form_state){/** VALIDATION FILE * */
$extensions = 'jpeg jpg gif tiff';
$size_limit = file_upload_max_size();
$validators = array(
'my_file_validate_extensions' => array($extensions),
'my_file_validate_size' => array($size_limit),
);
$dest = file_directory_path();
if ($file = file_save_upload('image', $validators, $dest)) {
//at this point your file is uploaded, moved in the files folder and saved in the DB table files
}
}
I think you'll want to use the filefield module and append it to a form, as described in:
Drupal Imagfield/Filefield in custom form
The question has a link to the solution:
http://sysadminsjourney.com/content/2010/01/26/display-cck-filefield-or-imagefield-upload-widget-your-own-custom-form
From the Drupal 6 Form API docs:
"Note: the #required property is not supported (setting it to true will always cause a validation error). Instead, you may want to use your own validation function to do checks on the $_FILES array with #required set to false. You will also have to add your own required asterisk if you would like one."
Old post, but I'm looking for something similar and figured I add that.

How to add custom blocks in drupal?

I have a simple module which will return a form , but now i have added this to a menu like
admin/settings/
But i want this form in another page ,so i added a hook_block() , my module showed up in the blocks page and i added it to be seen by all in all pages in content area but i dont get that form ? where did i go wrong ? I am new to drupal any help plz
function emp_form_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('New Block');
$blocks[0]['cache'] = BLOCK_NO_CACHE;
return $blocks;
}
}
i am using drupal 6
You should also implement the view op, like this:
case 'view':
return array(
'subject' => t('My awesome form'),
'content' => drupal_get_form('my_awesome_form'),
);
break;

Resources