Implement support for uploading multiple images, move the dashboard columns for a given table to its model, and clean a bunch of things up

This commit is contained in:
Kevin MacMartin 2018-01-11 01:13:58 -05:00
parent d02aa7e923
commit 5613c72d0c
7 changed files with 86 additions and 65 deletions

View file

@ -2,6 +2,7 @@
use App\Http\Requests; use App\Http\Requests;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use File;
use Image; use Image;
use Excel; use Excel;
@ -41,12 +42,7 @@ class DashboardController extends Controller {
'heading' => 'Contact Form Submissions', 'heading' => 'Contact Form Submissions',
'model' => 'contact', 'model' => 'contact',
'rows' => Contact::getContactSubmissions(), 'rows' => Contact::getContactSubmissions(),
'cols' => [ 'cols' => Contact::$dashboard_columns
[ 'Date', 'created_at' ],
[ 'Name', 'name' ],
[ 'Email', 'email' ],
[ 'Message', 'message' ]
]
]); ]);
} }
@ -56,11 +52,7 @@ class DashboardController extends Controller {
'heading' => 'Subscriptions', 'heading' => 'Subscriptions',
'model' => 'subscriptions', 'model' => 'subscriptions',
'rows' => Subscriptions::getSubscriptions(), 'rows' => Subscriptions::getSubscriptions(),
'cols' => [ 'cols' => Subscriptions::$dashboard_columns
[ 'Date', 'created_at' ],
[ 'Email', 'email' ],
[ 'Name', 'name' ]
]
]); ]);
} }
@ -104,9 +96,10 @@ class DashboardController extends Controller {
public function postImageUpload(Request $request) public function postImageUpload(Request $request)
{ {
if ($request->hasFile('file')) { if ($request->hasFile('file')) {
$file = base_path() . '/public/uploads/' . $request['model'] . '/img/' . $request['id'] . '.jpg'; $directory = base_path() . '/public/uploads/' . $request['model'] . '/img/';
file::makeDirectory($directory, 0755, true, true);
$image = Image::make($request->file('file')); $image = Image::make($request->file('file'));
$image->save($file); $image->save($directory . $request['id'] . "-" . $request['name'] . '.jpg');
} else { } else {
return 'file-upload-fail'; return 'file-upload-fail';
} }
@ -199,11 +192,15 @@ class DashboardController extends Controller {
return 'row-delete-fail'; return 'row-delete-fail';
} }
// delete the associated image if one exists // delete associated files if they exist
$image_file = base_path() . '/public/uploads/' . $request['model'] . '/img/' . $request['id'] . '.jpg'; foreach ($items::$dashboard_columns as $column) {
if ($column['type'] == 'image') {
$image_file = base_path() . '/public/uploads/' . $request['model'] . '/img/' . $request['id'] . "-" . $column['name'] . '.jpg';
if (file_exists($image_file) && !unlink($image_file)) { if (file_exists($image_file) && !unlink($image_file)) {
return 'image-delete-fail'; return 'image-delete-fail';
}
}
} }
// Return a success // Return a success

View file

@ -13,6 +13,18 @@ class Contact extends Model
*/ */
protected $table = 'contact'; protected $table = 'contact';
/**
* Dashboard columns
*
* @var array
*/
public static $dashboard_columns = [
[ 'Date', 'created_at' ],
[ 'Name', 'name' ],
[ 'Email', 'email' ],
[ 'Message', 'message' ]
];
/** /**
* Returns the list of all contact submissions * Returns the list of all contact submissions
* *

View file

@ -13,6 +13,17 @@ class Subscriptions extends Model
*/ */
protected $table = 'subscriptions'; protected $table = 'subscriptions';
/**
* Dashboard columns
*
* @var array
*/
public static $dashboard_columns = [
[ 'Date', 'created_at' ],
[ 'Email', 'email' ],
[ 'Name', 'name' ]
];
/** /**
* Returns the list of all subscriptions * Returns the list of all subscriptions
* *

View file

@ -171,12 +171,12 @@ This function should be named the same as the one above except with `Edit` at th
'model' => 'news', 'model' => 'news',
'id' => $id, 'id' => $id,
'item' => $item, 'item' => $item,
'imgup' => true,
'columns' => [ 'columns' => [
[ 'name' => 'title', 'type' => 'text', 'label' => 'The Title' ], [ 'name' => 'title', 'type' => 'text', 'label' => 'The Title' ],
[ 'name' => 'iframe', 'type' => 'text' ], [ 'name' => 'iframe', 'type' => 'text' ],
[ 'name' => 'halign', 'type' => 'select', 'options' => [ 'left', 'center', 'right' ] ], [ 'name' => 'halign', 'type' => 'select', 'options' => [ 'left', 'center', 'right' ] ],
[ 'name' => 'story', 'type' => 'mkd' ], [ 'name' => 'story', 'type' => 'mkd' ],
[ 'label' => 'Header Image', 'name' => 'headerimage', 'type' => 'image' ],
[ 'name' => 'order', 'type' => 'hidden' ] [ 'name' => 'order', 'type' => 'hidden' ]
] ]
]); ]);
@ -187,7 +187,6 @@ This function should be named the same as the one above except with `Edit` at th
* `model`: The model that will be accessed on this page * `model`: The model that will be accessed on this page
* `id`: Always set this to `$id` * `id`: Always set this to `$id`
* `item`: Always set this to `$item` * `item`: Always set this to `$item`
* `imgup`: Set this to `true` to enable image upload, otherwise set to `false`
* `help_text`: An optional value that will add a box containing help text above the form if set * `help_text`: An optional value that will add a box containing help text above the form if set
* `columns`: An array containing a set of arrays where: * `columns`: An array containing a set of arrays where:
* `name` is the name of the column to be edited * `name` is the name of the column to be edited
@ -203,6 +202,7 @@ The following is a list of possible `types` in the `columns` array for Editable
* `date`: Date and time selection tool for date/time data * `date`: Date and time selection tool for date/time data
* `select`: Text input via option select with possible options in an `options` array * `select`: Text input via option select with possible options in an `options` array
* `hidden`: Fields that will contain values to pass to the update function but won't appear on the page (this must be used for the sort column) * `hidden`: Fields that will contain values to pass to the update function but won't appear on the page (this must be used for the sort column)
* `image`: Fields that contain image uploads (name is not part of the database and is instead used in the filename)
* `display`: Displayed information that can't be edited * `display`: Displayed information that can't be edited
#### Edit Item Functionality #### Edit Item Functionality

View file

@ -254,7 +254,7 @@ function editItemInit() {
$textInputs = $(".text-input"), $textInputs = $(".text-input"),
$dateTimePickers = $(".date-time-picker"), $dateTimePickers = $(".date-time-picker"),
$mkdEditors = $(".mkd-editor"), $mkdEditors = $(".mkd-editor"),
$imgUpload = $("#image-upload"), $imgUploads = $(".image-upload"),
$token = $("#_token"), $token = $("#_token"),
$spinner = $("#loading-modal"), $spinner = $("#loading-modal"),
fadeTime = 250, fadeTime = 250,
@ -333,8 +333,8 @@ function editItemInit() {
}); });
}; };
const uploadImage = function(row_id) { const uploadImage = function(row_id, currentImage) {
let file; let file, imgUpload;
// functionality to run on success // functionality to run on success
const returnSuccess = function() { const returnSuccess = function() {
@ -343,30 +343,39 @@ function editItemInit() {
}; };
// add the image from the image upload box for image-upload class elements // add the image from the image upload box for image-upload class elements
if ($imgUpload.length && $imgUpload.val() !== "") { if ($imgUploads.length >= currentImage + 1) {
file = new FormData(); imgUpload = $imgUploads[currentImage];
// add the file, id and model to the formData variable if ($(imgUpload).val() !== "") {
file.append("file", $imgUpload[0].files[0]); file = new FormData();
file.append("id", row_id);
file.append("model", model);
$.ajax({ // add the file, id and model to the formData variable
type: "POST", file.append("file", imgUpload.files[0]);
url: "/dashboard/image-upload", file.append("name", $(imgUpload).attr("name"));
data: file, file.append("id", row_id);
processData: false, file.append("model", model);
contentType: false,
beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRF-TOKEN", $token.val()); } $.ajax({
}).always(function(response) { type: "POST",
if (response === "success") { url: "/dashboard/image-upload",
returnSuccess(); data: file,
} else { processData: false,
hideLoadingModal(); contentType: false,
showAlert("ERROR: Failed to upload image"); beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRF-TOKEN", $token.val()); }
submitting = false; }).always(function(response) {
} console.log(`response: ${response.responseText}`);
});
if (response === "success") {
uploadImage(row_id, currentImage + 1);
} else {
hideLoadingModal();
showAlert("ERROR: Failed to upload image");
submitting = false;
}
});
} else {
uploadImage(row_id, currentImage + 1);
}
} else { } else {
returnSuccess(); returnSuccess();
} }
@ -438,6 +447,7 @@ function editItemInit() {
// populate the formData object // populate the formData object
getFormData(); getFormData();
console.log(JSON.stringify(formData));
// submit the update // submit the update
$.ajax({ $.ajax({
@ -446,7 +456,7 @@ function editItemInit() {
data: formData data: formData
}).always(function(response) { }).always(function(response) {
if (/^id:[0-9][0-9]*$/.test(response)) { if (/^id:[0-9][0-9]*$/.test(response)) {
uploadImage(response.replace(/^id:/, "")); uploadImage(response.replace(/^id:/, ""), 0);
} else { } else {
hideLoadingModal(); hideLoadingModal();
showAlert("ERROR: Failed to " + operation + " record"); showAlert("ERROR: Failed to " + operation + " record");

View file

@ -348,6 +348,7 @@ body {
} }
.current-image { .current-image {
margin-bottom: 15px;
width: 125px; width: 125px;
height: 125px; height: 125px;
background-position: left center; background-position: left center;

View file

@ -45,6 +45,16 @@
@endif @endif
@endforeach @endforeach
</select> </select>
@elseif($column['type'] == 'image')
<input class="image-upload" type="file" name="{{ $column['name'] }}" id="{{ $column['name'] }}" />
@set('current_image', "/uploads/$model/img/$id-" . $column['name'] . ".jpg")
@if(file_exists(base_path() . '/public' . $current_image))
<div class="current-image" style="background-image: url({{ $current_image }});"></div>
@else
<div>(No Image Set)</div>
@endif
@elseif($column['type'] == 'display') @elseif($column['type'] == 'display')
<div class="text-display">{{ $value }}</div> <div class="text-display">{{ $value }}</div>
@endif @endif
@ -53,26 +63,6 @@
</div> </div>
@endforeach @endforeach
@if(!empty($imgup) && $imgup)
<div class="row">
<div class="col-xs-12 col-md-2">
<label for="{{ $column['name'] }}">Picture:</label>
</div>
<div class="col-xs-12 col-md-10">
<input class="image-upload" type="file" name="image-upload" id="image-upload" />
@set('current_image', "/uploads/$model/$id.jpg")
@if(file_exists(base_path() . '/public' . $current_image))
<div class="current-image" style="background-image: url({{ $current_image }});" />
@else
<div>(No Image Set)</div>
@endif
</div>
</div>
@endif
<div class="row"> <div class="row">
<button id="back" type="button" class="back-button btn btn-default">Back</button> <button id="back" type="button" class="back-button btn btn-default">Back</button>
<button id="submit" type="button" class="submit-button btn btn-primary">{{ $id == 'new' ? 'Create' : 'Update' }} {{ $heading }} Item</button> <button id="submit" type="button" class="submit-button btn btn-primary">{{ $id == 'new' ? 'Create' : 'Update' }} {{ $heading }} Item</button>