Skip Navigation

[Resolved] cred_form_ajax_upload_validate API Hook, not working or incorrect

This support ticket is created 6 years, 4 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

This topic contains 19 replies, has 3 voices.

Last updated by tinaH 6 years, 3 months ago.

Assisted by: Beda.

Author
Posts
#597745

Link to documentation page: https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_ajax_upload_validate

I expected this to work, following your documentation:

if ($fields['wpcf-attachment']['field_data']['size'] > 1500000) {
            //set error message for for max file size
            $errors['wpcf-attachment'] = 'File is to big. Max allowed file size: 1.5MB';
}
if if ($fields['wpcf-attachment']['field_data']['type'] !== 'application/pdf') {
            //set error message for non-pdf
            $errors['wpcf-attachment'] = 'Wrong file type. Only PDF's are allowed.';
}

But, $fields returns array instead of value, unable to execute if-statement

Temporary solution, awaiting your feedback (get first item in array [0]):

if ($fields['wpcf-attachment']['field_data']['size'][0] > 1500000) {
            //set error message for for max file size
            $errors['wpcf-attachment'] = 'File is to big. Max allowed file size: 1.5MB';
}
if if ($fields['wpcf-attachment']['field_data']['type'][0] !== 'application/pdf') {
            //set error message for non-pdf
            $errors['wpcf-attachment'] = 'Wrong file type. Only PDF's are allowed.';
}
#598000

Update.
I am working with repeating fields. The previously posted temporary solution did only work for the first uploaded file.
If user uploads multiple files I needed to do a foreach to check each field.

I cannot see that this is documented.
(I have not tested the documented code for non-repeating fields)

new temporary solution, awaiting your feedback:

$array_size = $fields['wpcf-attachment']['field_data']['size'];
        foreach($array_size as $size) {
            if ($size > 1000000) {
                $errors['wpcf-attachment'] = 'Filen är för stor. Max tillåten storlek: 1MB. Din fil är: '.round($size/1000000, 2).'MB.';
            }
}
$array_type = $fields['wpcf-attachment']['field_data']['type'];
        foreach($array_type as $type) {
            if ($type !== 'application/pdf') {
                $errors['wpcf-attachment'] = 'Fel filformat. Endast PDF är tillåtet som bilaga. Din filtyp är: '.$type;
            }
}
#598401

I am sorry, Tina.

Yesterday I sent you a long reply, with the solution and what not, but the Site (wp-types) became unusable exactly when I submitted the reply and hence is lost.
It might be you got my reply by email, still, even if it's not here.

Let me also re-write it for clearance:

1. The first code example is wrong, it has an unescaped Apostrophe which will break the code:

if ($fields['wpcf-attachment']['field_data']['size'] > 1500000) {
            //set error message for for max file size
            $errors['wpcf-attachment'] = 'File is to big. Max allowed file size: 1.5MB';
}
if if ($fields['wpcf-attachment']['field_data']['type'] !== 'application/pdf') {
            //set error message for non-pdf
            $errors['wpcf-attachment'] = 'Wrong file type. Only PDF's are allowed.';//Escape with \!
}

2. The $fields is always an array.
Please see the documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_ajax_upload_validate
- fields. An associative array of field names to this structure:

3. For repeating fields you can use the same examples as outlined here:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

They also work for the AJAX validation.

//For repetitive fields, $fields is an array of values.
//For example, in order to set error message for the second instance of a repetitive field, you can use the following code:
$errors['my_repetitive_field'][1]='Error for second field';
//For File and Image fields, $fields array also contain the upload data.
//For example, you can use the following code:
$fields['wpcf-my_file']['file_data'] = array(
    'size' => uploaded file size,
    'name' => name of uploaded file,
    'type' => type of uploaded file,
    'error' => what error occurred during upload,
    'tmp_name' => location of temporary uploaded file
);

Please let me know if you find issues with it.

#600282

I tried to use the "cred_form_validate" hook instead, but I don't get any array data.
Can you see what is wrong.

function email_save_maxsize_validation($error_fields, $form_data)
{
    //field data are field values and errors
    list($fields,$errors)=$error_fields;
    
    //validate if specific form
    if ($form_data['id']==22263 || $form_data['id']==22257)
    {
        error_log('Form id ok');
        error_log('fields: '.print_r($fields));
        $array_size = $fields['wpcf-attachment']['file_data']['size'];
        error_log('array_size: '.print_r($array_size));
        $max_total = 0;
        foreach($array_size as $size) {
            $max_total = $max_total + $size;
            error_log('Storlek: '.$size);
        }
        if ($max_total > 3000000) {
            $errors['wpcf-attachment'] = 'Dina bilagors sammanlagda storlek överstiger tillåtet värde – 3MB. Dina bilagor är: '.round($max_total/1000000, 2).'MB tillsammans.';
        }
    }
    //return result
    return array($fields,$errors);
}
add_filter('cred_form_validate','email_save_maxsize_validation', 10, 2);

from error log:
[19-Dec-2017 15:46:51 UTC] Form id ok
[19-Dec-2017 15:46:51 UTC] fields: 1
[19-Dec-2017 15:46:51 UTC] array_size: 1

#600768

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello Tina, Beda is on vacation. This is Minesh here and I'll take care of this ticket and try to help you further. Hope this is OK.

