I've developed an area in Pimcore that allows us to select a Pimcore object classification from a list, and transform it into an HTML renderable form.
I would like to increase the functionality of this by capturing successful submissions as objects in the backend, however I cannot seem to use the standard PHP method for object creation by class name.
What am I doing wrong? Does Pimcore handle this in an different way?
Accepted Answer Edits:
I've altered the code slightly to reflect the suggestions from the accepted answer. As noted, it's important to remember that while class names can have lowercase first letters, their actual namespaced identifiers use initial casing, which is where my code was breaking.
For instance:
$newObj_class
was outputting Pimcore\Model\Object\className
$newObj_class
should have been Pimcore\Model\Object\ClassName
Notice the distinction in the className
vs ClassName
...
Here's the core of the area's working view.php file:
// Get a list of available classes...
$form_class = null;
$class_list = new Pimcore\Model\Object\ClassDefinition\Listing();
$class_list->load();
// Turn the class names into dropdown options...
$class_options = array();
foreach( $class_list->getClasses() as $class )
{
$class_options[] = array( $class->name, $class->name );
}
// Admin only code...
if( $this->editmode )
{
$formSource = $this->select(
'formClass',
array(
'store' => $class_options,
'reload' => true
)
);
echo
'<table>'.
'<tr><th>Form Source:</th><td>'.$formSource.'</td></tr>'.
// Additional config fields go here...
'</table>';
}
// Iterate over the classes...
foreach( $class_list->getClasses() as $class )
{
// Skip unselected classes...
if( $this->select( 'formClass' )->getValue() != $class->name )
{
continue;
}
// Handle form submissions...
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
// Create an object using the selected class...
$newObj_class = 'Pimcore\\Model\\Object\\'.ucfirst( (string)$this->select( 'formClass' ) );
$newObj = new $newObj_class();
// Assign field values to the object here...
$newObj->save();
}
}
Your object class name probably starts with lower case but the actual class always stars with upper case.
This should fix your problem:
$newClass = 'Pimcore\\Model\\Object\\' . ucfirst($this->select( 'formClass' )->getValue());