我有一份员工登记表,如下所示,
namespace HrmEmployeeBundleForm;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilder;
use HrmUserBundleFormUserUserForm;
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 HrmUserBundleFormUser;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilder;
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文件如下,
HrmEmployeeBundleEntityEmployee:
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: HrmUserBundleEntityUser
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',
));
}
所以我需要做的是以下选项应该可用,
- 填写员工注册详细信息并创建登录名(已完成)
- 只填写员工注册详细信息,不需要为此创建登录名
所以第二个选项对我不起作用,它说列"用户名"不能为空我该如何解决这个问题?
要回答第二个问题,请在addEmployeeAction中,不要在新员工上添加用户,删除以下行:
$user = new User();
$employee->setUser($user);
目前,$employee是用一个没有用户名的空用户保存的,所以MySQL很不高兴!通过删除这些行,只有在填写了表单的情况下才会创建用户!
如果要设置SQL字段optionnal,请添加可为null的选项true:
oneToOne:
User:
targetEntity: SysUserBundleEntityUser
cascade: ["persist"]
joinColumn:
name: login_id
referencedColumnName: id
nullable: true
但在您的情况下,似乎您注册了一个没有用户名的用户,这是不合乎逻辑的。。。也许用户名字段工作不正常,请给我们更多的细节。