formbuilder.php 19.6 KB
Newer Older
Clément Damiens's avatar
 
Clément Damiens committed
1
<?php   
Raph El's avatar
Raph El committed
2
//var_dump($saveOneByOne);
Clément Damiens's avatar
 
Clément Damiens committed
3 4 5 6 7 8 9 10 11 12 13 14 15
$saveOneByOne = (isset($saveOneByOne)) ? $saveOneByOne :false;
if( isset( $form["inputs"] ) ){ ?>
<form id="formQuest">
    <?php 
    $initValues = [];
    $ct = 1;
    
    $orderInputs = [];
    $orderInputsKeys = [];

    foreach ( $form["inputs"] as $key => $input) {
        if( stripos( $input["type"] , "tpls.forms.cplx" ) !== false )
            $saveOneByOne = true;
Raph El's avatar
Raph El committed
16 17 18 19 20 21
    }
    
    foreach ( $form["inputs"] as $key => $input) {
        if(isset($input["position"])){
            $orderInputs[(int)$input["position"]] = $input;
            $orderInputsKeys[(int)$input["position"]] = $key;
Clément Damiens's avatar
 
Clément Damiens committed
22
        }
Raph El's avatar
Raph El committed
23
    }
Clément Damiens's avatar
 
Clément Damiens committed
24

Raph El's avatar
Raph El committed
25 26 27 28 29 30
    $inV = $form["inputs"];
    foreach ( $form["inputs"] as $key => $input) {
        if(!isset($input["position"])){
            unset( $form["inputs"][$key]);
        }else{
            unset( $inV[$key]);
Clément Damiens's avatar
 
Clément Damiens committed
31
        }
Raph El's avatar
Raph El committed
32
    }
Clément Damiens's avatar
 
Clément Damiens committed
33 34


Raph El's avatar
Raph El committed
35 36 37 38
    if(!function_exists('sortByPosOrder'))
    {
        function sortByPosOrder($a, $b) {
            return (int)$a['position'] - (int)$b['position'];
Clément Damiens's avatar
 
Clément Damiens committed
39
        }
Raph El's avatar
Raph El committed
40
    }
Clément Damiens's avatar
 
Clément Damiens committed
41

Raph El's avatar
Raph El committed
42
    uasort($form["inputs"], 'sortByPosOrder');
Clément Damiens's avatar
 
Clément Damiens committed
43 44 45



Raph El's avatar
Raph El committed
46
    $form["inputs"] = array_merge($form["inputs"], $inV);
Clément Damiens's avatar
 
Clément Damiens committed
47 48 49 50 51 52 53 54

    //nouvelle repositionnement




    //fin nouvelle repositionnement
   //echo json_encode($form["inputs"]) ;
55
    $dragNDrop = ($canEditForm) ? "dragNDrop" : "" ;
Clément Damiens's avatar
 
Clément Damiens committed
56
    echo "<ul class='questionList col-xs-12 ".$dragNDrop."'>";
Clément Damiens's avatar
 
Clément Damiens committed
57
    foreach ( $form["inputs"] as $key => $input) { 
Clément Damiens's avatar
 
Clément Damiens committed
58
        $canAnswer = (Yii::app()->session["userId"] == $answer["user"] || !empty($parentForm["anyOnewithLinkCanAnswer"])) ? true :false;
Raph El's avatar
Raph El committed
59
        $editQuestionBtn = ($canEditForm) ? " <a class='btn btn-xs btn-danger editQuestion' href='javascript:;' data-form='".$form["id"]."' data-id='".$form["_id"]."' data-collection='".Form::COLLECTION."' data-key='".$key."' data-path='inputs.".$key."'><i class='fa fa-pencil'></i></a>".
Tibor Katelbach's avatar
tweak  
Tibor Katelbach committed
60
            " <a class='btn btn-xs btn-danger deleteLine' href='javascript:;' data-id='".$form["_id"]."' data-collection='".Form::COLLECTION."' data-key='question".$key."' data-path='inputs.".$key."'><i class='fa fa-trash'></i></a>" : "";
Clément Damiens's avatar
 
Clément Damiens committed
61

Raph El's avatar
Test  
Raph El committed
62
        //var_dump($canEditForm);
Raph El's avatar
Raph El committed
63

Clément Damiens's avatar
 
Clément Damiens committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        $tpl = $input["type"];
        if(in_array($tpl, ["textarea","markdown","wysiwyg"]))
            $tpl = "tpls.forms.textarea";
        else if(empty($tpl) || in_array($tpl, ["text","button","color","date","datetime-local","email","image","month","number","radio","range","tel","time","url","week","tags"]))
            $tpl = "tpls.forms.text";
        else if(in_array($tpl, ["sectionTitle"]))
            $tpl = "tpls.forms.".$tpl;

        if( stripos( $tpl , "tpls.forms." ) !== false )
            $tplT = explode(".", $input["type"]);

        $kunikT = explode( ".", $input["type"]);
        $keyTpl = ( count($kunikT)>1 ) ? $kunikT[ count($kunikT)-1 ] : $input["type"];
        $kunik = $keyTpl.$key;
        $answers = null;
        $answerPath = "answers.".$key.".";
        if(isset($wizard))
        {
            if($wizard){
                $answerPath = "answers.".$form["id"].".".$key.".";
                if( isset($answer["answers"][$form["id"]][$key]) && count($answer["answers"][$form["id"]][$key])>0 )
                    $answers = $answer["answers"][$form["id"]][$key];
            }
            else {
                if(isset($answer["answers"][$key]))
                    $answers = $answer["answers"][$key];
            }
        }
        
        // var_dump($answerPath);
        // var_dump($answers);
95
        //var_dump($mode); exit;
Clément Damiens's avatar
 
Clément Damiens committed
96
        $p = [ 
Tibor Katelbach's avatar
Tibor Katelbach committed
97 98 99 100 101
            "el" => $el,
            "parentForm"=> $parentForm,
            "form"      => $form, 
            "key"       => $key, 
            "kunik"     => $kunik,
Clément Damiens's avatar
 
Clément Damiens committed
102 103
            "input"     => $input,
            "type"      => $input["type"], 
Tibor Katelbach's avatar
Tibor Katelbach committed
104 105
            "answerPath"=> $answerPath,
            "answer"    => $answer,
Clément Damiens's avatar
 
Clément Damiens committed
106 107
            "answers"   => $answers ,//sub answers for this input
            "label"     => $input["label"] ,//$ct." - ".$input["label"] ,
Tibor Katelbach's avatar
Tibor Katelbach committed
108
            "titleColor"=> (isset($this->costum["colors"]["pink"])) ? $this->costum["colors"]["pink"] : "#000",
Clément Damiens's avatar
 
Clément Damiens committed
109 110
            "info"      => isset($input["info"]) ? $input["info"] : "" ,
            "placeholder" => isset($input["placeholder"]) ? $input["placeholder"] : "" ,
Tibor Katelbach's avatar
Tibor Katelbach committed
111
            "mode"      => $mode,
Clément Damiens's avatar
 
Clément Damiens committed
112
            "canEdit"   => $canEdit,
113
            "canEditForm" => @$canEditForm,
114
            "canAdminAnswer" => $canAdminAnswer,
Tibor Katelbach's avatar
Tibor Katelbach committed
115
            "canAnswer" => $canAnswer,
Raph El's avatar
Modif  
Raph El committed
116
            "editQuestionBtn" => @$editQuestionBtn,
Clément Damiens's avatar
 
Clément Damiens committed
117
            "saveOneByOne" => $saveOneByOne,
Tibor Katelbach's avatar
Tibor Katelbach committed
118
            "wizard"    => (isset($wizard) && $wizard == true)  ];
Clément Damiens's avatar
 
Clément Damiens committed
119 120 121 122 123 124 125

        if(isset($tplT[2]) && $tplT[2] == "select" && isset($input["options"]))
            $p["options"] = $input["options"];
        
        if($input["type"] == "tags") 
            $initValues[$key] = $input;
        
Raph El's avatar
Raph El committed
126
        echo "<li id='question".$key."' class='col-xs-12 no-padding questionBlock'  data-id='".$form['_id']."' data-path='inputs.".$key.".position' data-key='".$key."' data-form='".$form["id"]."' style='margin-bottom:0px'>";
Clément Damiens's avatar
 
Clément Damiens committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140
            $this->renderPartial( "survey.views.".$tpl , $p );
        echo "</li>";
        
        $ct++; 
    }   
    echo "</ul>";
    $id = (!empty($answer)) ? " data-id='".$answer["_id"]."' " : "";
    
    //if form contains just one cplx input then all saves are made oneByone
    if(!$saveOneByOne){ ?>
    <a href="javascript:;" id="openFormSubmit" <?php echo $id ?> class=" btn btn-primary">Envoyer</a>
    <?php } ?>
</form>
<?php }
Raph El's avatar
Raph El committed
141

