前提・実現したいこと
前提:CakePHP 3.0
現在CakePHP3でSNSを構築しています。
文字のみのアップロード、また、画像のみのアップロードなら
すでに実現できたのですが、文字と画像同時投稿の仕組みが
どうしてもできません。
シンプルな参考コードもみながら、自分のコードに落とし込んでみたのですが
うまくいかなくて手詰まりしている状態です。
私のコードではどこがいけないのでしょうか?
お詳しい方ご教授いただけますでしょうか?
参考にしたサイト
リンク内容
●文字のみで投稿した場合はOK(画像に関するコードコメントアウト)
php
1// エラーのないコード 2// (中略) 3 public function add(){ 4 5 $content = $this->Contents->newEntity(); 6 7 // 画像関連部分ひとまずコメントアウト 8 // $fileName = $this->params['form']['image']; 9 // if($fileName['size'] > 0){ 10 // if($fileName['size']>1000000){ 11 // echo '画像サイズが大き過ぎます'; 12 // }else{ 13 // move_uploaded_file($fileName['tmp_name'],'../webroot/img'.$fileName['name']); 14 // } 15 // } 16 17 $data = [ 18 'user_id' => $this->request->data['Contents']['user_id'], 19 'body' => $this->request->data['Contents']['body'], 20 // 'image' => $fileName['name'], 21 ]; 22 23 $content = $this->Contents->patchEntity($content, $data); 24 if ($this->Contents->save($content)) { 25 return $this->redirect(['action' => 'index']); 26 }else{ 27 return $this->redirect(['action' => 'index']); 28 } 29 }
●[Error]文字と画像を同時に投稿するとデータベースエラーと出ます
データベース(カラム)
php
1// ContentsController.php 2// (中略) 3 public function add(){ 4 $fileName = $this->params['form']['Contents']['image']; 5 if($fileName['size'] > 0){ 6 if($fileName['size']>1000000){ 7 echo '画像サイズが大き過ぎます'; 8 }else{ 9 move_uploaded_file($fileName['tmp_name'],'../webroot/img'.$fileName['name']); 10 } 11 } 12 13 $data = [ 14 'user_id' => $this->request->data['Contents']['user_id'], 15 'body' => $this->request->data['Contents']['body'], 16 'image' => $fileName['name'] 17 ]; 18 19 $content = $this->Contents->patchEntity($content, $data); 20 if ($this->Contents->save($content)) { 21 return $this->redirect(['action' => 'index']); 22 }else{ 23 return $this->redirect(['action' => 'index']); 24 } 25 }
php
1// index.ctp 2// (中略) 3 4<div class="form"> 5 <?= $this->Form->create($data,['type'=>'post','url'=>['action'=>'add','type'=>'file']]) ?> 6 <?= $this->Form->hidden('Contents.user_id',['type'=>'text','value'=>$user_login_id]);?> 7 <?= $this->Form->input( 'Contents.body', ['type' => 'textarea','cols' => 10,'rows' => 1,'placeholder'=>'いまどうしてる?','label' => '' ] ); ?> 8 <?= $this->Form->text('Contents.image',['type'=>'file']); ?> 9 <?= $this->Form->button('ツイート'); ?> 10 <?= $this->Form->end() ?> 11 </div>
回答2件
あなたの回答
tips
プレビュー