>  기사  >  백엔드 개발  >  케이크PHP 양식

케이크PHP 양식

WBOY
WBOY원래의
2024-08-29 12:58:52904검색

CakePHP는 동적 프로그래밍을 처리하는 데 사용되는 오픈 소스 도구입니다. HTML 양식을 처리하기 위해 개발자에게 다양한 유형의 내장 태그를 제공합니다. form은 HTML form을 안정적으로 처리하기 위해 CakePHP에서 제공하는 태그 중 하나이며, 다른 PHP 프레임워크와 쉽고 안전하게 동일하다고 할 수 있습니다. 한 가지 장점은 CakePHP를 사용하여 HTML의 다양한 요소를 생성할 수 있다는 것입니다. CakePHP에서는 내장 태그와 메서드를 사용하여 필요한 모든 유효성 검사와 다양한 레이아웃을 통해 요구 사항에 따라 양식을 쉽게 생성할 수 있습니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

CakePHP 형식이 무엇인가요?

구조에는 CakePHP에서 다양한 활동을 수행하기 위한 강력한 구조 라이브러리 기록이 포함되어 있습니다. 양식은 승인, 다시 채우기 및 구성을 간소화할 수 있도록 이러한 방식으로 구조를 효과적으로 생성하는 데 중점을 둡니다. Form에는 형식 구성 도구에서 구조를 만드는 데 사용할 구조의 다양한 레이블이 있습니다. 게다가 양식은 유연하므로 특정 결과를 실행하기 위해 올바른 구두점과 전략을 활용하여 표시해야 하는 구조의 거의 모든 작업을 수행합니다. 구조를 만들기 위해서는 엄청난 양의 코드를 작성해야 하기 때문에 HTML 코드보다 한 줄이면 충분하지만, Form에서는 구조에 대한 간단한 문법을 ​​작성해야 합니다.

CakePHP 양식을 만드는 방법은 무엇입니까?

이제 다음과 같은 예제를 통해 CakePHP에서 양식을 만드는 방법을 살펴보겠습니다. 먼저 양식을 만들어야 합니다. 일반적으로 양식 클래스를 사용할 때 하위 클래스도 정의해야 한다는 것을 알고 있습니다.

예:

namespace App\Form;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
class sampleForm extends Form
{
protected function buildSchema(Schema $schema): Schema
{
return $schema->addField('Emp Name', 'string')
->addField('Emp Email', ['type' => 'string'])
->addField('Emp Address', ['type' => 'text']);
}
public function validationDefault(Validator $valid): Validator
{
$valid->minLength('Emp Name', 20)
->Emp Email('email');
return $valid;
}
protected function _run(array $data): bool
{
// Send an email.
return true;
}
}

설명

위의 예에서는 buildSchema, defaultvalidation, run의 세 가지 방법을 표시된 대로 사용합니다.

이제 다음과 같이 컨트롤러 내부에서 요청 데이터를 처리하기 위한 코드를 작성해야 합니다.

namespace App\Controller;
use App\Controller\AppController;
use App\Form\ sampleForm;
class SampleController extends AppController
{
public function index()
{
$sample= new sampleForm ();
if ($this->request->is('post')) {
if ($sample->execute($this->request->getData())) {
$this->Flash->success( ‘Welcome Done’);
} else {
$this->Flash->error('There is Problem');
}
}
$this->set('sample', $sample);
}
}

그런 다음 양식 값을 설정해야 하며 마지막으로 요구 사항에 따라 양식을 사용하여 HTML을 생성해야 합니다.

이제 이해를 돕기 위해 다음과 같은 예를 들어보겠습니다.

먼저 다음과 같이 Routes.php를 구성해야 합니다.

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
//$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
$builder->connect('register',['controller'=>'ContactForm','action'=>'index']);
$builder->fallbacks();
});

이제 위 코드와 유사한 컨트롤러 파일을 생성해야 하므로 컨트롤러 파일을 생성하고 다음과 같은 코드를 작성합니다.

