Skip to content

Commit

Permalink
No longer clears files from the input[file] box if failed, Under the …
Browse files Browse the repository at this point in the history
…hood changes, no longer duplicates Symphony code, uses a custom event to add entries.

Inspiration and thanks to Nick Dunn and his REST API extension. Will highlight which fields have problems and display errors on them (except the upload field)
This may get obnoxious and I might turn it off. This is instead of showing them in the queue list.
It's customizable by changing a variable in the javascript.
  • Loading branch information
scottkf committed May 12, 2011
1 parent e84cc5d commit 7591663
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 140 deletions.
File renamed without changes
File renamed without changes
4 changes: 4 additions & 0 deletions assets/massuploadutility.css
Expand Up @@ -17,7 +17,11 @@
height: 100%;
}

#error #file_list {
}

#file_list {
color: black;
height: 100px;
overflow: auto;
padding: 8px;
Expand Down
58 changes: 43 additions & 15 deletions assets/massuploadutility.js
Expand Up @@ -5,13 +5,13 @@
// check for html5 input multiple support first
html5Support = ("multiple" in document.createElement("input"));
if(!html5Support){
alert("Sorry, your browser doesn't support HTML5!");
console.log("Sorry, your browser doesn't support HTML5!");
return false;
}

Symphony.Language.add({
'Successfully added a whole slew of entries, {$total} to be exact.': false,
'But {$total} entries were successfully added.': false,
'However, {$total} entries were successfully added.': false,
'Some errors were encountered while attempting to save.': false,
'View all Entries': false,
'Create more?': false,
Expand All @@ -35,7 +35,6 @@
return string.replace(/([^\w\d_-])/gi,'-');
};


// if there's more than one upload field, I have no idea what to do, and it's not terribly important
if (fileField.size() == 1) {
label = fileField.parent().parent();
Expand All @@ -44,6 +43,7 @@
fileField.attr('multiple', 'true');
fileField.parent().append(" \
<input type='hidden' name='MUUsource' value='"+source+"' /> \
<input type='hidden' name='action[api]' value='true' /> \
<div id='progress_report'> \
<div id='progress_report_name'></div> \
<div id='progress_report_status'></div> \
Expand All @@ -69,6 +69,7 @@
return urlBase + urlMuu + '?' + string;
},
autostart: false,
autoclear: false,
method: "post",
sendBoundary: window.FormData || $.browser.mozilla,
onChange: function(event, files) {
Expand Down Expand Up @@ -100,33 +101,60 @@
$("#progress_report_bar").css('width', Math.ceil(val*100)+"%");
},
onFinishOne: function(event, response, name, number, total) {
// check json["message"] if its set nothing happened at all.
// change errorsInQueue to true if you want errors shown in the queue and not on the fields themselves
errorsInQueue = false;
json = $.parseJSON(response);
css = (json.status == 1) ? "success" : "failure";
id = idSafeFilename(name);
p = "<p id='"+id+"'><img src='"+urlAssets + "/images/"+json.status+".png' />&nbsp;" + name + "&nbsp;<small id='MUU-list' class="+css+">";
$.each(json["errors"], function(k,v) {
p += v;
});
p += "</small></p>";
p = "<p id='"+id+"'>";
if (json != null) {
css = (json.response["_result"] == 'error') ? "failure" : "success";
p += "<img src='"+urlAssets + "/images/"+css+".png' />&nbsp;" + name + "&nbsp;<small id='MUU-list' class="+css+">";
if (json.response["_result"] == "error") {
$.each(json.response, function(k,v) {
if (k != "_result" && k != "message" && k != "post-values") {
field = $("form *[name='fields["+k+"]']");
if (errorsInQueue || field.attr('type') == 'file') {
p += v._message + "&nbsp;";
}
else {
// highlight the fields that have errors
// if (v._type == "missing") {
field = field.parents("label");
console.log(field);
if (field.parent().attr('id') != 'error') {
// field.children(":first").attr("name") + " " + v;
field.wrap("<div id=\"error\" class=\"invalid\"></div>");
field.parent().append("<p>" + v._message + "</p>");
}
}
}
});
}
p += "</small></p>";
}
else {
p += "An unknown error occurred.</p>";
}
$("#file_list").show();
$('p#'+id).replaceWith(p);

},
onFinish: function(total) {
failed = $("#MUU-list.failure").size();
total = failed + $("#MUU-list.success").size();
success = total - failed;
p = "<p id=\"notice\" class=\"";
if (failed == 0) {
if (failed == 0 && success > 0) {
p += "success\">" + Symphony.Language.get('Successfully added a whole slew of entries, {$total} to be exact.', { 'total': total });
p += " \
<a href='"+urlBase+"/symphony/publish/"+source+"/new'>"+Symphony.Language.get("Create more?")+"</a> \
<a href='"+urlBase+"/symphony/publish/"+source+"'>"+Symphony.Language.get("View all Entries")+"</a>";
<a href='"+urlBase+"/symphony/publish/"+source+"'>"+Symphony.Language.get("View all Entries")+"</a>";
// reset the form here maybe
}
else {
p += "error\">" + Symphony.Language.get('Some errors were encountered while attempting to save.');
if (success > 0)
p += "&nbsp;" + Symphony.Language.get('But {$total} entries were successfully added.', { 'total' : success});
p += "&nbsp;" + Symphony.Language.get('However, {$total} entries were successfully added.', { 'total' : success});
$("#file_list")
.animate({ backgroundColor: "#eeee55", opacity: 1.0 }, 200)
.animate({ backgroundColor: "transparent", opacity: 1.0}, 350);
Expand Down Expand Up @@ -159,10 +187,10 @@
});
}
else if (fileField.size() > 1) {
console.log("MUU doesn't work with multiple upload fields");
console.log("The Mass Upload Utility doesn't work with multiple upload fields.");
}
else {
console.log("No upload fields detected");
console.log("No upload fields detected.");
}

});
Expand Down
106 changes: 17 additions & 89 deletions content/content.index.php
Expand Up @@ -3,6 +3,9 @@
require_once(TOOLKIT . '/class.administrationpage.php');
require_once(TOOLKIT . '/class.sectionmanager.php');
require_once(TOOLKIT . '/class.entrymanager.php');
require_once(CORE . '/class.frontend.php');
require_once(EXTENSIONS . '/massuploadutility/events/event.mass_upload_utility_entry.php');
require_once(EXTENSIONS . '/massuploadutility/lib/class.xmltoarray.php');

