/** * The method defines the correct default settings for the provided FieldDescription. * * {@inheritdoc} * * @throws \RuntimeException if the $fieldDescription does not specify a type. */ public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription) { $metadata = null; if ($admin->getModelManager()->hasMetadata($admin->getClass())) { /** @var \Doctrine\ODM\PHPCR\Mapping\ClassMetadata $metadata */ $metadata = $admin->getModelManager()->getMetadata($admin->getClass()); // set the default field mapping if (isset($metadata->mappings[$fieldDescription->getName()])) { $fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]); } // set the default association mapping if ($metadata->hasAssociation($fieldDescription->getName())) { $fieldDescription->setAssociationMapping($metadata->getAssociation($fieldDescription->getName())); } } if (!$fieldDescription->getType()) { throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), get_class($admin))); } $fieldDescription->setAdmin($admin); $fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'standard')); $mappingTypes = array(ClassMetadata::MANY_TO_ONE, ClassMetadata::MANY_TO_MANY, 'children', 'child', 'parent', 'referrers'); if ($metadata && $metadata->hasAssociation($fieldDescription->getName()) && in_array($fieldDescription->getMappingType(), $mappingTypes)) { $admin->attachAdminClass($fieldDescription); } }
/** * The method defines the correct default settings for the provided FieldDescription * * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription * @return void */ public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription) { if ($admin->getModelManager()->hasMetadata($admin->getClass())) { $metadata = $admin->getModelManager()->getMetadata($admin->getClass()); // set the default field mapping if (isset($metadata->fieldMappings[$fieldDescription->getName()])) { $fieldDescription->setFieldMapping($metadata->fieldMappings[$fieldDescription->getName()]); } // set the default association mapping if (isset($metadata->associationMappings[$fieldDescription->getName()])) { $fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]); } } if (!$fieldDescription->getType()) { throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), get_class($admin))); } $fieldDescription->setAdmin($admin); $fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'standard')); if (in_array($fieldDescription->getMappingType(), array(ClassMetadataInfo::ONE_TO_MANY, ClassMetadataInfo::MANY_TO_MANY, ClassMetadataInfo::MANY_TO_ONE, ClassMetadataInfo::ONE_TO_ONE ))) { $admin->attachAdminClass($fieldDescription); } }
/** * {@inheritdoc} */ public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription) { $fieldDescription->setTemplate('YnloAdminBundle::CRUD/list_enum.html.twig'); /** @var ModelManager $modelManager */ $modelManager = $admin->getModelManager(); if (null === $fieldDescription->getOption('enum_type') && $modelManager->hasMetadata($admin->getClass())) { $mapping = $modelManager->getMetadata($admin->getClass())->getFieldMapping($fieldDescription->getName()); $fieldDescription->setOption('enum_type', $mapping['type']); } }
/** * {@inheritdoc} */ public function addFilter(DatagridInterface $datagrid, $type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin) { // Try to wrap all types to search types if ($type == null) { $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager()); $type = $guessType->getType(); $fieldDescription->setType($type); $options = $guessType->getOptions(); foreach ($options as $name => $value) { if (is_array($value)) { $fieldDescription->setOption($name, array_merge($value, $fieldDescription->getOption($name, array()))); } else { $fieldDescription->setOption($name, $fieldDescription->getOption($name, $value)); } } } else { $fieldDescription->setType($type); } $this->fixFieldDescription($admin, $fieldDescription); $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription); $fieldDescription->mergeOption('field_options', array('required' => false)); $filter = $this->filterFactory->create($fieldDescription->getName(), $type, $fieldDescription->getOptions()); if (false !== $filter->getLabel() && !$filter->getLabel()) { $filter->setLabel($admin->getLabelTranslatorStrategy()->getLabel($fieldDescription->getName(), 'filter', 'label')); } $datagrid->addFilter($filter); }
/** * execute a batch delete * * @param array $idx * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function batchActionDelete($idx) { $modelManager = $this->admin->getModelManager(); $modelManager->batchDelete($this->admin->getClass(), $idx); // todo : add confirmation flash var return new RedirectResponse($this->admin->generateUrl('list')); }
/** * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param \Sonata\AdminBundle\Route\RouteCollection $collection */ public function build(AdminInterface $admin, RouteCollection $collection) { $collection->add('list'); $collection->add('create'); $collection->add('batch'); $collection->add('edit'); $collection->add('delete'); $collection->add('show'); $collection->add('export'); if ($this->manager->hasReader($admin->getClass())) { $collection->add('history', '/audit-history'); $collection->add('history_view_revision', '/audit-history-view'); } if ($admin->isAclEnabled()) { $collection->add('acl', $admin->getRouterIdParameter() . '/acl'); } // an admin can have only one level of nested child if ($admin->getParent()) { return; } // add children urls foreach ($admin->getChildren() as $children) { $collection->addCollection($children->getRoutes()); } }
/** * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param array $values * @return \Sonata\AdminBundle\Datagrid\DatagridInterface */ public function getBaseDatagrid(AdminInterface $admin, array $values = array()) { $pager = new Pager(); $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass())); $formBuilder = $this->formFactory->createNamedBuilder('form', 'filter', array(), array('csrf_protection' => false)); return new Datagrid($admin->createQuery(), $admin->getList(), $pager, $formBuilder, $values); }
/** * {@inheritdoc} */ public function alterNewInstance(AdminInterface $admin, $object) { if ($object->getParent() == null) { $reflectionClass = $admin->getClass(); $parent = $this->container->get('doctrine')->getRepository($reflectionClass)->findOneById($this->getRequest()->query->get('parent')); $object->setParent($parent); } }
/** * {@inheritdoc} */ public function batchConfigureAcls(OutputInterface $output, AdminInterface $admin, UserSecurityIdentity $securityIdentity = null) { $securityHandler = $admin->getSecurityHandler(); if (!$securityHandler instanceof AclSecurityHandlerInterface) { $output->writeln('Admin class is not configured to use ACL : <info>ignoring</info>'); return; } $output->writeln(sprintf(' > generate ACLs for %s', $admin->getCode())); $objectOwnersMsg = is_null($securityIdentity) ? '' : ' and set the object owner'; $em = $admin->getModelManager()->getEntityManager($admin->getClass()); $qb = $em->createQueryBuilder(); $qb->select('o')->from($admin->getClass(), 'o'); $count = 0; $countUpdated = 0; $countAdded = 0; try { $batchSize = 20; $batchSizeOutput = 200; $objectIds = array(); foreach ($qb->getQuery()->iterate() as $row) { $objectIds[] = ObjectIdentity::fromDomainObject($row[0]); $objectIdIterator = new \ArrayIterator($objectIds); // detach from Doctrine, so that it can be Garbage-Collected immediately $em->detach($row[0]); ++$count; if ($count % $batchSize == 0) { list($batchAdded, $batchUpdated) = $this->configureAcls($output, $admin, $objectIdIterator, $securityIdentity); $countAdded += $batchAdded; $countUpdated += $batchUpdated; $objectIds = array(); } if ($count % $batchSizeOutput == 0) { $output->writeln(sprintf(' - generated class ACEs%s for %s objects (added %s, updated %s)', $objectOwnersMsg, $count, $countAdded, $countUpdated)); } } if (count($objectIds) > 0) { list($batchAdded, $batchUpdated) = $this->configureAcls($output, $admin, $objectIdIterator, $securityIdentity); $countAdded += $batchAdded; $countUpdated += $batchUpdated; } } catch (\PDOException $e) { throw new ModelManagerException('', 0, $e); } $output->writeln(sprintf(' - [TOTAL] generated class ACEs%s for %s objects (added %s, updated %s)', $objectOwnersMsg, $count, $countAdded, $countUpdated)); }
/** * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function exportAction(Request $request) { if (false === $this->admin->isGranted('EXPORT')) { throw new AccessDeniedException(); } $format = $request->get('format'); $filename = sprintf('export_%s_%s.%s', strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)), date('Y_m_d_H_i_s', strtotime('now')), $format); return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator()); }
/** * @param FormMapper $formMapper * @param AdminInterface $admin * @param string $formField * @param string $field * @param array $fieldOptions * @param array $adminOptions * * @return FormBuilder */ protected final function getFormAdminType(FormMapper $formMapper, AdminInterface $admin, $formField, $field, $fieldOptions = array(), $adminOptions = array()) { $adminOptions = array_merge(array('edit' => 'list', 'translation_domain' => 'SonataClassificationBundle'), $adminOptions); $fieldDescription = $admin->getModelManager()->getNewFieldDescriptionInstance($admin->getClass(), $field, $adminOptions); $fieldDescription->setAssociationAdmin($admin); $fieldDescription->setAdmin($formMapper->getAdmin()); $fieldDescription->setAssociationMapping(array('fieldName' => $field, 'type' => ClassMetadataInfo::MANY_TO_ONE)); $fieldOptions = array_merge(array('sonata_field_description' => $fieldDescription, 'class' => $admin->getClass(), 'model_manager' => $admin->getModelManager(), 'required' => false), $fieldOptions); return $formMapper->create($formField, 'sonata_type_model_list', $fieldOptions); }
/** * {@inheritdoc} */ public function buildField($type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin) { if ($type == null) { $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager()); $fieldDescription->setType($guessType->getType()); } else { $fieldDescription->setType($type); } $this->fixFieldDescription($admin, $fieldDescription); }
/** * Export data to specified format. * * @param Request $request * * @return Response * * @throws AccessDeniedException If access is not granted * @throws \RuntimeException If the export format is invalid */ public function exportAction(Request $request) { $this->admin->checkAccess('export'); $format = $request->get('format'); $allowedExportFormats = (array) $this->admin->getExportFormats(); if (!in_array($format, $allowedExportFormats)) { throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats))); } $filename = sprintf('export_%s_%s.%s', strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)), date('Y_m_d_H_i_s', strtotime('now')), $format); return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator()); }
/** * Adds a field to the Field description collection and sets its type. * If not type provided, will try to guess it. * * @param \Sonata\AdminBundle\Admin\FieldDescriptionCollection $list * @param string|null $type * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @return FieldDescriptionCollection */ public function addField(FieldDescriptionCollection $list, $type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin) { if ($type == null) { $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName()); $fieldDescription->setType($guessType->getType()); } else { $fieldDescription->setType($type); } $this->fixFieldDescription($admin, $fieldDescription); $admin->addListFieldDescription($fieldDescription->getName(), $fieldDescription); return $list->add($fieldDescription); }
/** * return the Response object associated to the batch action * * @throws \RuntimeException * @return \Symfony\Component\HttpFoundation\Response */ public function batchAction() { if ($this->get('request')->getMethod() != 'POST') { throw new \RuntimeException('invalid request type, POST expected'); } if ($data = json_decode($this->get('request')->get('data'), true)) { $action = $data['action']; $idx = $data['idx']; $all_elements = $data['all_elements']; } else { $action = $this->get('request')->get('action'); $idx = $this->get('request')->get('idx'); $all_elements = $this->get('request')->get('all_elements', false); } $batchActions = $this->admin->getBatchActions(); if (!array_key_exists($action, $batchActions)) { throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action)); } if (count($idx) == 0 && !$all_elements) { // no item selected $this->get('session')->setFlash('sonata_flash_notice', 'flash_batch_empty'); return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); } $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true; if ($askConfirmation && $this->get('request')->get('confirmation') != 'ok') { $data = json_encode(array('action' => $action, 'idx' => $idx, 'all_elements' => $all_elements)); $datagrid = $this->admin->getDatagrid(); $formView = $datagrid->getForm()->createView(); return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array('action' => 'list', 'datagrid' => $datagrid, 'form' => $formView, 'data' => $data)); } // execute the action, batchActionXxxxx $action = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action); $final_action = sprintf('batchAction%s', ucfirst($action)); if (!method_exists($this, $final_action)) { throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action)); } $datagrid = $this->admin->getDatagrid(); $datagrid->buildPager(); $query = $datagrid->getQuery(); $query->setFirstResult(null); $query->setMaxResults(null); if (count($idx) > 0) { $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx); } return call_user_func(array($this, $final_action), $query); }
/** * {@inheritDoc} */ public function addField(FieldDescriptionCollection $list, $type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin) { if ($type == null) { $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager()); $fieldDescription->setType($guessType->getType()); } else { $fieldDescription->setType($type); } $this->fixFieldDescription($admin, $fieldDescription); $admin->addShowFieldDescription($fieldDescription->getName(), $fieldDescription); switch ($fieldDescription->getMappingType()) { case ClassMetadata::MANY_TO_ONE: case ClassMetadata::MANY_TO_MANY: return; default: $list->add($fieldDescription); } }
/** * return the Response object associated to the batch action * * @throws \RuntimeException * @return \Symfony\Component\HttpFoundation\Response */ public function batchAction() { if ($this->get('request')->getMethod() != 'POST') { throw new \RuntimeException('invalid request type, POST expected'); } $action = $this->get('request')->get('action'); $idx = $this->get('request')->get('idx'); $all_elements = $this->get('request')->get('all_elements', false); if (count($idx) == 0 && !$all_elements) { // no item selected $this->get('session')->setFlash('sonata_flash_notice', 'flash_batch_empty'); return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); } if (!array_key_exists($action, $this->admin->getBatchActions())) { throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action)); } // execute the action, batchActionXxxxx $action = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action); $final_action = sprintf('batchAction%s', ucfirst($action)); if (!method_exists($this, $final_action)) { throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action)); } $datagrid = $this->admin->getDatagrid(); $datagrid->buildPager(); $query = $datagrid->getQuery(); $query->setFirstResult(null); $query->setMaxResults(null); if (count($idx) > 0) { $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx); } return call_user_func(array($this, $final_action), $query); }
/** * {@inheritdoc} */ public function getBaseDatagrid(AdminInterface $admin, array $values = array()) { $pager = $this->getPager($admin->getPagerType()); $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass())); $defaultOptions = array(); if ($this->csrfTokenEnabled) { $defaultOptions['csrf_protection'] = false; } $formBuilder = $this->formFactory->createNamedBuilder('filter', 'form', array(), $defaultOptions); return new Datagrid($admin->createQuery(), $admin->getList(), $pager, $formBuilder, $values); }
/** * The method defines the correct default settings for the provided FieldDescription * * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription * @param array $options * @return void */ public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription, array $options = array()) { $fieldDescription->mergeOptions($options); if ($admin->getModelManager()->hasMetadata($admin->getClass())) { $metadata = $admin->getModelManager()->getMetadata($admin->getClass()); // set the default field mapping if (isset($metadata->fieldMappings[$fieldDescription->getName()])) { $fieldDescription->setFieldMapping($metadata->fieldMappings[$fieldDescription->getName()]); } // set the default association mapping if (isset($metadata->associationMappings[$fieldDescription->getName()])) { $fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]); } } if (!$fieldDescription->getType()) { throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), get_class($admin))); } $fieldDescription->setAdmin($admin); $fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'standard')); // fix template value for doctrine association fields if (!$fieldDescription->getTemplate()) { $fieldDescription->setTemplate(sprintf('SonataAdminBundle:CRUD:edit_%s.html.twig', $fieldDescription->getType())); } if ($fieldDescription->getType() == ClassMetadataInfo::ONE_TO_ONE) { $fieldDescription->setTemplate('SonataAdminBundle:CRUD:edit_orm_one_to_one.html.twig'); $admin->attachAdminClass($fieldDescription); } if ($fieldDescription->getType() == ClassMetadataInfo::MANY_TO_ONE) { $fieldDescription->setTemplate('SonataAdminBundle:CRUD:edit_orm_many_to_one.html.twig'); $admin->attachAdminClass($fieldDescription); } if ($fieldDescription->getType() == ClassMetadataInfo::MANY_TO_MANY) { $fieldDescription->setTemplate('SonataAdminBundle:CRUD:edit_orm_many_to_many.html.twig'); $admin->attachAdminClass($fieldDescription); } if ($fieldDescription->getType() == ClassMetadataInfo::ONE_TO_MANY) { $fieldDescription->setTemplate('SonataAdminBundle:CRUD:edit_orm_one_to_many.html.twig'); if ($fieldDescription->getOption('edit') == 'inline' && !$fieldDescription->getOption('widget_form_field')) { $fieldDescription->setOption('widget_form_field', 'Bundle\\Sonata\\AdminBundle\\Form\\EditableFieldGroup'); } $admin->attachAdminClass($fieldDescription); } // set correct default value if ($fieldDescription->getType() == 'datetime') { $options = $fieldDescription->getOption('form_field_options', array()); if (!isset($options['years'])) { $options['years'] = range(1900, 2100); } $fieldDescription->setOption('form_field', $options); } }
/** * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param array $values * @return \Sonata\AdminBundle\Datagrid\DatagridInterface */ public function getBaseDatagrid(AdminInterface $admin, array $values = array()) { $queryBuilder = $admin->getModelManager()->getDocumentManager()->createQueryBuilder(); $qomFactory = $queryBuilder->getQOMFactory(); $query = new ProxyQuery($qomFactory, $queryBuilder); $query->setDocumentName($admin->getClass()); $query->setDocumentManager($admin->getModelManager()->getDocumentManager()); $pager = new Pager(); $formBuilder = $this->formFactory->createNamedBuilder('form', 'filter', array(), array('csrf_protection' => false)); return new Datagrid($query, $admin->getList(), $pager, $formBuilder, $values); }
/** * @param AdminInterface $admin * @param mixed $object * * @return ComponentInterface */ protected function getTarget(AdminInterface $admin, $object) { return $this->actionManager->findOrCreateComponent($admin->getClass(), $admin->id($object)); }
/** * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param array $values * @return \Sonata\AdminBundle\Datagrid\DatagridInterface */ public function getBaseDatagrid(AdminInterface $admin, array $values = array()) { $queryBuilder = $admin->getModelManager()->createQuery($admin->getClass()); $query = new ProxyQuery($queryBuilder); $pager = new Pager; $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass())); return new Datagrid( $query, $admin->getList(), $pager, $this->formFactory, $values ); }
/** * @param \Sonata\AdminBundle\Admin\AdminInterface $admin * @param array $values * @return \Sonata\AdminBundle\Datagrid\DatagridInterface */ public function getBaseDatagrid(AdminInterface $admin, array $values = array()) { $queryBuilder = $admin->getModelManager()->createQuery($admin->getClass()); $query = new ProxyQuery($queryBuilder); return new Datagrid($query, $admin->getList(), new Pager(), $this->formFactory, $values); }