<?php
namespace App\Controller;
use App\Controller\AppController;
class ContactFormController extends AppController{
public function index(){
$country = array('India',England',Canada');
$this->set('country',$country);
$gender = array('Male','Female');
$this->set('gender',$gender);
}
}
?>

설명

위 코드에서는 국가, 성별 등 연락처 정보에 대한 코드를 작성했습니다. 이제 인덱스 파일을 생성하고 다음 코드를 작성해 보세요.

<?php
echo $this->Form->create(NULL,array('url'=>'/sampleForm'));
echo '<label for="name">Name</label>';
echo '<label for="country">Country</label>';
echo $this->Form->select('country',$country);
echo '<label for="gender">Gender</label>';
echo $this->Form->radio('gender ',$gender);
echo '<label for="address">Address</label>';
echo $this->Form->text ('address');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>

위 코드를 실행하면 다음 스크린샷과 같은 화면이 나옵니다.

케이크PHP 양식

다음 스크린샷과 같이 인도와 같은 국가를 선택했다고 가정해 보겠습니다.

케이크PHP 양식

이제 다음 스크린샷과 같이 이름과 주소 등 세부 정보를 입력하세요.

케이크PHP 양식

이제 제출 버튼을 클릭하면 환영 메시지를 받게 됩니다.

CakePHP 양식 함수

이제 다음과 같이 CakePHP의 폼 함수를 살펴보겠습니다.

옵션 선택

배열 요소를 반환하는데 사용됩니다.

구문

selectOptions( array $specifiedarrayelement(), array $parentsarrayelement(),
boolean $showParentsnull, array $attributesarray() )

설명

위 구문에서는 요소 형식, 상위 요소 그룹, 다양한 HTML 속성 등 다양한 매개변수와 함께 selectOption 함수를 사용합니다. 기본적으로 배열을 반환합니다.

선택

형식이 지정된 요소를 선택하는 데 사용됩니다.

구문

select( string $Specified Name field, array $required options of array(), array $specified attributes array() )

설명

위 구문에서는 선택을 사용하여 다양한 매개변수로 작동하고 지정된 이름 필드를 사용하여 이름 속성을 선택하며 배열도 요소를 선택하는 데 사용되며 선택한 요소를 반환합니다.

버튼

타입이 있는 버튼을 만들 때 사용됩니다.

구문

Button(string $specified name, array $optionsarray() )

설명

버튼의 비문입니다. 자연스럽게 HTML로 인코딩되지 않습니다. 선택 항목과 HTML의 클러스터가 할당되어 버튼 태그를 반환합니다.

체크박스

이 기능을 사용하여 요구 사항에 따라 양식 내부에 확인란을 만듭니다.

구문

Checkbox(string $Specifed name field, array $optionsarray() )

설명

In the above syntax, we use a checkbox function with different parameters such as name and array attributes. It returns the text input element.

Create

It is used to return the returned form element.

Syntax

create( mixed $nullmodel value , array $array() )

Explanation

Here we need to specify the name of the model and the array of specified HTML attributes.

File

By using this function, we can create the file and return the generated file.

Hidden

It is used to create the hidden file and returns the generated hidden input.

Input

It is used to create input elements and return the form widget.

Radio

It is used to create a set of radio buttons and returns the radio widget.

Submit

It is used to create a submit button element and it returns the HTML submit.

Values

Here we can set the default value for form by using setData() method as per our requirement as shown in the following code.

namespace App\Controller;
use App\Controller\AppController;
use App\Form\ContactForm;
class SampleController extends AppController
public function index()
{
$sample = new SampleForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->getData())) {
$this->Flash->success(' Welcome Done ');
} else {
$this->Flash->error('There is Problem');
}
}
if ($this->request->is('get')) {
$contact->setData([
'Emp of name' => 'sam',
Emp'email' => [email protected]'
]);
}
$this->set('sample', $sample);
}
}

Conclusion

We hope from this article you learn more about the CakePHP form. From the above article, we have taken in the essential idea of the CakePHP form and we also see the representation and example of the CakePHP form. From this article, we learned how and when we use the CakePHP form.

위 내용은 케이크PHP 양식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:CakePHP 인증다음 기사:CakePHP 인증