/**
* Called to build the content for the page.
Expand All @@ -13,8 +16,8 @@ class contentExtensionMassUploadUtilityIndex extends AdministrationPage {
protected $_valid = false;
protected $_message = '';

public function getSectionID() {
$sectionManager = new SectionManager($this->_Parent);
public function getSectionId() {
$sectionManager = new SectionManager(Frontend::instance());

$section_id = $sectionManager->fetchIDFromHandle(General::sanitize($_REQUEST['MUUsource']));

Expand All @@ -24,109 +27,34 @@ public function getSectionID() {
return $section_id;
}
/**
* ---------------------------------------------------------
* This functionality is essentially duplicated (and slightly changed)
* from Symphony's content.publish.php
* in the function public function __actionNew(){
* Should that core ever change, this needs to be as well.
*
* _REQUEST view() are used because jquery.html5_upload.js can't deal
* _REQUEST in view() are used because jquery.html5_upload.js can't deal
* with extra variables in the POST
* Should this change, view() will need to be changed to action()
* ---------------------------------------------------------
*/
public function view() {
if (!isset($_REQUEST['MUUsource']) or $_REQUEST['MUUsource'] == '')
{ $this->_message = __("You didn't choose a source, perhaps you don't have any sections with an upload field in them?"); $this->__response(); }

if (($section_id = $this->getSectionID()) === NULL)
{ $this->_message = __('The Section you are looking, <code>%s</code> for could not be found.', $this->_context['section_handle']); $this->__response(); }
$sectionManager = new SectionManager($this->_Parent);

$entryManager = new EntryManager($this->_Parent);
{ exit; }

$entry =& $entryManager->create();
$entry->set('section_id', $section_id);
$entry->set('author_id', Administration::instance()->Author->get('id'));
$entry->set('creation_date', DateTimeObj::get('Y-m-d H:i:s'));
$entry->set('creation_date_gmt', DateTimeObj::getGMT('Y-m-d H:i:s'));

$fields = $_REQUEST['fields'];
if ((!$this->__processFilePostData($fields)) === NULL)
{ $this->_message = __("Did you forget to upload some files?"); $this->__response(); }

if(__ENTRY_FIELD_ERROR__ == $entry->checkPostData($fields, $error))
{ $this->_errors[key($error)] = $error[key($error)]; $this->__response(); }
if (($section_id = $this->getSectionId()) === NULL)
{ exit; }

// setup the data, process it
// if(__ENTRY_OK__ != $this->setDataFromPost($entry, $fields, $this->_errors, false, false, $entries))
elseif(__ENTRY_OK__ != $entry->setDataFromPost($fields, $error)) {
$this->_errors[key($error)] = $error[key($error)];
$this->__response();
}
$_POST['fields'] = $_REQUEST['fields'];
$_POST['action'] = $_REQUEST['action'];

else {
Symphony::ExtensionManager()->notifyMembers('EntryPreCreate', '/publish/new/', array('section' => $section, 'entry' => &$entry, 'fields' => &$nfields));
$event = new Event_Mass_Upload_Utility_Entry(Frontend::instance(), array());

$prepopulate_field_id = $prepopulate_value = NULL;
if(isset($_POST['prepopulate'])){
$prepopulate_field_id = array_shift(array_keys($_POST['prepopulate']));
$prepopulate_value = stripslashes(rawurldecode(array_shift($_POST['prepopulate'])));
}
// Borrowed from Nick Dunn
$xml = $event->load();
if(is_array($xml)) $xml = reset($xml);
if($xml instanceOf XMLElement) $xml = $xml->generate(TRUE);

// commit the entry if we made it
if(!$entry->commit()){
define_safe('__SYM_DB_INSERT_FAILED__', true);
$this->pageAlert(NULL, Alert::ERROR);
}
else
{
// keep track of it if it was inserted
$entries[] = $entry->get('id');
$this->_valid = true;
Symphony::ExtensionManager()->notifyMembers('EntryPostCreate', '/publish/new/', array('section' => $section, 'entry' => $entry, 'fields' => $nfields));
}
echo(json_encode(XMLToArray::convert($xml)));

}

$this->__response();
exit;
}