I need access details with problem URL to debug issue on your install.

*** Please make a FULL BACKUP of your database and website.***
I would also eventually need to request temporary access (WP-Admin and FTP) to your site. Preferably to a test site where the problem has been replicated if possible in order to be of better help and check if some configurations might need to be changed.

I would additionally need your permission to de- and re-activate Plugins and the Theme, and to change configurations on the site. This is also a reason the backup is really important. If you agree to this, please use the form fields I have enabled below to provide temporary access details (wp-admin and FTP).

I have set the next reply to private which means only you and I have access to it.

#600795

I will gladly wait until Beda is back.

#600797

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Ok great to know. He will be in touch with you once he will get back from vacation.

#600945

Tina, I will be off until the 9th January.

If you are sure you want to wait, this is OK for me.

If you require attention earlier, please let Minesh know.

He is following this ticket (subscribed to it).

#601113

I'll wait. No problem.

#604705

Hello Tina, I am back.

I have analyzed this, for ease I used the non-ajax filter in the tests as well, since the DOC states that you can validate the Image Fields as well with it.

Simply the cred_form_validate() $fields array does not hold any 'file_data' value.
If you var_dump() $fields of your custom field, you will see that it is an array of:
value, name, type, repetitive.

That's it. There is no 'file_data' at all, as the Documented code sample wrongly states.

This does not depend on wether it is a repeating or single field.
In cred_form_validate there is definitely no 'file_data' at all.

To be honest I have no idea how you would be supposed to validate the size of that field, since this value is simply never present in any of the hooks.

The DOC says it shall be:

$fields['wpcf-my_field']['file_data'] = array(
    'size' => uploaded file size,
    'name' => name of uploaded file,
    'type' => type of uploaded file,
    'error' => what error occurred during upload,
    'tmp_name' => location of temporary uploaded file
);

Well, as a simple test shows, this is false.
What we have is:

$fields['wpcf-my_field'] = array(
  'value' => file_name,
  'name' => field_name,
  'type' => internal_cred_field_type,
  'repetitive' => if repetitive (0/1),
  'plugin_type' => from types?,
  'validation' => array (
                            'url2' => array (
                                           'active' => 1/0,
                                           'message' => 'Please enter a valid URL address pointing to the image file.' (length=60)
                                           'suppress_for_cred' => true
                                           )
                             )
)

That's all. I see no file_data at all.

I have reported this problem to the Developers.

The issue with the index you also see, is so far expected, since we have several repeating instances you get an array instead of a single value.
But, it does not work according what is documented.

I will ask the developers to fix this and also revise the documentation.

Right now I have no solution.

#605038

Glad to know it wasn't me ...
Can see other problems with the doc an outputted value:
Doc: 'name' => name of uploaded file
Output: 'name' => field_name

Apart form the other differences.

Awaiting feedback from developers.
I hope there will be a way to check/limit total size of all uploaded files in a form.

#605040

There is no direct way to check the size of ALL items.
Only single items can be counter-proofed.

You would need more elaborated custom code for that, for example, sum up all sizes and then compare that.

I will get back at you as soon we have an update on the reported issue.

#605709

I tested this and that is what I came up with:

1. To validate an upload that happens before the form is submitted (which is the case for file, image and featured image fields) you use cred_form_ajax_upload_validate()
2. For validation in the moment you hit "Submit", where you can also validate Uploaded data again, you do use cred_form_validate()
3. Based on this, and your information (you are trying to validate a repeating field), I tested this locally and it works just fine.

I have used this code:

add_filter('cred_form_ajax_upload_validate','my_validation',10,2);
function my_validation($error_fields, $form_data)
{
    //field data are field values and errors
    list($fields,$errors)=$error_fields;
    //validate if specific form
    if ($form_data['id']==5)
    {
        //check if wpcf-toolset-image is bigger than 1
        if ($fields['wpcf-toolset-image']['field_data']['size'] > 1)
        {

            //set error message for wpcf-toolset-image if bigger than 1

            $errors['wpcf-toolset-image']='Error for wpcf-toolset-image field';

        }
    }
    //return result
    return array($fields,$errors);
}

This will produce a Browser Pop up the moment you upload the image to the field (before you submit the form).
It will work no matter how many instances you upload.
It does not matter if you have a repeating field or a single field.

Does this work for you as well?

Now, that does not remove all other issues, present on the DOC, for which filed internal issues, but it explains how to use the code successfully.

Can you confirm this?

#607944

My current script works well for checking individual file size with cred_form_ajax_upload_validate
It is checking total sizes of all files on cred_form_validate that is the problem.

Do you mean that I should expand the cred_form_ajax_upload_validate function?

#607945

Well, on upload, you should use the Ajax hook, because all the others act only on PHP (means when the form is submitted)

I don't think you should use cred_form_ajax_upload_validate as shown here:
https://toolset.com/forums/topic/cred_form_ajax_upload_validate-api-hook-not-working-or-incorrect/#post-605709

That is how you should check upon sizes of things when they get added to the form.
If you do that later, it is as well somewhat annoying for the user, as he/she counted with the fact to have done all right.
If you validated on upload moment, this is smoother, I believe.

What is the reason you hook into the later validation related to uploads?

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.