Before you can allow a user to manage their profile photo in your front-end profile edit form, be sure to update your form tag with the enctype="multipart/form-data"
parameter:
<form method="post" enctype="multipart/form-data">
You can access a users profile photo using the currentUser
global and fallback to a different image like so:
{% if currentUser.photoUrl %}
<img src="{{ currentUser.photoUrl }}" />
{% else %}
<img src="/assets/images/fallback.gif" />
{% endif %}
The upload and manage part becomes a bit trickier. Setting up a basic use case is fairly straightforward but if you want to begin giving the user a better UI and more feedback as to the status of the uploaded image, you'll have to get into some css and javascript.
For example, when you delete a photo you might want to swap in the fallback image. When an image is uploaded, you may want to display the image instead of just the filename for the user. Before a user has uploaded an image, you probably don't want to display the delete button.
I'm not going to go into those items here, but here's one approach to get you started with the functionality:
{# Check to see if the user has a photo #}
{% if currentUser.photoUrl %}
{# If a photo exists, give the option to change the user photo #}
<input type="file" name="userPhoto" value="Change Photo">
{% else %}
{# If no photo exists, give the option to upload a new one #}
<input type="file" name="userPhoto" value="Upload">
{% endif %}
If you want to be more brief, you can do the same using a ternary operator:
<input type="file" name="userPhoto" value="{{ (currentUser.photoUrl ? 'Change Photo' : 'Upload') }}">
In both cases, at different points in the process, you may want to give the user an option to remove their photo. To delete a photo, you can pass any value to an input field called deleteUserPhoto
.
{# Setup a delete action (see javascript snippet below) #}
<a href="#" id="deleteUserPhotoAction">Delete</a>
{# Setup a hidden deleteUserPhoto field with no value #}
<input type="hidden" name="deleteUserPhoto" id="deleteUserPhotoInput" value="">
When a user clicks the delete button you want to update the deleteUserPhoto
input field to have a value. Any value works. Here's an example using jQuery:
(function() {
// Bind an action to the deleteUserPhotoAction click event
$("#deleteUserPhotoAction").on('click', function() {
// Add the value 'zap' to the deleteUserPhoto input
document.getElementById("deleteUserPhotoInput").value = 'zap';
});
})();