0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Symfony】エンティティからデータを画面表示する方法

Posted at

はじめに

PHPフレームワーク「Symfony」は、MVCモデルを採用したアーキテクチャです。
そこで今回は、エンティティクラスからのGetterやSetterを使ってデータ表示してみます。

完成イメージ

名前、年齢、メールアドレスを入れてみます。
symfony6.png

各データを入れたらClickボタンを押下します。
symfony7.png

画面上部に送信データを表示します。
symfony8.png

ソースコード

フロントエンドはこんな感じです。

index.html.twig
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>データの取得:{{ data }}</p>
    <form action='/hello' method='post'>
        Name:<input type="text" name="name"/>
        Age:<input type="Number" name="age"/>
        Email:<input type="text" name="mail"/>
        <input type='submit' value='Click'/>
    </form>
</body>
</html>

サーバサイドでは、リクエストデータをエンティティクラスのsetXX()関数を使って値を詰めて画面に返すという処理にしています。

HelloController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class HelloController extends AbstractController
{
    /**
     * @Route("/hello",name="hello")
     */
    #[Route('/hello',name:'hello')]
    public function index(Request $request,SessionInterface $session)
    {
        //MyDataインスタンスを生成する
        $data = new MyData();

        $person = new Person();
        $person->setName('taro')
               ->setAge(36)
               ->setMail('taro@yamada.com');

        //リクエストされた値をセットする
        $name = $request->get('name');
        $age = $request->get('age');
        $mail = $request->get('mail');
        $person->setName($name)->setAge($age)->setMail($mail);
    
        $form = $this->createFormBuilder($person)
            ->add('name',TextType::class)
            ->add('age',IntegerType::class)
            ->add('mail',EmailType::class)
            ->add('save',SubmitType::class,['label'=>'Click'])
            ->getForm();
        
        //リクエストされた値をセットする
        //$data->setData($request->get('data'));

        if($request->getMethod() == 'POST'){
            $form->handleRequest($request);

            //$data = $form->getData();
            $obj = $form->getData();
            $msg = 'Name:'.$obj->getName().' '
            .'Age:'.$obj->getAge().' '
            .'Email:'.$obj->getMail();
            /*
            if($data == '!'){
                $session->remove('data');
            }else{
                $session->set('data',$data->getData());
            }
            */
 
        }else{
            $msg = 'お名前をどうぞ';
        }
        
        // Twigテンプレートにフォームとメッセージを渡す
        return $this->render('hello/index.html.twig', [
            'title' => 'データを取得するアプリ',
            'data'=>$msg,
            //'data'=>$session->get('data'),
            'form'=>$form->createView(),
        ]);
  
    }

    #[Route('/notfound',name:'notfound')]
    public function notfound(Request $request)
    {
        $content = <<< EOM
        <html><head><title>ERROR</title></head>
        <body><h1>ERROR! 404</h1>
        </body></html>
        EOM;
        $response = new Response(
            $content,
            Response::HTTP_NOT_FOUND,
            array('content-type'=>'text/html')
        );
        return $response;
    }

    #[Route('/error',name:'error')]
    public function error(Request $request)
    {
        $content = <<< EOM
        <html><head><title>ERROR</title></head>
        <body><h1>ERROR! 500</h1>
        </body></html>
        EOM;

        $response = new Response(
            $content,
            Response::HTTP_INTERNAL_SERVER_ERROR,
            array('content-type'=>'text/html')
        );
        return $response;
    }

    #[Route('/other',name:'other')]
    public function other(Request $request)
    {
       $input = $request->request->get('input');
       $msg = 'こんにちは、'.$input.'さん。';
       return $this->render('hello/index.html.twig',[
        'title'=>'Hello',
        'message'=>$msg
       ]);
    }   
}

class Person{
    protected $name;
    protected $age;
    protected $mail;

    public  function getName(){
        return $this->name;
    }

    public function setName($name){
        $this->name = $name;
        return $this;
    }

    public  function getAge(){
        return $this->age;
    }

    public function setAge($age){
        $this->age = $age;
        return $this;
    }

    public  function getMail(){
        return $this->mail;
    }

    public function setMail($mail){
        $this->mail = $mail;
        return $this;
    }
}

class MyData
{
    protected $data = '';
    public function getData()
    {
        return $this->data;
    }

    public function setData($data)
    {
        $this->data = $data;
    }
}

ざっくりですが、エンティティクラスを使ってデータを画面表示させることができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?