Symfony CMF隐藏表单的父文档字段

时间:2015-06-18 14:51:28

标签: symfony-cmf symfony2-forms

如何在表单中隐藏父文档字段?我有一些块将被修复,不想显示父文档字段。我已经尝试将css类或内联样式传递给字段,但在渲染字段后它不会出现。

尝试1

示例代码:

->add(
    'parentDocument',
    'doctrine_phpcr_odm_tree',
    array('attr' => ['style' => 'display:none !important'], 'root_node' => $this->getRootPath(), 'choice_list' => array(), 'select_root_node' => true)
)

尝试2

我还尝试隐藏字段,在字段中传递字符串作为默认数据,设置prepersist事件以覆盖需要父文档的字符串。虽然这对于未嵌入时的块效果很好,但它也会在幻灯片块上触发副作用,除非孩子的父文档字段存在,否则我无法保存子块。

子块的示例代码:

形式:

->with('form.group_general')
        ->add('parentDocument', 'hidden', ['required' => false, 'data' => 'filler'])
        ->add('name', 'hidden', ['required' => false, 'data' => 'filler'])
        ->end();

Prepersist:

public function prePersist($document)
{
    parent::prePersist($document);
    $this->initialiseDocument($document);
}

private function initialiseDocument(&$document)
{
    $documentManager = $this->getModelManager();
    $parentDocument = $documentManager->find(null, $this->getRootPath());

    $document->setParentDocument($parentDocument);
    $slugifier = new Slugify();
    $document->setName($slugifier->slugify($document->getTitle()));
}

错误:

    ERROR - 
Context: {"exception":"Object(Sonata\\AdminBundle\\Exception\\ModelManagerException)","previous_exception_message":"Warning: get_class() expects parameter 1 to be object, string given"}

对于尝试2的总结,当子项的父文档字段保留为默认值时,幻灯片显示块正常工作。但我想隐藏那个领域!

1 个答案:

答案 0 :(得分:0)

这可以忽略,请参阅下面的编辑

我弄清楚尝试的问题是什么。我认为当父母一直存在时会触发孩子的prepersist事件但事实证明并非如此。只调用了父母的prepersist事件。

所以在我的情况下,我使用文本'填充'填充了孩子的parentDocument属性。由于未调用prepersist事件,因此未被覆盖到文档对象。因此提到错误。因此,我修改了父亲的perpersist事件,以循环到其子节点并设置正确的父文档。

示例代码:

private function initialiseDocument(&$document)
{
    $documentManager = $this->getModelManager();
    $parentDocument = $documentManager->find(null, $this->getRootPath());

    $document->setParentDocument($parentDocument);
    $slugifier = new Slugify();
    if ($document->getName() == null || $document->getName() == 'filler') {
        $document->setName($slugifier->slugify($document->getTitle()));
    }

    foreach ($document->getChildren() as $child) {
        $child->setParentDocument($document);
        if ($child->getName() == null || $child->getName() == 'filler') {
            $child->setName($slugifier->slugify($child->getLabel()));
        }
    }
}

编辑:最后,我简单地将ParentDocument字段的模板覆盖为:(最后一个if语句):

  

应用\资源\ SonataAdminBundle \视图\表格\ form_admin_fields.html.twig

<div class="form-group{% if errors|length > 0%} has-error{%endif%}" id="sonata-ba-field-container-{{ id }}"{% if 'parentDocument' in id %} style="display: none"{% endif %}>

从表单中删除名称字段,在Document的构造函数中初始化。工作正常,无需任何复杂的代码。