Skip to content

Instantly share code, notes, and snippets.

@Qubadi
Last active April 29, 2024 13:45
Show Gist options
  • Save Qubadi/48174b21a5a28e93da7737835e31cccf to your computer and use it in GitHub Desktop.
Save Qubadi/48174b21a5a28e93da7737835e31cccf to your computer and use it in GitHub Desktop.
Custom code for JetFormBuilder, designed to allow users to crop images.
UPDATED :
A new functionality for generating unique filenames for each cropped image
1. I've developed a new custom code for JetFormBuilder, designed to allow users to crop images.
I'm excited to share it with the group, making it accessible to most members here.
2. To begin, you'll need to create four fields: two media fields and two hidden fields. It's convenient to use the same
field names across these, so there's no need to modify the custom code.
3. An important aspect I didn’t cover in the video is setting the media field as the post thumbnail and configuring
the gallery field as a Meta field. This is done in the 'Post Submit Actions' under 'Insert/Update Post' in the FIELDS MAP section.
4. I have included CSS custom code in the provided link to help you style and customize the media field
5. Lastly, it’s crucial to enable CSRF protection for enhanced security.
If you want to see the video, visit the Crocoblock community group in Facebook.
CSS code:
/* Style and customize the media field */
.jet-form-builder__field-wrap.jet-form-builder-file-upload {
border-radius: 10px !important;
border-style: dashed !important;
border-width: 2px !important;
border-color: #69727d !important;
padding: 10px !important;
}
Custom code ( PHP snippet, all in one )
function enqueue_cropperjs_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('cropperjs', 'https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.9/cropper.min.js', array('jquery'), '1.5.9', true);
wp_enqueue_style('cropperjs-css', 'https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.9/cropper.min.css', array(), '1.5.9', 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_cropperjs_scripts');
function add_custom_cropperjs_javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var croppers = {};
var galleryCroppers = [];
var maxGalleryFiles = 2; // Maximum files allowed for gallery_field
var maxMediaFiles = 1; // Maximum files allowed for media_field_upload
function generateUniqueFilename(prefix) {
var timestamp = new Date().getTime();
var randomNum = Math.floor(Math.random() * 1000);
return prefix + '_' + timestamp + '_' + randomNum + '.jpg';
}
function setupCropper(fieldId, previewIdBase, buttonName) {
$('#' + fieldId).change(function(event) {
var files = event.target.files;
var fileCount = (fieldId === 'gallery_field') ? galleryCroppers.length : (croppers[fieldId] ? 1 : 0);
if ((fieldId === 'gallery_field' && fileCount + files.length > maxGalleryFiles) ||
(fieldId === 'media_field_upload' && fileCount + files.length > maxMediaFiles)) {
alert('You can only upload a maximum of ' + (fieldId === 'gallery_field' ? maxGalleryFiles : maxMediaFiles) + ' image(s).');
this.value = ''; // Clear the selected files
return; // Stop further execution
}
var imageContainer = $('#' + fieldId).siblings('.image-container');
if (imageContainer.length === 0) {
imageContainer = $('<div class="image-container"></div>'); // Create a container for all images
$('#' + fieldId).after(imageContainer); // Append the container after the input field
}
$.each(files, function(index, file) {
if (!file.type.match('image.*')) {
alert('Invalid file type. Please select an image.');
return true;
}
var fileReader = new FileReader();
var previewId = previewIdBase + fileCount + index;
fileReader.onload = function(e) {
var imagePreview = $('<img id="' + previewId + '" class="gallery-image">');
imagePreview.attr('src', e.target.result);
var imagePreviewContainer = $('<div class="gallery-image-container"></div>');
imagePreviewContainer.append(imagePreview);
imageContainer.append(imagePreviewContainer);
imagePreview.show();
if (fieldId === 'gallery_field') {
galleryCroppers.push(new Cropper(imagePreview[0], {
aspectRatio: 600 / 400,
viewMode: 1
}));
} else if (fieldId === 'media_field_upload') {
if (croppers[fieldId]) {
croppers[fieldId].destroy();
}
croppers[fieldId] = new Cropper(imagePreview[0], {
aspectRatio: 1,
viewMode: 1
});
}
};
fileReader.readAsDataURL(file);
});
$('input[name="' + buttonName + '"]').attr('type', 'button').val('Crop Images').show();
});
}
setupCropper('media_field_upload', 'mediaImagePreview', 'crop_button');
setupCropper('gallery_field', 'galleryImagePreview', 'crop_button_gallery');
$(document).on('click', 'input[name="crop_button"]', function() {
if (croppers['media_field_upload']) {
croppers['media_field_upload'].getCroppedCanvas({
width: 300,
height: 300
}).toBlob(function(blob) {
var uniqueFilename = generateUniqueFilename('croppedImage');
var newFile = new File([blob], uniqueFilename, {type: 'image/jpeg'});
var dataTransfer = new DataTransfer();
dataTransfer.items.add(newFile);
$('#media_field_upload')[0].files = dataTransfer.files;
}, 'image/jpeg');
}
$(this).hide();
});
$(document).on('click', 'input[name="crop_button_gallery"]', function() {
var dataTransfer = new DataTransfer();
$.each(galleryCroppers, function(index, cropper) {
if (cropper) {
cropper.getCroppedCanvas({
width: 600,
height: 400
}).toBlob(function(blob) {
var uniqueFilename = generateUniqueFilename('croppedGalleryImage_' + index);
var newFile = new File([blob], uniqueFilename, {type: 'image/jpeg'});
dataTransfer.items.add(newFile);
if (index === galleryCroppers.length - 1) {
$('#gallery_field')[0].files = dataTransfer.files;
}
}, 'image/jpeg');
}
});
$(this).hide();
});
});
</script>
<?php
}
add_action('wp_footer', 'add_custom_cropperjs_javascript');
@ShannaKae
Copy link