/* main page */


public function __processFilePostData(&$fields) {
if(isset($_FILES['fields'])){
$filedata = General::processFilePostData($_FILES['fields']);

foreach($filedata as $handle => $data){
if(!isset($fields[$handle])) $fields[$handle] = $data;
elseif(isset($data['error']) && $data['error'] == 4) $fields['handle'] = NULL;
else{

foreach($data as $ii => $d){
if(isset($d['error']) && $d['error'] == 4) $fields[$handle][$ii] = NULL;
elseif(is_array($d) && !empty($d)){

foreach($d as $key => $val)
$fields[$handle][$ii][$key] = $val;
}
}
}
}
return TRUE;
}
else
return NULL;

}


private function __response() {
echo json_encode(array("status"=>$this->_valid, "message"=>$this->_message, "errors" => $this->_errors));
exit;
}

}
?>
12 changes: 8 additions & 4 deletions events/event.mass_upload_utility_entry.php
@@ -1,8 +1,12 @@
<?php
/**
* An event to avoid duplicating on the Symphony Core when
* adding an entry
*/

require_once(TOOLKIT . '/class.event.php');

Class EventMass_Upload_Utility_Entry extends Event{
Class Event_Mass_Upload_Utility_Entry extends Event{

const ROOTELEMENT = 'response';

Expand All @@ -16,7 +20,7 @@ public static function about(){
'website' => 'http://tesoriere.com',
'email' => 'scott@tesoriere.com'),
'version' => '1.0',
'release-date' => '2009-11-13T11:35:07+00:00',
'release-date' => '2011-05-12T11:35:07+00:00',
'trigger-condition' => 'action[api]');
}

Expand All @@ -28,8 +32,8 @@ public static function documentation(){
return '';
}

public function load(){
return $this->__trigger();
public function load(){
if(isset($_POST['action']['api'])) return $this->__trigger();
}

protected function __trigger(){
Expand Down
25 changes: 0 additions & 25 deletions lang/lang.de.example.php

This file was deleted.

0 comments on commit 7591663

Please sign in to comment.