Skip to content

Commit

Permalink
Dev: Condition quick-add can now save new conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
olleharstedt committed Oct 20, 2016
1 parent 8f781dd commit 6abd0e6
Show file tree
Hide file tree
Showing 6 changed files with 249 additions and 13 deletions.
174 changes: 174 additions & 0 deletions application/controllers/admin/conditionsaction.php
Expand Up @@ -309,6 +309,15 @@ public function index($subaction, $iSurveyID=null, $gid=null, $qid=null)

$aData['quickAddConditionForm'] = $this->getQuickAddConditionForm($args);

$aData['quickAddConditionURL'] = $this->getController()->createUrl(
'/admin/conditions/sa/quickAddCondition',
array(
'surveyId' => $this->iSurveyID,
'gid' => $gid,
'qid' => $qid
)
);

$aViewUrls['conditionshead_view'][] = $aData;

$conditionsList = array();
Expand Down Expand Up @@ -808,6 +817,171 @@ protected function insertCondition(array $args)
$this->redirectToConditionStart($qid, $gid);
}

/**
* As insertCondition() but using Ajax, called from quickAddCondition
* @todo Code duplication
* @return array [message, result], where result = 'success' or 'error'
*/
protected function insertConditionAjax($args)
{
Yii::log(print_r($args, true), CLogger::LEVEL_TRACE, 'debug');
// Extract scenario, cquestions, ...
extract($args);

if (isset($cquestions) && $cquestions != '') {
$conditionCfieldname = $cquestions;
}
elseif(isset($csrctoken) && $csrctoken != '') {
$conditionCfieldname = $csrctoken;
}

$condition_data = array(
'qid' => $qid,
'scenario' => $scenario,
'cqid' => $cqid,
'cfieldname' => $conditionCfieldname,
'method' => $method
);

if (!empty($canswers)) {

$results = array();

foreach ($canswers as $ca) {
//First lets make sure there isn't already an exact replica of this condition
$condition_data['value'] = $ca;

$result = Condition::model()->findAllByAttributes($condition_data);

$count_caseinsensitivedupes = count($result);

if ($count_caseinsensitivedupes == 0) {
$results[] = Condition::model()->insertRecords($condition_data);;
}
}

// Check if any result returned false
if (in_array(false, $results, true)) {
return array(gT('Could not insert all conditions.'), 'error');
}
else if (!empty($results)) {
return array (gT('Condition added.'), 'success');
}
else {
return array(
gT(
"Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.",
"js"
),
'error'
);
}

}
else {

$posted_condition_value = null;

// Other conditions like constant, other question or token field
if ($request->getPost('editTargetTab')=="#CONST") {
$posted_condition_value = Yii::app()->request->getPost('ConditionConst');
}
elseif ($request->getPost('editTargetTab')=="#PREVQUESTIONS") {
$posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
}
elseif ($request->getPost('editTargetTab')=="#TOKENATTRS") {
$posted_condition_value = Yii::app()->request->getPost('tokenAttr');
}
elseif ($request->getPost('editTargetTab')=="#REGEXP") {
$posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
}

if ($posted_condition_value) {
$condition_data['value'] = $posted_condition_value;
$result = Condition::model()->insertRecords($condition_data);
}
else {
$result = null;
}

if ($result === false) {
return array(gT('Could not insert all conditions.'), 'error');
}
else if ($result === true) {
return array (gT('Condition added.'), 'success');
}
else {
return array(
gT(
"Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.",
"js"
),
'error'
);
}
}

}

/**
* Used by quick-add form to add conditions async
* @return void
*/
public function quickAddCondition()
{
Yii::import('application.helpers.admin.ajax_helper', true);
$request = Yii::app()->request;
$data = $this->getQuickAddData($request);

list($message, $status) = $this->insertConditionAjax($data);

if ($status == 'success') {
LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $data['qid']);
ls\ajax\AjaxHelper::outputSuccess($message);
}
else if ($status == 'error') {
ls\ajax\AjaxHelper::outputError($message);
}
else {
ls\ajax\AjaxHelper::outputError('Internal error: Could not add condition, status unknown: ' . $status);
}
}

/**
* Get posted data from quick-add modal form
* @param LSHttpRequest $request
* @return array
*/
protected function getQuickAddData(LSHttpRequest $request)
{
$result = array();
$keys = array(
'scenario',
'cquestions',
'method',
'canswers',
'ConditionConst',
'ConditionRegexp',
'sid',
'qid',
'gid',
'cqid',
'canswersToSelect',
'editSourceTab',
'editTargetTab',
'csrctoken',
'prevQuestionSGQA',
'tokenAttr'
);
foreach ($keys as $key) {
$value = $request->getPost('quick-add-' . $key);
$value = str_replace('QUICKADD-', '', $value); // Remove QUICKADD- from editSourceTab/editTargetTab
$result[$key] = $value;
}

return $result;
}

