我有如下僱員登記表,有一個與兩個實體關聯的表單。我需要讓一個實體可選 - symfony 2?
namespace Hrm\EmployeeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Hrm\UserBundle\Form\User\UserForm;
class EmpForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('id','hidden');
$builder->add('firs_name', 'text');
$builder->add('middle_name', 'text');
$builder->add('last_name', 'text');
$builder->add('user', new UserForm(), array('required' => false));
}
public function getName()
{
return 'EmpForm';
}
}
也我有如下用戶登錄表單,
namespace Hrm\UserBundle\Form\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class UserForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add("id","hidden",array("required"=>false));
$builder->add("userName","text",array("label"=>"Username"));
$builder->add("password","password",array("label"=>"Password"));
$builder->add("confirmPassword","password",array("property_path" =>
false,"label"=>"Confirm Password"));
$builder->add("email","email",array("label"=>"Email"));
}
public function getName()
{
return 'user';
}
}
僱員YML文件將作爲跟隨,
Hrm\EmployeeBundle\Entity\Employee:
type: entity
table: employee
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
firs_name:
type: string
length: '255'
default: null
middle_name:
type: string
length: '255'
default: null
last_name:
type: string
length: '255'
default: null
oneToOne:
User:
targetEntity: Hrm\UserBundle\Entity\User
cascade: ["remove", "persist"]
joinColumn:
name: login_id
referencedColumnName: id
nullable: true
lifecycleCallbacks: { }
員工控制器就是這樣,
public function addEmployeeAction(Request $request) {
$employee = new Employee();
$user = new User();
$employee->setUser($user);
$form = $this->createForm(new EmpForm(), $employee);
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($employee);
$em->flush();
return $this->redirect($this->generateUrl('HrmEmployeeBundle_homepage'));
}
}
return $this->render('HrmEmployeeBundle:Pages:add.html.twig', array(
'form' => $form->createView(), 'status' => 'addEmployee',
));
}
所以我需要做的是,下列選項應該可用,
- 填寫員工登記詳細信息,並創建一個登錄(這已經完成)
- 只填寫員工登記信息,並不需要創建爲此登錄。
所以第二個選項不適合我,它說Column'username'不能爲空 我該如何擺脫這個問題?
我不明白你的問題。這不是很清楚。 – Flukey