How do I hide parent document field in a form? I have some blocks that will be fixed and do not want to show the parent document field. I have tried passing a css class or inline style to the field but it doesn't appear after the field is rendered.
Attempt 1
Sample code:
->add(
'parentDocument',
'doctrine_phpcr_odm_tree',
array('attr' => ['style' => 'display:none !important'], 'root_node' => $this->getRootPath(), 'choice_list' => array(), 'select_root_node' => true)
)
Attempt 2
I also tried making the field hidden, pass a string as default data in the field, set up a prepersist event to override the string with parent document needed. While this works well for the block when not embedded, it also triggered a side effect on slideshow block where I am unable to save my child block unless the child's parent document field is present.
Sample code of child block:
Form:
->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:
ERROR -
Context: {"exception":"Object(Sonata\\AdminBundle\\Exception\\ModelManagerException)","previous_exception_message":"Warning: get_class() expects parameter 1 to be object, string given"}
In summary for attempt 2, slideshow block works correctly when the child's parent document field is left as default. But I want to hide that field!
This can be ignored and look at Edit below
I figured out what the issue was with attempt 2. I thought that the child's prepersist event would be triggered when the parent block is persisted but turned out that this wasn't the case. Only the parent's prepersist event was called.
So in my case I filled the child's parentDocument property with text 'filler' which did not get overridden to a document object since it's prepersist event was not called. Hence the error mentioned. I thus modified my parent's perpersist event to loop into its children and set the correct parent document.
Sample code:
Edit: In the end I simply overwrote the template for ParentDocument field to become like this (the last if statement) in:
And the Name field removed from the form, initialized in Document's constructor. Works fine without need of any complex code.