formbuilder.php 19.8 KB
Newer Older
Clément Damiens's avatar
 
Clément Damiens committed
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
<?php   
//var_dump($answer);
$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;
        }
        foreach ( $form["inputs"] as $key => $input) {
            if(isset($input["position"])){
                $orderInputs[(int)$input["position"]] = $input;
                $orderInputsKeys[(int)$input["position"]] = $key;
            }
        }

        $inV = $form["inputs"];
        foreach ( $form["inputs"] as $key => $input) {
            if(!isset($input["position"])){
                unset( $form["inputs"][$key]);
            }else{
                unset( $inV[$key]);
            }
        }


        if(!function_exists('sortByPosOrder'))
        {
            function sortByPosOrder($a, $b) {
                return (int)$a['position'] - (int)$b['position'];
            }
        }

        uasort($form["inputs"], 'sortByPosOrder');



        $form["inputs"] = array_merge($form["inputs"], $inV);

    //nouvelle repositionnement




    //fin nouvelle repositionnement
   //echo json_encode($form["inputs"]) ;

    echo "<ul class='questionList'>";
    foreach ( $form["inputs"] as $key => $input) { 

Raph El's avatar
Raph El committed
58
        $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
59
            " <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
60

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

Clément Damiens's avatar
 
Clément Damiens committed
63 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 95 96 97 98 99 100
        $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);
        $p = [ 
            "input"     => $input,
            "type"      => $input["type"], 
            "answerPath" => $answerPath,
            "answer"        => $answer,
            "answers"   => $answers ,//sub answers for this input
            "label"     => $input["label"] ,//$ct." - ".$input["label"] ,
Tibor Katelbach's avatar
Tibor Katelbach committed
101
            "titleColor"=> (isset($this->costum["colors"]["pink"])) ? $this->costum["colors"]["pink"] : "#16A9B1",
Clément Damiens's avatar
 
Clément Damiens committed
102 103 104 105 106
            "info"      => isset($input["info"]) ? $input["info"] : "" ,
            "placeholder" => isset($input["placeholder"]) ? $input["placeholder"] : "" ,
            "form"      => $form,
            "key"       => $key, 
            "kunik"     => $kunik,
Raph El's avatar
Modif  
Raph El committed
107
            "mode"     => $mode,
Clément Damiens's avatar
 
Clément Damiens committed
108
            "canEdit"   => $canEdit,
109
            "canEditForm" => @$canEditForm,
Raph El's avatar
Modif  
Raph El committed
110
            "editQuestionBtn" => @$editQuestionBtn,
Clément Damiens's avatar
 
Clément Damiens committed
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
            "saveOneByOne" => $saveOneByOne,
            "wizard"    => (isset($wizard) && $wizard == true) ,
            "el" => $el ];

        if(isset($tplT[2]) && $tplT[2] == "select" && isset($input["options"]))
            $p["options"] = $input["options"];
        
        if($input["type"] == "tags") 
            $initValues[$key] = $input;
        
        echo "<li id='question".$key."' class='questionBlock'  data-id='".$form['_id']."' data-path='inputs.".$key.".position' data-key='".$key."' data-form='".$form["id"]."' style='margin-bottom:0px'>";
            $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
Test  
Raph El committed
137
if ($canEditForm) { ?>
Clément Damiens's avatar
 
Clément Damiens committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
<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>
<?php } ?>

<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");
    
    <?php if(!$saveOneByOne){ 
         //if form contains just one cplx input then all saves are made oneByone?>
    $( "#openFormSubmit" ).off().on( "click", function( event ) {
      event.preventDefault();
      $("#openFormSubmit").html("<i class='fa fa-spin fa-spinner'></i>Veuillez Patienter nous traitons vos données")
      var answer = {
        value:{
            formId : "<?php echo $formId ?>",
            type : "openForm",
            "answers":{},
            user : userId,
            parentSlug : "<?php echo $el["slug"] ?>"
        }
      };
      $("form#formQuest :input").each(function(){
        if(typeof $(this).attr("id") != "undefined" && $(this).val() != "" )
            answer.value.answers[ $(this).attr("id") ] = $(this).val();
        });
Tibor Katelbach's avatar
Tibor Katelbach committed
169
      mylog.log("#openFormSubmit", answer );
Clément Damiens's avatar
 
Clément Damiens committed
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
      answer.collection = "answers";
      if($(this).data("id"))
        answer.id = $(this).data("id");
      
      dataHelper.path2Value( answer , function(params) { 
            $("form#formQuest").html("<h2>Merci de votre participation!!</h2><a href='javascript:;'>Voir toutes les réponses</a>");
            //location.reload();
        } );
    });
    <?php } else {
        //here answer allready exists is only completed by small updates
        ?>

    $( ".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
203
            mylog.log("saveOneByOne",$(this).attr("id"), answer );
Clément Damiens's avatar
 
Clément Damiens committed
204 205
              
            dataHelper.path2Value( answer , function(params) { 
Tibor Katelbach's avatar
Tibor Katelbach committed
206 207 208
                toastr.success('saved');
                saveLinks(answerObj._id.$id,"updated",userId);
            } );
Clément Damiens's avatar
 
Clément Damiens committed
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 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
        } else {
            toastr.error('answer cannot be empty, on saveOneByOne!');
        }
    });

    <?php } ?>

    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
    $( ".questionList" ).sortable({
        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
327
            mylog.dir(tplCtx );
Clément Damiens's avatar
 
Clément Damiens committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 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
              
              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
376
                        mylog.log("incPositions",k,inp.position)
Clément Damiens's avatar
 
Clément Damiens committed
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 405 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
                        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
434
            mylog.log("save tplCtx",tplCtx);
Clément Damiens's avatar
 
Clément Damiens committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
            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;
            tplCtx.value = {
                label : $("#label").val(),
                placeholder : $("#placeholder").val(),
                info : $("#info").val(),
                type : $("#type").val()
            };
            delete tplCtx.form;
Tibor Katelbach's avatar
Tibor Katelbach committed
489
            mylog.log("activeForm save tplCtx",tplCtx);
Clément Damiens's avatar
 
Clément Damiens committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
            if(typeof tplCtx.value == "undefined")
                toastr.error('value cannot be empty!');
            else {
                dataHelper.path2Value( tplCtx, function(params) { 
                    $("#ajax-modal").modal('hide');
                    //location.href = location.origin+location.pathname+"/form/<?php echo $formId ?>";
                    location.reload();
                } );
            }

        }

        dyFObj.openForm( activeForm );
    });

    
<?php } ?>
    
});
Tibor Katelbach's avatar
Tibor Katelbach committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

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();
        } );
533 534
    } else if(typeof callB == "function" )
        callB();
Tibor Katelbach's avatar
Tibor Katelbach committed
535
}
Clément Damiens's avatar
 
Clément Damiens committed
536 537
</script>