Thank you, testing it out now!

@imanharandi
Copy link

Thank you for sharing this good tutorial with us
I tried it and it was great
Is it possible to do something so that after clicking the Crop Images button, the cropped image will be displayed in a small format and not in a large format?

@Qubadi
Copy link
Author

Qubadi commented Jan 25, 2024

Thank you, testing it out now!

Thank you for sharing this good tutorial with us
I tried it and it was great
Is it possible to do something so that after clicking the Crop Images button, the cropped image will be displayed in a small format and not in a large format?

Hello, If u mean the size of cropped image, yes its possible, u can change the cropped size direct from the code. U will find it there, if u need any help contant me again, and tell me what size u want so i can help.

@imanharandi
Copy link

imanharandi commented Jan 28, 2024

Hello
Thank you for your answer
What I mean is, is it possible to hide the box editor that I marked in red by pressing the green button, that is, after selecting the dimensions and cutting the large box, it will be hidden.
https://i.postimg.cc/c42qHM7t/Screenshot-2024-01-28-154956.png

@Qubadi
Copy link
Author

Qubadi commented Jan 28, 2024

Hello Thank you for your answer What I mean is, is it possible to hide the box editor that I marked in red by pressing the green button, that is, after selecting the dimensions and cutting the large box, it will be hidden. https://i.postimg.cc/c42qHM7t/Screenshot-2024-01-28-154956.png

Hello again

Yes its possible and i have allready added it.
Watch this video please:
https://gemoo.com/tools/upload-video/share/610375750859382784?codeId=vzx32grLXg0rz&card=610375746778324992

@liranop
Copy link

liranop commented Feb 15, 2024

Hi Qubadi!
Very useful code! I really need that feature.
But I find it needs two more critical adjustments:
1- It's important that the Cropper will one the new photos being added and NOT also the preset photos. It destroy already cropped images.
2-In order to re-crop an image, it will be good to have icon on the preview image (like the remove icon) that will trigger cropper ONLY on that image.

For 2, I started with this:
// Add edit icon to already added files $('.jet-form-builder-file-upload__file').each(function(index, element) { var fileName = $(this).find('.jet-form-builder-file-upload__value').val().split('/').pop(); var editIcon = $('<div class="edit-icon" data-file-name="' + fileName + '"><i class="fa fa-pencil"></i></div>'); $(this).append(editIcon); });

But i got no idea how to make the edit icon to trigger the cropper only on the relevant image.

Hope you can help with this.

@Qubadi
Copy link
Author

Qubadi commented Feb 16, 2024

liranop

Hello

I will add your request to my list. Thank u

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment