动态嵌入表单symfony的更好方法是什么?
我一直在使用Symfony的表单框架。但想知道是否有人有更好的方法来动态地嵌入表单。动态嵌入表单symfony的更好方法是什么?
问题出在我嵌入表单时(见底部),我需要给它一个数组索引,因为Fabian解释了sfForm对象如何在本文Advanced forms中像多维数组。
如果我想给用户点击一个按钮,并嵌入另一种形式的能力,我怎么能实现以下,如果他们点击按钮多次:
<input type="parent[child][]" />
<input type="parent[child][]" />
<input type="parent[child][]" />
...重复多少时间用户点击一个按钮。我可以使用快速的JavaScript来复制和粘贴DOM中的表单元素。
而不是这样的:
<input type="parent[child][1]" />
<input type="parent[child][2]" />
<input type="parent[child][3]" />
...反复多次的用户怎么点击一个按钮。需要JavaScript方法来计算用户单击按钮的次数,即设置正确的数组索引。还需要Ajax调用一个嵌入了此数组索引的PHP函数。如果可能,我想避免使用这种方法。
如何嵌入表单:
$parentForm = new ParentForm($parent)
$child = new child();
$child->setParent($parent);
$sfForm = new sfForm();
$sfForm ->embedForm($someIndex, new ChildForm($child));
$parentForm->embedForm('child', $sfForm);
嘿,我找到了一种方法!这里棘手的部分是重写sfWidgetFormSchema :: generateName方法。
class myWidgetFormSchema extends sfWidgetFormSchema
{
/**
* Generates a name.
*
*/
public function generateName($name)
{
$name = parent::generateName($name);
//match any [number] and replace it with []
$name = preg_replace('/\[\d+\]/','[]', $name);
return $name;
}
}
现在,您只需要将其设置为您的'包装'形式。下面是我的例子有“法师有许多奴隶”模式:
public function configure()
{
$this->getWidgetSchema()->setFormFormatterName('list');
$this->widgetSchema->setNameFormat('master[%s]');
$slavesForm = new sfForm();
$slavesForm->setWidgetSchema(new myWidgetFormSchema);
$slavesCount = $this->getOption('slaves_count', 2);
for ($i = 0; $i < $slavesCount; $i++)
{
$slave = new Slave();
$slave->Master = $this->getObject();
$form = new SlaveForm($slave);
$slavesForm->embedForm($i, $form);
}
$this->embedForm('new_slaves', $slavesForm);
}
注意“slaves_count”选项,我从executeCreate经过是这样的:
public function executeCreate(sfWebRequest $request)
{
$schema = $this->getRequest()->getParameter('master');
$this->form = new MasterNewForm(null, array('slaves_count'=> count($schema['new_slaves'])));
$this->processForm($request, $this->form);
$this->setTemplate('new');
}
现在你可以很容易地使用jQuery克隆行不用担心索引!干杯。
谢谢你。 Geeez抱歉花了我很长时间来投票。我更喜欢允许用户使用jQuery克隆行。更好的..... – 2011-05-21 00:46:02
我认为你可以在ahDoctrineEasyEmbeddedRelationsPlugin http://www.symfony-project.org/plugins/ahDoctrineEasyEmbeddedRelationsPlugin 看看也许这将是有益的,即使你并不需要嵌入主义形式相关的记录。
根据我的经验,我只听到了AJAX方法 - 事实上,我的工作这样的模块上了。你为什么避免这个动机? – yitznewton 2011-03-06 02:42:01
我意识到可以在不使用AJAX的情况下复制JS代码中的AJAX功能 - 所有的AJAX都会返回一堆带有表单域的HTML,例如, http://pastebin.com/KwXHcJ3Q。不知道这是否解决您的问题。 – yitznewton 2011-03-06 03:20:08