selectQuestionBy.php 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
<?php
/**
 * selectBySurveyQuestion get list of answers in another survey
 *
 * @author Denis Chenu <denis@sondages.pro>
 * @copyright 2017 Denis Chenu <www.sondages.pro>
 * @copyright 2017 OECD (Organisation for Economic Co-operation and Development ) <www.oecd.org>
 * @license GPL v3
 * @version 0.0.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
class selectQuestionBy extends \ls\pluginmanager\PluginBase
{

  static protected $description = 'Use a text question as a dropdown filled by another question, a label or a survey';
  static protected $name = 'selectQuestionBy';
  /**
  * Add function to be used in beforeQuestionRender event and to attriubute
  */
  public function init()
  {
    $this->subscribe('beforeQuestionRender');
    $this->subscribe('newQuestionAttributes');

    /* Register package and language */
    $this->subscribe('afterPluginLoad');

  }

  /**
   * The attribute
   */
  public function newQuestionAttributes()
  {
    $newAttributes = array(
      'selectQuestionByType'=>array(
        'types'=>'T',
        'category'=>gT('Drop down'),
        'sortorder'=>100,
        'inputtype'=>'singleselect',
        'options'=>array(
          'none'=>$this->_translate("Disable"),
          'question'=>$this->_translate("Question"),
          //~ 'label'=>$this->_translate("Label"),
        ),
        'default'=>'none',
        'help'=>gT('Choose the type of source'),
        'caption'=>gT('Type of source'),
      ),
      'selectQuestionBySource'=>array(
        'types'=>'T',/* Long text allow to save anything */
        'category'=>gT('Drop down'),
        'sortorder'=>110, /* Own category */
        'inputtype'=>'text',
        'default'=>'',
        'help'=>gT('Question code in this survey, label id or name  or survey id or name. With name : return the first find.'),
        'caption'=>gT('Value for the source'),
      ),
      'selectQuestionByDropdownType'=>array(
        'types'=>'T',
        'category'=>gT('Drop down'),
        'sortorder'=>120,
        'inputtype'=>'singleselect',
        'options'=>array(
          'single'=>$this->_translate("Single"),
          'multiple'=>$this->_translate("Multiple"),
        ),
        'default'=>'multiple',
        'help'=>gT('Choose if user can select multiple or only one choice'),
        'caption'=>gT('Dropdown type'),
      ),
Chenu Denis's avatar
Chenu Denis committed
81
      'selectQuestionByForceOne'=>array(// Maybe add an automatic system for mandatory ? 
82
        'types'=>'T',
Chenu Denis's avatar
Chenu Denis committed
83
        'category'=>gT('Drop down'),
84 85 86 87 88 89
        'sortorder'=>140,
        'inputtype'=>'switch',
        'default'=>0,
        'help'=>gT(''),
        'caption'=>gT('Disable removing last one'),
      ),
Chenu Denis's avatar
Chenu Denis committed
90 91 92 93 94 95 96 97 98
      //~ 'selectQuestionByExclusive'=>array(
        //~ 'types'=>'T',
        //~ 'category'=>gT('Drop down'),
        //~ 'sortorder'=>150,
        //~ 'inputtype'=>'text',
        //~ 'default'=>'',
        //~ 'help'=>gT('Work in progress : list of code for exclusive option (disable other, is disable if other are checked)'),
        //~ 'caption'=>gT('[WIP] Exclusive option'),
      //~ ),
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    );

    if(method_exists($this->getEvent(),'append')) {
      $this->getEvent()->append('questionAttributes', $newAttributes);
    } else {
      $questionAttributes=(array)$this->event->get('questionAttributes');
      $questionAttributes=array_merge($questionAttributes,$newAttributes);
      $this->event->set('questionAttributes',$questionAttributes);
    }
  }

  /**
   * Update Answer part in question display
   */
  public function beforeQuestionRender()
  {
    $oEvent=$this->getEvent();
    if($oEvent->get('type')=='T') {
      $aAttributes=\QuestionAttribute::model()->getQuestionAttributes($oEvent->get('qid'));
      list($aListDropdown,$aListOptions)=$this->_getDataDropDownList($aAttributes['selectQuestionByType'],$aAttributes['selectQuestionBySource']);
      if($aListDropdown) {
        $oQuestion=\Question::model()->findByPk(array('qid'=>$oEvent->get('qid'),'language'=>App()->getLanguage()));
        $name=$oEvent->get('surveyId').'X'.$oEvent->get('gid').'X'.$oEvent->get('qid');
        $actualValue=$_SESSION['survey_'.$oEvent->get('surveyId')][$name];
        switch ($aAttributes['selectQuestionByDropdownType']) {
          case 'single':
            $empty=null;
            if(!$actualValue) {
                $empty=gT("Please choose...");
            } elseif ($oQuestion->mandatory!='Y') {
                $empty=gT("(None)");
            }
            $answer=\CHtml::dropDownList(
              $name,
              $actualValue,
              $aListDropdown,
              array(
                'id'=>"answer{$name}",
                'class'=>'form-control select-surveyquestion',
                'prompt'=>$empty,
                'data-selectQuestionBy'=>'simple',
              )
            );
            $answer=\CHtml::tag("div",array('class'=>'answer-item select-item dropdown-item selectBySurveyQuestion-item'),$answer);
            $oEvent->set('answers',$answer);
Chenu Denis's avatar
Chenu Denis committed
144
            Yii::app()->getClientScript()->registerPackage('selectQuestionBy');
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            break;
          case 'multiple':
            $aActualValue=explode(',',$actualValue);
            $dropDownHtml=\CHtml::dropDownList(
              "select2-{$name}[]",
              $aActualValue,
              $aListDropdown,
              array(
                'id'=>"select2-answer{$name}",
                'class'=>'form-control select-surveyquestion',
                'multiple'=>true,
                'data-update'=>"answer{$name}",
                'data-selectQuestionBy'=>'multiple',
                'data-forceone'=> $aAttributes['selectQuestionByForceOne'],
                'data-placeholder' => "Select one or more option",
                'options'=>$aListOptions
              )
            );
            $dropDownHtml=\CHtml::tag("div",array('class'=>'answer-item select-multiple-item dropdown-multiple-item selectBySurveyQuestion-item'),$dropDownHtml);
            $textareaHtml=\CHtml::textArea(
              $name,
              $actualValue,
              array(
                'id'=>"answer{$name}",
                'class'=>'form-control select-surveyquestion',
              )
            );
            $textareaHtml=\CHtml::tag("div",array('class'=>'answer-item text-item hidden'),$textareaHtml);
            $oEvent->set('answers',$dropDownHtml.$textareaHtml);
            Yii::app()->getClientScript()->registerPackage('selectQuestionBy');
            break;
          default:
            /* No update, @todo : log it */
        }
      }

    }
  }

  /**
   * Get the dropdown list according to params
   * @param string $type type of source : can be question, label or survey
   * @param string $value value of the source
   * @return null|array
   */
  private function _getDataDropDownList($type,$value)
  {
    $value=trim($value);
    if(empty($type) || empty($value)) {
      return;
    }
    switch ($type) {
      case 'question':
        return $this->_getListByQuestion($value);
      case 'label':
        return $this->_getListByLabel($value);
      case 'survey':
        return $this->_getListBySurvey($value);
    }
  }

  /**
   * Get the dropdown list according to survey
   * @param string $qcode Question code
   * @return null|array
   */
  private function _getListByQuestion($qcode) {
    
    $surveyid=$this->getEvent()->get('surveyId',null,null,$this->getEvent()->get('survey'));
    $language=Yii::app()->getLanguage();
    $oQuestion=Question::model()->find(
        "title=:title AND sid=:sid and language=:language and (type='!' or type='L')",
        array(
            ":title"=>$qcode,
            ":sid"=>$surveyid,
            ":language"=>$language
        )
    );
    if($oQuestion) {
        $oAnswers=Answer::model()->findAll(array(
            'condition'=>"qid=:qid and language=:language",
            'order'=>"sortorder",
            'params'=>array(':qid'=>$oQuestion->qid,':language'=>$oQuestion->language)
        ));
        if($oAnswers) {
            /* Find if we need categories ? */
            $oSeparator=QuestionAttribute::model()->find("qid=:qid and attribute='category_separator'",array(":qid"=>$oQuestion->qid));
            if(!$oSeparator) {
Chenu Denis's avatar
Chenu Denis committed
233
                return array(\CHtml::listData($oAnswers,'code','answer'),array());
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            }
            $separator=trim($oSeparator->value);
            $aCategories=array();
            $aOptions=array();
            foreach($oAnswers as $oAnswer) {
                $aAnswer=explode($separator,$oAnswer->answer);
                if(count($aAnswer)==1) {
                    $aAnswer=array("",$aAnswer[0]);
                }
                if(!isset($aCategories[$aAnswer[0]])) {
                    $aCategories[$aAnswer[0]]=array();
                }
                $aCategories[$aAnswer[0]][$oAnswer->code]=$aAnswer[1];
                $aOptions[$oAnswer->code]=array('data-group'=>$aAnswer[0]);
            }
            return array($aCategories,$aOptions);
        }
    }
  }

  /**
   * Get the dropdown list according to survey
   * @param string $qcode Question code
   * @return null|array
   */
  private function _getListByLabel($qcode) {

  }

  /**
   * Get the dropdown list according to survey
   * @param string|int $survey survey id
   * @return null|array
   */
  private function _getListBySurvey($survey) {
    $iSurveyId=(int) $survey;
    if((string) $iSurveyId !== (string) $survey) {
      return;
    }
    $oSurvey=Survey::model()->findByPk($iSurveyId);
    if(!$oSurvey) {
      return;
    }
    $language=$oSurvey->language;
    $aDropDownList=array();
    $oGroups=\QuestionGroup::model()->findAll(array(
      'select'=>'gid,group_name',
      'condition'=>'sid=:surveyid and language=:language',
      'order'=>'group_order asc',
      'params'=>array(
        ':surveyid'=>$iSurveyId,
        ':language'=>$language,
      )
    ));
    /* Todo : one request and listData */
    $aGroups=array();
    foreach ($oGroups as $oGroup) {
      $oQuestions=\Question::model()->findAll(array(
        'select'=>'qid,title,question',
        'condition'=>'gid=:gid and language=:language',
        'order'=>'question_order asc',
        'params'=>array(
          ':gid'=>$oGroup->gid,
          ':language'=>$language,
        )
      ));
      $aQuestions=array();
      foreach($oQuestions as $oQuestion) {
        switch($condition) {
          case 'oecdTopicCode':
            $oQuestionValid=\QuestionAttribute::model()->find('qid=:qid and attribute=:attribute',array(':qid'=>$oQuestion->qid,':attribute'=>'oecdTopicCode'));
            if($oQuestionValid && $oQuestionValid->value) {
              $aQuestions[trim($oQuestionValid->value)]=$oQuestion->question;
            }
            break;
          case 'code':
          default:
            $aQuestions[$oQuestion->title]=$oQuestion->question;
        }
      }
      if(count($aQuestions) ) {
        $aGroups[$oGroup->group_name]=$aQuestions;
      }
    }
    if(count($aGroups) ) {
      return $aGroups;
    }
  }
  /**
   * @todo Translate a string
   * @param string $string
   * @return string
   */
  private function _translate($string)
  {
    return $string;
  }

  /**
   * Done just after plugin loaded, allow to update Yii and LS config
   */
  public function afterPluginLoad()
  {
    Yii::setPathOfAlias('selectQuestionBy',dirname(__FILE__));
    Yii::app()->clientScript->addPackage( 'selectQuestionBy', array(
        'basePath'    => 'selectQuestionBy.assets',
        'css'         => array('selectQuestionBy.css'),
        'js'          => array('selectQuestionBy.js'),
        'depends'     => array('select2-bootstrap-theme'),
    ));
  }
}