Commit becfd621 authored by Sebastian Castro's avatar Sebastian Castro

Element import ontology mapping

parent 7f7bc7d0
......@@ -54,48 +54,56 @@ class MigrationCommand extends GoGoAbstractCommand
$em->persist($migrationState);
}
// Collecting the Database to be updated
$dbs = ['gogocarto_default'];
$dbNames = $em->createQueryBuilder('BiopenSaasBundle:Project')->select('domainName')->hydrate(false)->getQuery()->execute()->toArray();
foreach ($dbNames as $object) { $dbs[] = $object['domainName']; }
try {
// Collecting the Database to be updated
$dbs = ['gogocarto_default'];
$dbNames = $em->createQueryBuilder('BiopenSaasBundle:Project')->select('domainName')->hydrate(false)->getQuery()->execute()->toArray();
foreach ($dbNames as $object) { $dbs[] = $object['domainName']; }
if (count($this->migrations) > $migrationState->getMigrationIndex()) {
$migrationsToRun = array_slice($this->migrations, $migrationState->getMigrationIndex());
foreach($dbs as $db) {
foreach($migrationsToRun as $migration) {
$this->runCommand($db, $migration);
}
if (count($this->migrations) > $migrationState->getMigrationIndex()) {
$migrationsToRun = array_slice($this->migrations, $migrationState->getMigrationIndex());
foreach($dbs as $db) {
foreach($migrationsToRun as $migration) {
$this->runCommand($db, $migration);
}
}
$this->log(count($migrationsToRun) . " migrations performed");
} else {
$this->log("No Migrations to perform");
}
$this->log(count($migrationsToRun) . " migrations performed");
} else {
$this->log("No Migrations to perform");
}
$asyncService = $this->getContainer()->get('biopen.async');
if (count($this->commands) > $migrationState->getCommandsIndex()) {
$commandsToRun = array_slice($this->commands, $migrationState->getCommandsIndex());
foreach($dbs as $db) {
foreach($commandsToRun as $command) {
$asyncService->callCommand($command, [], $db);
}
$asyncService = $this->getContainer()->get('biopen.async');
// run them syncronously otherwise all the command will be run at once
$asyncService->setRunSynchronously(true);
if (count($this->commands) > $migrationState->getCommandsIndex()) {
$commandsToRun = array_slice($this->commands, $migrationState->getCommandsIndex());
foreach($dbs as $db) {
foreach($commandsToRun as $command) {
$asyncService->callCommand($command, [], $db);
}
}
$this->log(count($commandsToRun) . " commands to run");
} else {
$this->log("No commands to run");
}
$this->log(count($commandsToRun) . " commands to run");
} else {
$this->log("No commands to run");
}
if (count($this->messages) > $migrationState->getMessagesIndex()) {
$messagesToAdd = array_slice($this->messages, $migrationState->getMessagesIndex());
foreach($dbs as $db) {
foreach($messagesToAdd as $message) {
// create a GoGoLogUpdate
$asyncService->callCommand('gogolog:add:message', ['"' . $message . '"'], $db);
}
if (count($this->messages) > $migrationState->getMessagesIndex()) {
$messagesToAdd = array_slice($this->messages, $migrationState->getMessagesIndex());
foreach($dbs as $db) {
foreach($messagesToAdd as $message) {
// create a GoGoLogUpdate
$asyncService->callCommand('gogolog:add:message', ['"' . $message . '"'], $db);
}
}
$this->log(count($messagesToAdd) . " messages added to admin dashboard");
} else {
$this->log("No Messages to add to dashboard");
}
$this->log(count($messagesToAdd) . " messages added to admin dashboard");
} else {
$this->log("No Messages to add to dashboard");
}
catch (\Exception $e) {
$message = $e->getMessage() . '</br>' . $e->getFile() . ' LINE ' . $e->getLine();
$this->error("Error performing migrations: " . $message);
}
$migrationState->setMigrationIndex(count($this->migrations));
$migrationState->setCommandsIndex(count($this->commands));
......@@ -106,6 +114,6 @@ class MigrationCommand extends GoGoAbstractCommand
private function runCommand($db, $command)
{
$process = new Process("mongo {$db} --eval \"{$command}\"");
return $process->start();
return $process->run();
}
}
\ No newline at end of file
......@@ -20,6 +20,13 @@ class AsyncService
*/
protected $phpPath;
protected $runSynchronously = false;
public function setRunSynchronously($bool)
{
$this->runSynchronously = $bool;
}
/**
* AsyncService constructor.
* @param string $consolePath
......@@ -91,6 +98,14 @@ class AsyncService
$process = new Process($commandline);
$process->start();
if ($this->runSynchronously)
{
while ($process->isRunning()) {
// waiting for process to finish
}
return $process->getOutput();
}
return $process->getPid();
}
}
\ No newline at end of file
......@@ -10,7 +10,7 @@ use Biopen\GeoDirectoryBundle\Document\ElementStatus;
class ImportDynamicAdmin extends ImportAbstractAdmin
{
public function getTemplate($name)
public function getTemplate($name)
{
switch ($name) {
case 'edit': return '@BiopenAdmin/edit/edit_import_dynamic.html.twig';
......@@ -22,36 +22,56 @@ class ImportDynamicAdmin extends ImportAbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with("Import Dynamique, pour afficher des données gérées par quelqu'un d'autre", ['class' => 'col-md-6'])
->add('sourceName', 'text', array('required' => true, 'label' => 'Nom de la source '))
->add('url', 'text', array('label' => "Url de l'api Json", 'required' => true))
->add('refreshFrequencyInDays', null, array('required' => false, 'label' => "Fréquence de mise à jours des données en jours (laisser vide pour ne jamais mettre à jour automatiquement"))
->add('idsToIgnore', 'text', array('required' => false, 'attr' => ['class' => 'gogo-display-array'], 'label' => "Liste des IDs qui seront ignorées lors de l'import", 'label_attr' => ['title' => "Pour ignorer un élément, supprimer le (définitivement) et il ne sera plus jamais importé. Si vous supprimez un élément dynamiquement importé juste en changeant son status (soft delete), l'élément sera quand meme importé mais conservera son status supprimé. Vous pourrez donc à tout moment restaurer cet élement pour le voir apparaitre de nouveau"]))
$dm = $this->getConfigurationPool()->getContainer()->get('doctrine_mongodb');
$repo = $dm->getRepository('BiopenGeoDirectoryBundle:Element');
$formProperties = json_encode($repo->findFormProperties());
$elementProperties = json_encode($repo->findDataCustomProperties());
$formMapper
->tab('Général')
->with("Import Dynamique, pour afficher des données gérées par quelqu'un d'autre", ['class' => 'col-md-6'])
->add('sourceName', 'text', array('required' => true, 'label' => 'Nom de la source '))
->add('url', 'text', array('label' => "Url de l'api Json", 'required' => true))
->add('refreshFrequencyInDays', null, array('required' => false, 'label' => "Fréquence de mise à jours des données en jours (laisser vide pour ne jamais mettre à jour automatiquement"))
->add('idsToIgnore', 'text', array('required' => false, 'attr' => ['class' => 'gogo-display-array'], 'label' => "Liste des IDs qui seront ignorées lors de l'import", 'label_attr' => ['title' => "Pour ignorer un élément, supprimer le (définitivement) et il ne sera plus jamais importé. Si vous supprimez un élément dynamiquement importé juste en changeant son status (soft delete), l'élément sera quand meme importé mais conservera son status supprimé. Vous pourrez donc à tout moment restaurer cet élement pour le voir apparaitre de nouveau"]))
->end()
->with("Autres options", ['box_class' => 'box box-default', 'class' => 'col-md-6'])
->add('geocodeIfNecessary', null, array('required' => false, 'label' => 'Géocoder les élements sans latitude ni longitude à partir de leur adresse'))
->add('createMissingOptions', null, array('required' => false, 'label' => 'Créer les catégories manquantes', 'label_attr' => ['title' => "Si un élément importé a une catégorie qui n'existe pas encore sur votre carte, elle sera automatiquement crée"]))
->add('optionsToAddToEachElement', 'sonata_type_model', array(
'class'=> 'Biopen\GeoDirectoryBundle\Document\Option',
'required' => false,
'choices_as_values' => true,
'multiple' => true,
'btn_add' => false,
'label' => 'Catégories à ajouter à chaque élément importé'), array('admin_code' => 'admin.option'))
->add('needToHaveOptionsOtherThanTheOnesAddedToEachElements', null, array('required' => false, 'label' => 'Les éléments importés doivent contenir au moins une catégorie en dehors de celles ajoutées manuellement ci-dessus', 'label_attr' => ['title' => "Sans prendre en compte les catégories ajoutés via le champs \"Catégories à ajouter à chaque élément importé\", si les éléments importés n'ont pas de catégories, ils seront marqués comme \"Modération aucune catégorie renseignée\""]))
->add('fieldToCheckElementHaveBeenUpdated', null, array('required' => false, 'label' => "Nom de l'attribut à comparer pour la mise à jour", 'label_attr' => ['title' => "Lorsqu'on met à jour une source, certains des éléments à importer existent déjà dans notre base de donnée. Vous pouvez renseigner ici un champs qui permettra de comparer si l'élément à été mis à jour au sein de la source depuis le dernier import. Exple de champ: updatedAt, date_maj etc... (laisser vide pour mettre à jour les éléments à chaque fois)"]))
->end()
->with('Historique', array('class' => 'col-sm-12'))
->add('logs', 'hidden', array('attr' => ['class' => 'gogo-display-logs'], 'mapped' => false))
->end()
->end()
->tab('Table de correspondance des champs')
->with('Transformer les données à importer')
->add('ontologyMapping', 'hidden', array('attr' => ['class' => 'gogo-mapping-ontology', 'data-form-props' => $formProperties, 'data-props' => $elementProperties]))
->end()
->end()
->with("Autres options", ['box_class' => 'box box-default', 'class' => 'col-md-6'])
->add('geocodeIfNecessary', null, array('required' => false, 'label' => 'Géocoder les élements sans latitude ni longitude à partir de leur adresse'))
->add('createMissingOptions', null, array('required' => false, 'label' => 'Créer les catégories manquantes', 'label_attr' => ['title' => "Si un élément importé a une catégorie qui n'existe pas encore sur votre carte, elle sera automatiquement crée"]))
->add('optionsToAddToEachElement', 'sonata_type_model', array(
'class'=> 'Biopen\GeoDirectoryBundle\Document\Option',
'required' => false,
'choices_as_values' => true,
'multiple' => true,
'btn_add' => false,
'label' => 'Catégories à ajouter à chaque élément importé'), array('admin_code' => 'admin.option'))
->add('needToHaveOptionsOtherThanTheOnesAddedToEachElements', null, array('required' => false, 'label' => 'Les éléments importés doivent contenir au moins une catégorie en dehors de celles ajoutées manuellement ci-dessus', 'label_attr' => ['title' => "Sans prendre en compte les catégories ajoutés via le champs \"Catégories à ajouter à chaque élément importé\", si les éléments importés n'ont pas de catégories, ils seront marqués comme \"Modération aucune catégorie renseignée\""]))
->add('fieldToCheckElementHaveBeenUpdated', null, array('required' => false, 'label' => "Nom de l'attribut à comparer pour la mise à jour", 'label_attr' => ['title' => "Lorsqu'on met à jour une source, certains des éléments à importer existent déjà dans notre base de donnée. Vous pouvez renseigner ici un champs qui permettra de comparer si l'élément à été mis à jour au sein de la source depuis le dernier import. Exple de champ: updatedAt, date_maj etc... (laisser vide pour mettre à jour les éléments à chaque fois)"]))
->end()
->with("Aide", ['box_class' => 'box box-default', "description" => $this->getInstructions('13154fa0-13c2-41f1-a4ad-e04c35c86e89')])
->tab('Table de correspondance des catégories')
->with('Faites correspondre les catégories')
->add('taxonomyMapping', 'hidden', array('attr' => ['class' => 'gogo-mapping-taxonomy']))
->end()
->end()
->with('Historique', array('class' => 'col-sm-12'))
->add('logs', 'hidden', array('attr' => ['class' => 'gogo-display-logs'], 'mapped' => false))
->end();
->tab('Aide')
->with("Aide", ['box_class' => 'box box-default', "description" => $this->getInstructions('13154fa0-13c2-41f1-a4ad-e04c35c86e89')])
->end()
->end();
}
protected function configureRoutes(RouteCollection $collection)
{
$collection->add('refresh', $this->getRouterIdParameter().'/refresh');
$collection->add('collect', $this->getRouterIdParameter().'/collect');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
......@@ -66,7 +86,7 @@ class ImportDynamicAdmin extends ImportAbstractAdmin
$deletedElementsCount = $dm->getRepository('BiopenGeoDirectoryBundle:Element')->findDeletedElementsByImportIdCount();
$listMapper
->addIdentifier('sourceName', null, array('label' => 'Nom de la source'))
->addIdentifier('sourceName', null, array('label' => 'Nom de la source'))
// Total count
->add('logs', null, array('label' => "Nombre d'éléments", 'template' => '@BiopenAdmin/partials/import/list_total_count.html.twig'))
// non visibles count
......
......@@ -279,7 +279,7 @@ class ChartBlockService extends AbstractBlockService
->match()
->field('type')->in($types)
->field('userRole')->notEqual('3') // not by an admin
->field('status')->notIn([-5, null]) // -5 = pending modification, null = not resolved
->field('status')->notIn([-5, null, 7, 8]) // -5 = pending modification, null = not resolved, 7 & 8 = dynamic import
->group()
->field('_id')
->expression('$status')
......
......@@ -9,28 +9,123 @@ use Biopen\GeoDirectoryBundle\Document\ImportState;
class ImportDynamicAdminController extends Controller
{
public function refreshAction()
{
$object = $this->admin->getSubject();
public function collectAction()
{
$object = $this->admin->getSubject();
$result = $this->get('biopen.element_import')->collectData($object);
$object->setCurrState(ImportState::Started);
$object->setCurrMessage("En attente...");
$em = $this->get('doctrine_mongodb')->getManager();
$em->persist($object);
$em->flush();
$this->addFlash('sonata_flash_success', "Les données ont été chargées avec succès. Vous pouvez maintenant compléter les tables de correspondances, puis importer les données.");
$url = $this->admin->generateUrl('edit', ['id' => $object->getId()]) . "#tab_2";
return $this->redirect($url);
}
$this->get('biopen.async')->callCommand('app:elements:importSource', [$object->getId()]);
public function refreshAction()
{
$object = $this->admin->getSubject();
// $result = $this->get('biopen.element_import')->importJson($object);
$object->setCurrState(ImportState::Started);
$object->setCurrMessage("En attente...");
$em = $this->get('doctrine_mongodb')->getManager();
$em->persist($object);
$em->flush();
$redirectionUrl = $this->admin->generateUrl('edit', ['id' => $object->getId()]);
$stateUrl = $this->generateUrl('biopen_import_state', ['id' => $object->getId()]);
$this->get('biopen.async')->callCommand('app:elements:importSource', [$object->getId()]);
return $this->render('@BiopenAdmin/pages/import/import-progress.html.twig', [
'import' => $object,
'redirectUrl' => $redirectionUrl,
'redirectListUrl' => $redirectionUrl = $this->admin->generateUrl('list'),
'stateUrl' => $stateUrl
]);
// $result = $this->get('biopen.element_import')->importJson($object);
$redirectionUrl = $this->admin->generateUrl('edit', ['id' => $object->getId()]);
$stateUrl = $this->generateUrl('biopen_import_state', ['id' => $object->getId()]);
return $this->render('@BiopenAdmin/pages/import/import-progress.html.twig', [
'import' => $object,
'redirectUrl' => $redirectionUrl,
'redirectListUrl' => $redirectionUrl = $this->admin->generateUrl('list'),
'stateUrl' => $stateUrl
]);
}
/**
* Overite Sonata CRud Controller
*/
public function editAction($id = null)
{
$request = $this->getRequest();
$id = $request->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
if (!$object) throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
$this->admin->checkAccess('edit', $object);
$this->admin->setSubject($object);
$form = $this->admin->getForm();
$form->setData($object);
$form->handleRequest($request);
if ($form->isSubmitted()) {
//TODO: remove this check for 4.0
if (method_exists($this->admin, 'preValidate')) {
$this->admin->preValidate($object);
}
$isFormValid = $form->isValid();
// persist if the form was valid and if in preview mode the preview was approved
if ($isFormValid) {
try {
// ----- CUSTOM -------
$object->setOntologyMapping($request->get('ontology'));
// ---- END CUSTOM ------
$object = $this->admin->update($object);
$this->addFlash(
'sonata_flash_success',
$this->trans(
'flash_edit_success',
array('%name%' => $this->escapeHtml($this->admin->toString($object))),
'SonataAdminBundle'
)
);
// redirect to edit mode
return $this->redirectTo($object);
} catch (ModelManagerException $e) {
$this->handleModelManagerException($e);
$isFormValid = false;
} catch (LockException $e) {
$this->addFlash('sonata_flash_error', $this->trans('flash_lock_error', array(
'%name%' => $this->escapeHtml($this->admin->toString($object)),
'%link_start%' => '<a href="'.$this->admin->generateObjectUrl('edit', $object).'">',
'%link_end%' => '</a>',
), 'SonataAdminBundle'));
}
}
// show an error message if the form failed validation
if (!$isFormValid) {
if (!$this->isXmlHttpRequest()) {
$this->addFlash(
'sonata_flash_error',
$this->trans(
'flash_edit_error',
array('%name%' => $this->escapeHtml($this->admin->toString($object))),
'SonataAdminBundle'
)
);
}
}
}
$view = $form->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
return $this->render($this->admin->getTemplate('edit'), array(
'action' => 'edit',
'form' => $view,
'object' => $object,
), null);
}
}
\ No newline at end of file
......@@ -106,7 +106,18 @@ class Import extends AbstractFile
*
* @MongoDB\Field(type="collection")
*/
private $idsToIgnore = [];
private $idsToIgnore = [];
/**
* @MongoDB\Field(type="hash")
*/
private $ontologyMapping = [];
/**
* @MongoDB\Field(type="hash")
*/
private $taxonomyMapping = [];
public function __construct() {
......@@ -413,4 +424,48 @@ class Import extends AbstractFile
{
return $this->fieldToCheckElementHaveBeenUpdated;
}
/**
* Set ontologyMapping
*
* @param hash $ontologyMapping
* @return $this
*/
public function setOntologyMapping($ontologyMapping)
{
$this->ontologyMapping = $ontologyMapping;
return $this;
}
/**
* Get ontologyMapping
*
* @return hash $ontologyMapping
*/
public function getOntologyMapping()
{
return $this->ontologyMapping;
}
/**
* Set taxonomyMapping
*
* @param hash $taxonomyMapping
* @return $this
*/
public function setTaxonomyMapping($taxonomyMapping)
{
$this->taxonomyMapping = $taxonomyMapping;
return $this;
}
/**
* Get taxonomyMapping
*
* @return hash $taxonomyMapping
*/
public function getTaxonomyMapping()
{
return $this->taxonomyMapping;
}
}
......@@ -32,7 +32,6 @@ class ImportDynamic extends Import
*/
private $nextRefresh = null;
public function isDynamicImport() { return true; }
......
......@@ -280,15 +280,23 @@ class ElementRepository extends DocumentRepository
$dataProperties = $onlyPublic ? $this->findPublicCustomProperties() : $this->findDataCustomProperties();
$allProperties = [];
foreach ($dataProperties as $prop) {
$allProperties[$prop] = $prop;
$allProperties[] = $prop;
}
$config = $this->getDocumentManager()->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
$formProperties = $this->findFormProperties();
return array_merge($allProperties, $formProperties);
}
public function findFormProperties()
{
$formProperties = [];
$propTypeToIgnore = ['separator', 'header', 'address', 'title', 'email', 'taxonomy', 'openhours'];
$config = $this->getDocumentManager()->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
foreach ($config->getElementFormFields() as $key => $field) {
if (property_exists($field, 'name') && !in_array($field->type, ['separator', 'address', 'title', 'email', 'taxonomy', 'openhours', 'header']))
$allProperties[$field->name] = $field->name;
if (property_exists($field, 'name') && !in_array($field->type, $propTypeToIgnore))
$formProperties[] = $field->name;
}
return $allProperties;
return $formProperties;
}
public function findDeletedElementsByImportIdCount()
......
......@@ -58,18 +58,24 @@ services:
- { name: doctrine_mongodb.odm.event_listener, event: preRemove }
- { name: doctrine_mongodb.odm.event_listener, event: preFlush }
biopen.csvtoarray:
class: Biopen\GeoDirectoryBundle\Services\ConvertCsvToArrayService
biopen.element_import:
public: true
class: Biopen\GeoDirectoryBundle\Services\ElementImportService
arguments:
- "@doctrine.odm.mongoDB.document_manager"
- "@biopen.csvtoarray"
- '@biopen.element_import_one'
- "@biopen.element_import_mapping"
biopen.element_import_one:
class: Biopen\GeoDirectoryBundle\Services\ElementImportOneService
arguments:
- "@doctrine.odm.mongoDB.document_manager"
- '@bazinga_geocoder.geocoder'
- "@biopen.user_interaction_service"
biopen.element_import_mapping:
class: Biopen\GeoDirectoryBundle\Services\ElementImportMappingService
arguments: []
biopen.gogocartojs_service:
class: Biopen\GeoDirectoryBundle\Services\GoGoCartoJsService
arguments: [ "@doctrine.odm.mongoDB.document_manager", "@security.context", "@router", "@session", "%base_protocol%" ]
......
<input type="hidden" id="{{ form.vars.id }}" name="{{ form.vars.full_name }}"/>
{% set object = form.vars.sonata_admin.admin.subject %}
{% set mapping = object.ontologyMapping %}
<table class="table">
<thead>
<tr>
<th>Attribute d'origine</th>
<th style="width:20px"></th>
<th>à transformer en</th>
</tr>
</thead>
<tbody class="table-striped">
{% for originName, mappedName in mapping %}
<tr>
<td class="original">{{originName}}</td>
<td><i class="arrow-icon fa fa-arrow-circle-right"></i></td>
<td class="mapped"><input type="text" name="ontology[{{originName}}]" class="form-control property-selector" value={{mappedName}} /></td>
</tr>
{% endfor %}
</tbody>
</table>
<style>
.arrow-icon { font-size: 18px; }
.arrow-icon:hover { cursor: pointer; }
td { vertical-align: middle !important; }
</style>
<script>
jQuery(document).ready(function() {
// on arrow click, use the original name
$('.arrow-icon').click(function() {
$(this).parent().parent().find('.property-selector:not(.select2-container)').val($(this).parent().siblings('.original').text()).trigger('change');
});
var formProperties = JSON.parse('{{ form.vars.attr["data-form-props"]|raw }}');
var dataProperties = JSON.parse('{{ form.vars.attr["data-props"]|raw }}');
var coreFields = ['id', 'name', 'categories', 'streetAddress', 'addressLocality', 'postalCode', 'addressCountry', 'latitude', 'longitude', 'images', 'owner', 'source']
var formData = [], allProperties = [], otherData = []; var importedData = [];
formData.push({id: 'id', text: 'Identifiant unique'});
formData.push({id: 'name', text: 'Titre de la fiche'});
formData.push({id: 'categories', text: 'Liste des catégories (en tableau ou séparées par des virgules)'});
formData.push({id: 'streetAddress', text: 'Adresse: rue'});
formData.push({id: 'addressLocality', text: 'Adresse: ville'});
formData.push({id: 'postalCode', text: 'Adresse: code postal'});
formData.push({id: 'addressCountry', text: 'Adresse: pays'});
formData.push({id: 'latitude', text: 'Latitude'});
formData.push({id: 'longitude', text: 'Longitude'});
allProperties = $.map(formData, function(el) { return el.id });
for(var i = 0; i < formProperties.length; i++) {
var prop = formProperties[i];
allProperties.push(prop);
formData.push({id: prop, text: prop});
}
for(var i = 0; i < dataProperties.length; i++) {
var prop = dataProperties[i];
if (allProperties.indexOf(prop) == -1) {
allProperties.push(prop);
otherData.push({id: prop, text: prop});
}
}
{% for originName, mappedName in mapping %}
var originName = '{{ originName }}';
if (originName && allProperties.indexOf(originName) == -1 && coreFields.indexOf(originName) == -1)
{
importedData.push({id: originName, text: originName});
allProperties.push(originName);
}
var mappedName = '{{ mappedName }}';
if (mappedName && allProperties.indexOf(mappedName) == -1 && coreFields.indexOf(originName) == -1)
{
otherData.push({id: mappedName, text: mappedName});
allProperties.push(mappedName);
}
{% endfor %}
console.log(allProperties, otherData);
options = [{ text: "Attributs du formulaire", children: formData}];
if (otherData.length > 0) options.push({text: "Autres attributs", children: otherData});
options.push({ text: "Attributs importés", children: importedData});
$(".property-selector").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
data: options
});
});
</script>
\ No newline at end of file
<input type="hidden" id="{{ form.vars.id }}" name="{{ form.vars.full_name }}"/>
{% set object = form.vars.sonata_admin.admin.subject %}
{% set mapping = object.ontologyMapping %}
<table class="table">
<thead>
<tr>
<th>Attribute d'origine</th>
<th style="width:20px"></th>
<th>à transformer en</th>
</tr>
</thead>
<tbody class="table-striped">
{% for originName, mappedName in mapping %}
<tr>
<td class="original">{{originName}}</td>
<td><i class="arrow-icon fa fa-arrow-circle-right"></i></td>
<td class="mapped"><input type="text" name="ontology[{{originName}}]" class="form-control property-selector" value={{mappedName}} /></td>
</tr>
{% endfor %}
</tbody>
</table>
\ No newline at end of file
......@@ -37,6 +37,10 @@
{% include '@BiopenAdmin/core_custom/custom-fields/display-logs.html.twig' %}
{% elseif attr_class == "gogo-sort-options" %}
{% include '@BiopenAdmin/core_custom/custom-fields/sort-options.html.twig' %}
{% elseif attr_class == "gogo-mapping-taxonomy" %}
{% include '@BiopenAdmin/core_custom/custom-fields/mapping-taxonomy.html.twig' %}
{% elseif attr_class == "gogo-mapping-ontology" %}
{% include '@BiopenAdmin/core_custom/custom-fields/mapping-ontology.html.twig' %}
{% else %}
{% set attr = attr|merge({'class': attr_class ~ ' form-control'}) %}
{{ parent() }}
......