/**
* Update a condition
* @param array $args
Expand Down
7 changes: 4 additions & 3 deletions application/views/admin/conditions/conditionshead_view.php
Expand Up @@ -66,9 +66,10 @@ class='btn btn-default pull-right condition-header-button'
<?php echo $quickAddConditionForm; ?>
</div>
<div class="modal-footer">
<button type='submit' class='btn btn-primary'><?php eT('Save'); ?></button>
<button type='submit' class='btn btn-default'><?php eT('Save and close'); ?></button>
<button type="button" class="btn btn-danger" data-dismiss="modal">&nbsp;<?php eT("Close"); ?></button>
<button type='submit' id='quick-add-condition-save-button' class='btn btn-primary'><?php eT('Save'); ?></button>
<button type='submit' id='quick-add-condition-save-and-close-button' class='btn btn-default'><?php eT('Save and close'); ?></button>
<button type="button" id='quick-add-condition-close-button' class="btn btn-danger" data-dismiss="modal">&nbsp;<?php eT("Close"); ?></button>
<span id='quick-add-url' class='hidden'><?php echo $quickAddConditionURL; ?></span>
</div>
</div>
</div>
Expand Down
Expand Up @@ -191,7 +191,7 @@ class='form-control'
<div class='col-sm-5'>
<textarea name='ConditionRegexp' class='form-control' id='ConditionRegexp' rows='5' cols='113'><?php echo $EDITConditionRegexp; ?></textarea>
<div id='ConditionRegexpLabel'>
<a href="http://manual.limesurvey.org/wiki/Using_regular_expressions" target="_blank">
<a href="http://manual.limesurvey.org/Using_regular_expressions" target="_blank">
<?php eT("Regular expression"); ?>
</a>
</div>
Expand Down
@@ -1,7 +1,7 @@
<div class="row">
<div class="col-lg-12">

<!-- Form editconditions -->
<!-- Form quick-add condition -->
<?php echo CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"),'post',array('id'=>"quick-add-conditions-form",'name'=>"quick-add-conditions-form", 'class' => 'form form-horizontal'));?>
<div class='form-group'>
<div class='col-sm-2'></div>
Expand Down Expand Up @@ -64,7 +64,7 @@

<div class='form-group'>
<label class='control-label col-sm-2'><?php eT("Comparison operator"); ?></label>
<div class='col-sm-2'>
<div class='col-sm-4'>
<select class='form-control' name='quick-add-method' id='quick-add-method'>
<?php foreach ($method as $methodCode => $methodTxt): ?>
<option value='<?php echo $methodCode; ?>' <?php if ($methodCode == "=="): echo ' selected="selected" '; endif; ?>>
Expand Down Expand Up @@ -167,7 +167,7 @@ class='form-control'
<div class='col-sm-10'>
<textarea name='quick-add-ConditionRegexp' class='form-control' id='quick-add-ConditionRegexp' rows='5' cols='113'></textarea>
<div id='quick-add-ConditionRegexpLabel'>
<a href="http://manual.limesurvey.org/wiki/Using_regular_expressions" target="_blank">
<a href="http://manual.limesurvey.org/Using_regular_expressions" target="_blank">
<?php eT("Regular expression"); ?>
</a>
</div>
Expand Down
8 changes: 6 additions & 2 deletions scripts/admin/admin_core.js
Expand Up @@ -927,15 +927,17 @@ var LsGlobalNotifier = new NotifyFader();
function notifyFader(text, classes, styles, customOptions) {

// Hide all modals
$('.modal').modal('hide');
// TODO: Where is this needed?
// TODO: Commented, because doesn't work quick condition quick-add where modal should stay open
//$('.modal').modal('hide');

LsGlobalNotifier.create(text, classes, styles, customOptions);
}

/**
* Part of ajax helper
* @param {object} JSON object from server
* @return {boolean} true if the original success method should be run after this
* @return {boolean} true if the original success method should be run after this (always, except on failed login)
* @todo Localization
* @todo Branch on message type?
*/
Expand Down Expand Up @@ -978,6 +980,7 @@ LS.ajaxHelperOnSuccess = function(response) {
* Like $.ajax, but with checks for errors,
* permission etc. Should be used together
* with the PHP AjaxHelper.
* @todo Handle error from server (500)?
* @param {object} options - Exactly the same as $.ajax options
* @return {object} ajax promise
*/
Expand All @@ -987,6 +990,7 @@ LS.ajax = function(options) {
var oldError = options.error;
options.success = function(response) {

// User-supplied success is always run EXCEPT when login fails
var runOldSuccess = LS.ajaxHelperOnSuccess(response);

if (oldSuccess && runOldSuccess) {
Expand Down
65 changes: 61 additions & 4 deletions scripts/admin/conditions.js
Expand Up @@ -213,6 +213,35 @@ function selectTabFromOper() {
}
}

/**
* Same as selectTabFromOper but for quick-add modal
*/
function quickAddSelectTabFromOper() {
var val = $('#quick-add-method').val();
if(val == 'RX') {
$('a[href="#QUICKADD-CANSWERSTAB"]').parent().addClass('disabled');
$('a[href="#QUICKADD-CONST"]').parent().addClass('disabled');
$('a[href="#QUICKADD-PREVQUESTIONS"]').parent().addClass('disabled');
$('a[href="#QUICKADD-TOKENATTRS"]').parent().addClass('disabled');
$('a[href="#QUICKADD-REGEXP"]').parent().removeClass('disabled');
$('a[href="#QUICKADD-REGEXP"]').trigger('click');
}
else {
//if (!isAnonymousSurvey) $('#conditiontarget').bootTabs('enable', 3);

$('a[href="#QUICKADD-CANSWERSTAB"]').parent().removeClass('disabled');
$('a[href="#QUICKADD-CONST"]').parent().removeClass('disabled');
$('a[href="#QUICKADD-PREVQUESTIONS"]').parent().removeClass('disabled');
$('a[href="#QUICKADD-TOKENATTRS"]').parent().removeClass('disabled');
$('a[href="#QUICKADD-REGEXP"]').parent().addClass('disabled');

// If regexp tab is selected, trigger click on first tab instead
if ($('a[href="#QUICKADD-REGEXP"]').parent().hasClass('active')) {
$('a[href="#QUICKADD-CANSWERSTAB"]').trigger('click');
}
}
}

$(document).ready(function() {

$('#resetForm').click( function() {
Expand All @@ -226,6 +255,7 @@ $(document).ready(function() {

// Select the condition target Tab depending on operator
$('#method').change(selectTabFromOper);
$('#quick-add-method').change(quickAddSelectTabFromOper);

var p = new populateCanswersSelectObject();
populateCanswersSelect = p.fun;
Expand Down Expand Up @@ -263,22 +293,34 @@ $(document).ready(function() {
$('a[href="' + editTargetTab + '"]').trigger('click');
$('a[href="' + editSourceTab + '"]').trigger('click');

// When user clicks tab, update hidden input
$('#editconditions .src-tab').on('click', function(e) {
var href = $(e.currentTarget).find('a').attr('href');
$('input[name="editSourceTab"]').val(href);
});

// When user clicks tab, update hidden input
$('#editconditions .target-tab').on('click', function(e) {
var href = $(e.currentTarget).find('a').attr('href');
$('input[name="editTargetTab"]').val(href);
});

// Tab management for quick-add modal
var editTargetTab = $('input[name="quick-add-editTargetTab"]').val();
var editSourceTab = $('input[name="quick-add-editSourceTab"]').val();
$('a[href="' + editTargetTab + '"]').trigger('click');
$('a[href="' + editSourceTab + '"]').trigger('click');

// When user clicks tab, update hidden input
$('.src-tab').on('click', function(e) {
$('#quick-add-conditions-form .src-tab').on('click', function(e) {
var href = $(e.currentTarget).find('a').attr('href');
$('input[name="editSourceTab"]').val(href);
$('input[name="quick-add-editSourceTab"]').val(href);
});

// When user clicks tab, update hidden input
$('.target-tab').on('click', function(e) {
$('#quick-add-conditions-form .target-tab').on('click', function(e) {
var href = $(e.currentTarget).find('a').attr('href');
$('input[name="editTargetTab"]').val(href);
$('input[name="quick-add-editTargetTab"]').val(href);
});

// Disable clicks on disabled tabs (regexp)
Expand All @@ -289,6 +331,21 @@ $(document).ready(function() {
}
});

// Bind save-buttons in quick-add modal
$('#quick-add-condition-save-button').on('click', function(ev) {
var formData = $('#quick-add-conditions-form').serializeArray();
var url = $('#quick-add-url').html();
console.log('formData', formData);
LS.ajax({
url: url,
data: formData,
method: 'POST',
error: function () {
console.log(arguments);
}
});
});

});

/**
Expand Down

0 comments on commit 6abd0e6

Please sign in to comment.