我知道它反对框架使实体容器知道,但这是一个特例,我有一个信用卡实体,我想这样做:
/**
* @return mixed
*/
public function getNumber()
{
$number = $this->number;
$crypt = base64_decode($number);
$number = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypt, MCRYPT_MODE_ECB);
return trim($number);
}
/**
* @param $number
* @return $this
*/
public function setNumber($number)
{
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $number, MCRYPT_MODE_ECB);
$number = trim(base64_encode($crypt));
$this->number = $number;
return $this;
}
我希望$ key是来自parameters.yml的秘密,因为我不想将它保存在代码中。
当我使用FormType时,我无法将其作为参数传递,因为表单类型在绑定请求时不会传递它。
$credit_card = new CreditCard();
$credit_card->setCustomer($customer);
$payment_form = $this->createPaymentForm($credit_card);
$payment_form->handleRequest($request);
答案 0 :(得分:1)
从您的实体中删除数据修改,并将其添加到您的FormType。
public function getNumber()
{
return $this->number;
}
public function setNumber($number)
{
$this->number = $number;
return $this;
}
让你的FormType
将参数作为参数。
class CreditCardType extends AbstractType {
private $key;
public function __construct($key) {
$this->key = $key;
}
// ...
// Listen on the PRE_BIND event to update your value before binding
$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event)
{
$data = $event->getData();
$number = $data['number'];
$crypt = $this->encryptNumber($number);
$data['number'] = $crypt;
$event->setData($data);
});
public function encryptNumber($key, $number)
{
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $number, MCRYPT_MODE_ECB);
$number = trim(base64_encode($crypt));
return $number;
}
}
现在,在您的createPaymentForm中,将参数添加到FormType
实例中,如下所示:
$param = $this->container->getParameter('yourkeyparam');
$form = $this->createForm(new CreditCardType($param), $credit_card, array());
希望这就是你所需要的。