Wj.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace app\h5\controller;
  3. use think\Controller;
  4. use think\Db;
  5. use think\Exception;
  6. class Wj extends Controller
  7. {
  8. public function index(){
  9. $id = input('id');
  10. if(!$id){
  11. return $this->fetch('h5/error');
  12. }else{
  13. $info = db('questionnaire')
  14. ->where('id',$id)
  15. ->find();
  16. if(!$info || $info['enable'] != 1){
  17. return $this->fetch('h5/error');
  18. }else{
  19. db('questionnaire')
  20. ->where('id',$id)
  21. ->setInc('view',1);
  22. $this->assign('info',$info);
  23. return $this->fetch('index/wj');
  24. }
  25. }
  26. }
  27. public function answer(){
  28. $id = input('id');
  29. $answers = input('answer');
  30. if($id <= 0 || !$answers){
  31. $this->error('参数错误');
  32. }
  33. $info = db('questionnaire')
  34. ->where('id',$id)
  35. ->find();
  36. if(!$info || $info['enable'] != 1){
  37. $this->error('问卷停止回收');
  38. }
  39. $curTime = date('Y-m-d H:i:s');
  40. $questions = json_decode($info['questions'],true);
  41. $qarr = [];
  42. foreach ($questions as $k=>$v){
  43. if($v['required'] && empty($answers[$v['id']])){
  44. $this->error('有必做题未完成');
  45. }
  46. if(($v['type'] == 'text'||$v['type'] == 'textarea') && $v['limit'] < mb_strlen($answers[$v['id']])){
  47. $this->error('答题字数超过限制');
  48. }
  49. if($v['type'] == 'checkbox'){
  50. $answer = empty($answers[$v['id']])?'':implode(',',$answers[$v['id']]);
  51. }else{
  52. $answer = empty($answers[$v['id']])?'':$answers[$v['id']];
  53. }
  54. $qarr[] = [
  55. 'create_time' => $curTime,
  56. 'question_id' => $v['id'],
  57. 'questionnaire_id' => $id,
  58. 'answer' => $answer,
  59. 'user_id' => 0,
  60. ];
  61. }
  62. $data = [
  63. 'ip' => $_SERVER['REMOTE_ADDR'],
  64. 'questionnaire_id' => $id,
  65. 'user_id' => 0,
  66. 'create_time' => $curTime,
  67. ];
  68. Db::startTrans();
  69. try{
  70. $questionnaireId = db('questionnaire_record')->insertGetId($data);
  71. if(!$questionnaireId){
  72. throw new Exception('记录保存失败');
  73. }
  74. foreach ($qarr as $k=>$v){
  75. $qarr[$k]['questionnaire_id'] = $questionnaireId;
  76. }
  77. $res = db('questionnaire_record_answer')
  78. ->insertAll($qarr);
  79. if(!$res){
  80. throw new Exception('问题记录保存失败');
  81. }
  82. Db::commit();
  83. $this->success('操作成功');
  84. }catch (Exception $e){
  85. Db::rollback();
  86. $this->error($e->getMessage());
  87. }
  88. }
  89. public function wjsuccess(){
  90. $title = db('config')
  91. ->where('name','web_site_title')
  92. ->value('value');
  93. $this->assign('title',$title);
  94. return $this->fetch('index/success');
  95. }
  96. }