
PHP 프레임워크 – Symfony – 폼 처리와 검증
안녕하세요 여러분 😊
이번 시간에는 Symfony에서 웹 애플리케이션을 만들 때 거의 필수적으로 사용되는 기능인 **폼(Form) 처리와 검증(Validation)**에 대해 배워보겠습니다!
폼은 사용자와 서버가 소통하는 입구예요.
마치 우체통처럼 사용자 입력을 받아 서버에 전달해주는 역할을 하죠📬
그리고 검증은 마치 그 편지를 뜯어보기 전에 봉투가 찢어지지 않았는지, 주소가 잘 적혀 있는지 확인하는 단계랍니다!
1. Symfony 폼 컴포넌트란?
Symfony는 자체적으로 아주 강력한 Form 컴포넌트를 제공해요.
이걸 이용하면 HTML <form>
을 자동으로 만들고,
사용자의 입력값을 객체와 연결해서 쉽게 검증하고 처리할 수 있답니다!
2. Form 컴포넌트 설치
composer require symfony/form
composer require symfony/validator
composer require symfony/twig-bundle
form
: 폼 생성을 위한 컴포넌트validator
: 입력값 검증 기능twig-bundle
: 뷰에서 폼 렌더링을 위한 템플릿 엔진
3. 간단한 예제 시나리오
사용자가 상품(Product)을 등록하는 폼을 만들어볼게요.
- 필드: 이름(name), 가격(price), 설명(description)
4. Entity 클래스 준비
// src/Entity/Product.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Product
{
#[Assert\NotBlank]
private string $name;
#[Assert\Positive]
private float $price;
private ?string $description = null;
// getter/setter 생략
}
여기서
@Assert\NotBlank
,@Assert\Positive
는 유효성 검사를 위한 제약 조건입니다.
5. Form 클래스 생성
php bin/console make:form
입력: ProductType
→ Product
클래스 선택
생성된 폼 클래스는 다음과 같아요:
// src/Form/ProductType.php
namespace App\Form;
use App\Entity\Product;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('price', MoneyType::class)
->add('description', TextareaType::class, [
'required' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Product::class,
]);
}
}
6. 컨트롤러에서 폼 처리하기
// src/Controller/ProductController.php
use App\Entity\Product;
use App\Form\ProductType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/product/new', name: 'product_new')]
public function new(Request $request): Response
{
$product = new Product();
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 데이터 저장 or 처리
// 예: 데이터베이스에 저장
return new Response('폼이 성공적으로 제출되었습니다!');
}
return $this->render('product/new.html.twig', [
'form' => $form->createView(),
]);
}
7. 템플릿에서 폼 출력하기
{# templates/product/new.html.twig #}
<h1>상품 등록</h1>
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.price) }}
{{ form_row(form.description) }}
<button type="submit">제출</button>
{{ form_end(form) }}
8. 폼 유효성 검증 처리
폼이 제출되면 다음과 같은 순서로 처리돼요:
- 사용자의
POST
데이터 수신 $form->handleRequest($request)
로 데이터 바인딩$form->isSubmitted()
로 제출 여부 확인$form->isValid()
로 유효성 검사 수행- 실패 시 오류 메시지 출력, 성공 시 저장 또는 처리
9. 오류 메시지 표시하기
Twig는 자동으로 오류 메시지를 표시해줘요:
{{ form_errors(form.name) }}
또는 전체 폼 에러를 출력하려면:
{{ form_errors(form) }}
10. 커스텀 검증 메시지
#[Assert\NotBlank(message: "이름을 입력해주세요.")]
private string $name;
message
속성을 활용하면 더 친절한 메시지를 사용자에게 보여줄 수 있어요 😊
11. 폼 필드 옵션들
옵션 | 설명 |
---|---|
label |
라벨 텍스트 설정 |
required |
필수 여부 설정 |
attr |
HTML 속성 설정 (예: placeholder, class 등) |
constraints |
유효성 검증 조건 추가 |
예:
->add('name', TextType::class, [
'label' => '상품명',
'required' => true,
'attr' => ['placeholder' => '상품명을 입력하세요'],
'constraints' => [new Assert\Length(['min' => 3])]
])
주의할 점 ✅
항목 | 설명 |
---|---|
handleRequest() 필수 |
이 메서드를 호출하지 않으면 사용자 입력을 처리할 수 없음 |
Entity 필드 이름과 폼 필드 이름은 일치해야 바인딩 가능 | |
유효성 검사는 isValid() 로 꼭 확인해야 함 |
|
템플릿에서 form_start , form_end 로 감싸야 정상 렌더링됨 |
|
JavaScript 검증은 별도로 적용해야 함 (서버 측 검증은 필수!) |
요약 정리 🎯
항목 | 명령어/기능 |
---|---|
폼 생성 | php bin/console make:form |
요청 처리 | $form->handleRequest($request) |
유효성 검사 | $form->isSubmitted() + $form->isValid() |
렌더링 | {{ form_start(form) }} ... {{ form_end(form) }} |
오류 표시 | {{ form_errors(form.field) }} |
검증 어노테이션 | #[Assert\NotBlank] , #[Assert\Email] 등 |
마무리하며 😊
Symfony의 폼 컴포넌트는 다소 복잡해 보일 수 있지만,
익숙해지면 정말 편리하게 사용자 입력을 받고 검증하고 처리할 수 있어요!
사용자가 제출한 데이터가 서버로 안전하게 도착하도록,
그리고 그 안에 실수나 오류가 없도록 꼼꼼하게 체크하는 것이 개발자의 책임이죠 💪
다음 시간에는 Symfony의 사용자 인증과 권한 관리에 대해 배워보겠습니다.
그럼 오늘도 즐거운 코딩 되세요~ ✨📨💻