Raph El's avatar
Test  
Raph El committed
142
if ($canEditForm) { ?>
Clément Damiens's avatar
 
Clément Damiens committed
143 144 145
<div class="text-center">   
    <a href="javascript:;" class="addQuestion btn btn-danger" data-form="<?php echo $formId ?>"  data-id="<?php echo $form['_id'] ?>" ><i class="fa fa-plus"></i> Ajouter Une Question</a>
</div>
Raph El's avatar
Raph El committed
146 147
<?php } 
if ($mode != "pdf") { ?>
Clément Damiens's avatar
 
Clément Damiens committed
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
<script type="text/javascript">

var initValues = <?php echo (!empty($initValues)) ?json_encode( $initValues ) : "null"; ?>;

jQuery(document).ready(function() {

    mylog.log("render","/modules/survey/views/tpls/forms/formbuilder.php");
    
    $( ".saveOneByOne" ).off().on( "blur", function( event ) {
        event.preventDefault();
        //toastr.info('saving...'+$(this).attr("id"));
        //$('#openForm118').parent().children("label").children("h4").css('color',"green")
        if( notNull(answerObj)){

            var answer = {
                collection : "answers",
                id : answerObj._id.$id,
                path : "answers."+$(this).attr("id")
            };

            if(answerObj.formList)
                answer.path = "answers."+$(this).data("form")+"."+$(this).attr("id");           
              
            if($(this).attr("type") == "checkbox")
                answer.value = $(this).is(":checked");
            else
                answer.value = $(this).val();
              
Tibor Katelbach's avatar
Tibor Katelbach committed
176
            mylog.log("saveOneByOne",$(this).attr("id"), answer );
Clément Damiens's avatar
 
Clément Damiens committed
177 178
              
            dataHelper.path2Value( answer , function(params) { 
Tibor Katelbach's avatar
Tibor Katelbach committed
179 180 181
                toastr.success('saved');
                saveLinks(answerObj._id.$id,"updated",userId);
            } );
Clément Damiens's avatar
 
Clément Damiens committed
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 233 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
        } else {
            toastr.error('answer cannot be empty, on saveOneByOne!');
        }
    });

    if(initValues){
        $.each(initValues, function(k,inp) { 
            if(inp.type == "tags"){
                $("#"+k).select2({
                    "tags": inp.data ,
                    "tokenSeparators": [','],
                    //"minimumInputLength" : (inp.limit) ? inp.limit : 3,
                    "placeholder" : inp.placeholder
                });
            }
        })
    }



<?php if($canEdit) { ?>


    // var myOtherformInputsHere = formInputs;
    //
    // if( notNull(formInputs [ tplCtx.form ]) )
    //     myformInputsHere = formInputs[ tplCtx.form ];
    <?php if(isset($wizard)) { ?>
    var myWizard = '<?php echo $wizard ?>';
    <?php }else{ ?>
    var myWizard = '0';
    <?php } ?>


    if(myWizard === '1'){
        $.each(formInputs, function (index, value) {

            var arrayPosition = [];
            var arrayMissingV = 0;
            var i = 1;

            arrayPosition.push(0);

            $.each(value, function (indexNiv2, valueNiv2) {

                if(notNull(valueNiv2) && notNull(valueNiv2.position)){
                    arrayPosition.push(parseInt(valueNiv2.position));
                } else {
                    arrayMissingV++;
                }
            });

            var maxValueInArray = Math.max.apply(Math, arrayPosition);

            if(arrayMissingV !== 0){
                $.each(value, function (indexNiv2, valueNiv2) {
                    if(arrayMissingV !== 0){
                        if(notNull(valueNiv2) && !notNull(valueNiv2.position)){
                            valueNiv2.position = (maxValueInArray + i).toString();
                            i++;
                            arrayMissingV--;
                        }
                    }
                });
            }

        });
    } else {

        var arrayPosition = [];
        var arrayMissingV = 0;
        var i = 1;

        arrayPosition.push(0);

        $.each(formInputs, function (index, value) {

            if(notNull(value) && notNull(value.position)){
                arrayPosition.push(parseInt(value.position));
            } else {
                arrayMissingV++;
            }
        });

        var maxValueInArray = Math.max.apply(Math, arrayPosition);

        if(arrayMissingV !== 0){
            $.each(formInputs, function (index, value) {
                if(arrayMissingV !== 0){
                    if(notNull(value) && !notNull(value.position)){
                        value.position = (maxValueInArray + i).toString();
                        i++;
                        arrayMissingV--;
                    }
                }
            });
        }

    }

    //questions can be ordered by drag n drop
283
    $( ".dragNDrop" ).sortable({
Clément Damiens's avatar
 
Clément Damiens committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297
        stop: function(event, ui) {
            //alert("New position: " + ui.item.index()+ ui.item.data("key")+ ui.item.data("form"));
            tplCtx.id = ui.item.data("id");
            tplCtx.collection = "forms";            
            tplCtx.path = ui.item.data("path");
            tplCtx.key = ui.item.data("key");
            tplCtx.form = ui.item.data("form");
            tplCtx.value = ""+ui.item.index();

            //apres la ligne 186
            //il faut traverser tout les formInputs
            //et si formInputs.xxx.position est >= tplCtx.value alors 
            //formInputs.xxx.position = formInputs.xxx.position+1

Tibor Katelbach's avatar
Tibor Katelbach committed
298
            mylog.dir(tplCtx );
Clément Damiens's avatar
 
Clément Damiens committed
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 346
              
              dataHelper.path2Value( tplCtx , function(params) { 
                    toastr.success('move saved!');

                var myformInputsHere = formInputs;
                
                if( notNull(formInputs [ tplCtx.form ]) )
                    myformInputsHere = formInputs[ tplCtx.form ];

                    var distance =0;

                    if(parseInt(tplCtx.value) + 1 < parseInt(myformInputsHere[tplCtx.key]["position"]) ){ // Go up
                        distance = parseInt(myformInputsHere[tplCtx.key]["position"]) - parseInt(tplCtx.value);
                        distance = distance - 1;
                            $.each(myformInputsHere, function (index, value) {
                                if (distance !== 0){
                                    if (value.position >= (parseInt(tplCtx.value) + 1).toString()) {
                                      value.position = (parseInt(value.position) + 1).toString();
                                      distance--;
                                  }
                              }
                          });
                      myformInputsHere[tplCtx.key]["position"] = (parseInt(tplCtx.value)+1).toString();
                    }else { // Go down
                      distance = parseInt(tplCtx.value) - parseInt(myformInputsHere[tplCtx.key]["position"]);
                      distance = distance + 1;
                      for (let [key, value] of Object.entries(myformInputsHere).reverse()) {
                          if (distance !== 0){
                              if (value.position <= (parseInt(tplCtx.value) + 1).toString()) {
                                  value.position = (parseInt(value.position) - 1).toString();
                                  distance--;
                              }
                          }
                      }
                      myformInputsHere[tplCtx.key]["position"] = (parseInt(tplCtx.value)+1).toString();
                    }

                  tplCtx.path = "inputs";
                  tplCtx.value = myformInputsHere;
                  dataHelper.path2Value( tplCtx , function(params) {
                      toastr.success('edit saved!');
                  });


                  //formInputs[tplCtx.form][tplCtx.key]["position"] = tplCtx.value;
                    var clearDoublePos = false;
                    //if input exists on same position delete position attribute
                    $.each( formInputs[tplCtx.form], function(k,inp) {
Tibor Katelbach's avatar
Tibor Katelbach committed
347
                        mylog.log("incPositions",k,inp.position)
Clément Damiens's avatar
 
Clément Damiens committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
                        if( k != tplCtx.key && inp.position == tplCtx.value ){
                            clearDoublePos = true;

                            tplCtx.path = "inputs."+k+".position";
                            tplCtx.value = null;
                            dataHelper.path2Value( tplCtx , function(params) { 
                                delete formInputs[tplCtx.form][k]["position"];
                            } );
                        }
                    })
                    if(clearDoublePos)
                        toastr.info('conflicting positions , please reload the page!');
                } );

        }
    });

    $(".editQuestion").off().on("click",function() { 

        var activeForm = {
            "jsonSchema" : {
                "title" : "Edit Question config",
                "type" : "object",
                "properties" : {
                    
                }
            }
        };
        var formInputsHere = formInputs;
        if( notNull(formInputs [ $(this).data("form")]) )
            formInputsHere = formInputs[  $(this).data("form") ];
        // if( typeof formInputsHere [ $(this).data("key") ].position == "undefined")
        //  formInputsHere [ $(this).data("key") ].position = "";

        $.each( formInputsHere [ $(this).data("key") ] , function(k,val) { 
            mylog.log("formInputs",k,val); 
            activeForm.jsonSchema.properties[ k ] = {
                label : k,
                value : val
            };
        });

        
        mylog.log("tplCtx formInputs activeForm.jsonSchema.properties",formInputsHere,activeForm.jsonSchema.properties); 
        tplCtx.id = $(this).data("id");
        tplCtx.key = $(this).data("key");
        tplCtx.collection = $(this).data("collection");            
        tplCtx.path = $(this).data("path");
        mylog.log("tplCtx",tplCtx); 
        //alert(tplCtx.collection+":"+tplCtx.path);
        activeForm.jsonSchema.save = function () {  
            tplCtx.value = {};
            $.each ( formInputsHere [ tplCtx.key ] , function(k,val) { 
                tplCtx.value[k] = $("#"+k).val();
            } );
            
            //alert("#"+tplCtx.key+" : "+$( "#"+tplCtx.key ).val());
Tibor Katelbach's avatar
Tibor Katelbach committed
405
            mylog.log("save tplCtx",tplCtx);
Clément Damiens's avatar
 
Clément Damiens committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
            if(typeof tplCtx.value == "undefined")
                toastr.error('value cannot be empty!');
            else {
                dataHelper.path2Value( tplCtx, function(params) { 
                    $("#ajax-modal").modal('hide');
                    location.reload();
                } );
            }
        } 
        dyFObj.openForm( activeForm );
    });

    $(".addQuestion").off().on("click",function() { 
        var activeForm = {
            "jsonSchema" : {
                "title" : "Ajouter une Question",
                "type" : "object",
                "properties" : {
                    label : { label : "Titre de la Question" },
                    placeholder : { label : "Texte dans la Question" },
                    info : { 
                        inputType : "textarea",
                        label : "Information complémentaire sur la Question" },
                    type : { label : "Type de cette question",
                             inputType : "select",
                             options : <?php echo json_encode(Form::$inputTypes); ?>,
                             value : "text" }
                }
            }
        };          
        
        tplCtx.id = $(this).data("id");
        tplCtx.key = $(this).data("key");
        tplCtx.collection = "<?php echo Form::COLLECTION ?>";  
        tplCtx.form = $(this).data("form");           
        
        activeForm.jsonSchema.save = function () {  
            var formInputsHere = formInputs;
            if( notNull(formInputs [tplCtx.form]) )
                formInputsHere = formInputs[ tplCtx.form ];

            var inputCt = (formInputsHere == null) ? "1" : (Object.keys(formInputsHere).length+1);
            if(notNull(formInputsHere[tplCtx.form+inputCt]))
                inputCt = inputCt+"x";
            //alert("inputs."+tplCtx.form+inputCt);
            
            tplCtx.path = "inputs."+tplCtx.form+inputCt;
Tibor Katelbach's avatar
Tibor Katelbach committed
453
            tplCtx.inputId = tplCtx.form+inputCt;
Clément Damiens's avatar
 
Clément Damiens committed
454 455 456 457
            tplCtx.value = {
                label : $("#label").val(),
                type : $("#type").val()
            };
Tibor Katelbach's avatar
Tibor Katelbach committed
458 459 460 461 462 463
            if( $("#placeholder").val() != "" )
                tplCtx.value.placeholder = $("#placeholder").val();
            if( $("#info").val() != "" )
                tplCtx.value.info = $("#info").val();


Clément Damiens's avatar
 
Clément Damiens committed
464
            delete tplCtx.form;
Tibor Katelbach's avatar
Tibor Katelbach committed
465
            mylog.log("activeForm save tplCtx",tplCtx);
Clément Damiens's avatar
 
Clément Damiens committed
466 467 468 469
            if(typeof tplCtx.value == "undefined")
                toastr.error('value cannot be empty!');
            else {
                dataHelper.path2Value( tplCtx, function(params) { 
Tibor Katelbach's avatar
Tibor Katelbach committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
                    if(tplCtx.value.type == "tpls.forms.cplx.openDynform" ){
                        delete tplCtx.path;
                        delete tplCtx.id;
                        tplCtx.value = {
                            id : tplCtx.inputId,
                            name : tplCtx.value.label,
                            type : "dynform"
                        };
                        mylog.log("create openDynform save tplCtx",tplCtx);
                        dataHelper.path2Value( tplCtx, function(params) { 
                            $("#ajax-modal").modal('hide');
                            urlCtrl.loadByHash(location.hash);
                        } );

                    } else {
                        $("#ajax-modal").modal('hide');
                        urlCtrl.loadByHash(location.hash);
                    }

Clément Damiens's avatar
 
Clément Damiens committed
489 490 491 492 493 494 495 496 497 498 499 500
                } );
            }

        }

        dyFObj.openForm( activeForm );
    });

    
<?php } ?>
    
});
Tibor Katelbach's avatar
Tibor Katelbach committed
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

function saveLinks(id,linkType,uid,callB){  
    var today = new Date();
    today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear()+ ' ' + today.getHours()+ ':' + today.getMinutes();
    //alert(uid+":"+today);
    if( typeof answerObj.links == "undefined" ||
        typeof answerObj.links[linkType] == "undefined" || 
        typeof answerObj.links[linkType][uid] == "undefined" //||typeof answerObj.links[linkType][uid] != today 
        )
    {
        var link = {
            collection : "answers",
            id : answerObj._id.$id,
            path : "links."+linkType+"."+uid,
            value : 1 //today
        };

        mylog.log("saveLinks", link );
          
        dataHelper.path2Value( link , function(params) { 
            mylog.log("saveLinks saved",params );
            if(typeof callB == "function" )
                callB();
        } );
525 526
    } else if(typeof callB == "function" )
        callB();
Tibor Katelbach's avatar
Tibor Katelbach committed
527
}
Clément Damiens's avatar
 
Clément Damiens committed
528 529
</script>

Raph El's avatar
Raph El committed
530
<?php } ?>