src/Crud/Controller/crudPlainController.php line 273

Open in your IDE?
  1. <?php
  2. namespace App\Crud\Controller;
  3. use App\Crud\Crud;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Pagerfanta\Pagerfanta;
  6. use Pagerfanta\Adapter\DoctrineORMAdapter;
  7. use App\Crud\FormFilter\crudFilterType;
  8. use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
  9. use Symfony\Component\Form\Extension\Core\Type\DateType;
  10. use Symfony\Component\Form\Extension\Core\Type\TimeType;
  11. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  12. //use Symfony\Component\Form\Extension\Core\Type\ChoiceType
  13. use App\Crud\ParseConfig\ParseConfig;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. use Psr\Log\LoggerInterface;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\HttpFoundation\RequestStack;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  20. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  22. use Symfony\Component\HttpFoundation\StreamedResponse;
  23. /**
  24.  * crudController controller.
  25.  */
  26. class crudPlainController extends AbstractController
  27. {
  28.     //CONSTANTES RELACIONADAS CON LAS PLANTILLAS POR DEFECTO EN CASO DE QUE NO SE
  29.     //ESPECIFIQUE NINGUNA
  30.     const defaultTwigIndexName       '@crud\crud\index.html.twig';
  31.     const defaultTwigInlineIndexName '@crud\crud\index_inline.html.twig';
  32.     const defaultTwigNewName         '@crud\crud\new.html.twig';
  33.     const defaultModalTwigNewName    '@crud\crud\formulario_new_modal.html.twig';
  34.     const defaultTwigEditName        '@crud\crud\edit.html.twig';
  35.     const defaultTwigShowName        '@crud\crud\show.html.twig';
  36.     const defaultModalTwigEditName   '@crud\crud\formulario_edit_modal.html.twig';
  37.     const defaultModalTwigShowName   '@crud\crud\show_data.html.twig';
  38.     const defaultTwigExcelName       '@crud\crud\excel.html.twig';
  39.     
  40.     //COSNTANTE QUE INDICA LA CANTIDAD DE COLUMNAS QUE TENDRÁ EL FORMULARIO DE
  41.     //FILTRADO EN CASO DE QUE NO SE ESPECIFIQUE NINGÚN OTRO
  42.     const defaultFilterColumns 2;
  43.     //REQUEST OBJECT
  44.     protected $request;
  45.     protected $inline false;
  46.     protected $ajax false;
  47.     //PROPIEDADES RELACIONADAS CON LA IDENTIFICACION DE LA ENTIDAD A LA QUE SE 
  48.     //LE HACE CRUD
  49.     protected $rol;             //rol pasado en la ruta
  50.     protected $routeClassName;  //Identificador de la clase en el mapa
  51.     protected $className;       //Nombre real de la clase
  52.     protected $fabricante;      //Fabricante de la clase
  53.     protected $bundle;          //Bundle donde reside la clase
  54.     protected $entityFolder;    //Folder donde reside el fichero que define la clase
  55.     protected $classFullName;   //Calculado. Nombre completo de la clase: <Fabricante/Bundle/Folder/Clase>
  56.     protected $bundleName;      //Calculado. Nombre del bundle: <FabricanteBundle>
  57.     
  58.     //PROPIEDADES RELACIONADAS CON LAS PLANTILLAS QUE SE USARÁN PARA MOSTRAR LAS
  59.     //DISTINTAS OPERACIONES
  60.     protected $twigIndexName;   
  61.     protected $twigNewName;
  62.     protected $twigShowName;
  63.     protected $twigEditName;
  64.     protected $heightModalForm;
  65.     protected $widthModalForm;
  66.     protected $heightModalShow;
  67.     protected $widthModalShow;
  68.     protected $indexInnerView;
  69.     protected $twigExcelName;
  70.     
  71.     //PROPIEDADES RELACIONADAS CON LA OPERACION INDEX.
  72.     //
  73.     //Layout de la tabla
  74.     protected $columnAction;
  75.     protected $search;
  76.     protected $tableInfo;
  77.     protected $scrollY;
  78.     
  79.     //BOTONES QUE SE MOSTRARÁN O NO. 
  80.     protected $showInIndex;
  81.     protected $newInIndex;
  82.     protected $editInIndex;
  83.     protected $deleteInIndex;
  84.     protected $buttons;         //Imágenes que se usarán para cada botón.
  85.     //
  86.     //FILTRADO
  87.     protected $showFilter;
  88.     protected $filterColumns;
  89.     protected $showColumns;
  90.     protected $filterData;
  91.     protected $formularioFiltro;
  92.     //
  93.     //PAGINADO
  94.     protected $paginator
  95.     protected $showPaginator;
  96.     protected $maxPerPage 10;
  97.     //PROPIEDADES RELACIONADAS CON LAS OPERACIONES NEW Y EDIT.
  98.     protected $showIdInForm;
  99.     protected $formulario;
  100.     protected $formColumns;
  101.     //OTRAS PROPIEDADES ÚTILES Y COMUNES A TODAS LAS OPERACIONES
  102.     protected $em;
  103.     protected $translator;
  104.     protected $translatorBase;
  105.     protected $booleans;
  106.     protected $paramsRequest;
  107.     protected $entities;
  108.     protected $oldEntity;
  109.     protected $logger;
  110.     protected $widthLabel;
  111.     protected $modal;
  112.     protected $mailer;
  113.     protected $session;
  114.     protected $dateFields = [];
  115.     
  116.     protected $allowedRol null;
  117.     protected $allowedINDEX null;
  118.     protected $allowedCREATE null;
  119.     protected $allowedUPDATE null;
  120.     protected $allowedDELETE null;
  121.     protected $allowedSHOW null;
  122.     
  123.     protected $accion;
  124.     
  125.     protected function setDateToBeginMonth($fecha)
  126.     {
  127.         $year $fecha->format('Y');
  128.         $month $fecha->format('m');
  129.         $fecha->setDate($year$month1);
  130.         $fecha->setTime(0,0,0);
  131.         return $fecha;
  132.     }
  133.     /* 
  134.      * MÉTODOS DE LA CLASE
  135.      */
  136.     public function __construct(TranslatorInterface $translatorLoggerInterface $loggerMailerInterface $mailerRequestStack $requestStackEntityManagerInterface $entityManager)
  137.     {
  138.         $this->translator $translator;
  139.         $this->logger $logger;
  140.         $this->mailer $mailer;
  141.         $this->session $requestStack->getSession();
  142.         $this->request $requestStack->getCurrentRequest();
  143.         $this->em $entityManager;
  144.     }
  145.     /* 
  146.      * MÉTODOS COMUNES A UNA O VARIAS ACCIONES
  147.      */
  148.     protected function comunCheckConstrains($entity)
  149.     {
  150.         $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  151.         $paramsForFunctionInEntity['accion'] = $this->accion;
  152.         $paramsForFunctionInEntity['bundle_class'] = $this->bundleName ':' $this->className;
  153.         $paramsForFunctionInEntity['entity'] = $entity;
  154.         return $this->comunCheckNullableConstrains($entity
  155.                &&
  156.                $this->comunCheckUniqueConstrains($entity
  157.                &&
  158.                $this->checkNonUniqueConstrains($entity);
  159.     }
  160.     
  161.     protected function comunCheckUniqueConstrains($entity)
  162.     {
  163.        $className $this->classFullName;
  164.        $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  165.        $constraints $className::getUniqueConstraints($paramsForFunctionInEntity);
  166.        $existe false;
  167.        if (isset($constraints['singles']))
  168.          foreach ($constraints['singles'] as $campo)
  169.          {    
  170.             $search = array(); 
  171.             $value=$entity->getFieldValue($campo['nombre']);
  172.             if ($campo['association'])
  173.               if ($value)  
  174.                   $value=$value->getId();
  175.               else
  176.                   continue;
  177.             $search[$campo['nombre']]=$value;
  178.             $otraEntidad $this->em->getRepository($this->bundleName '\\Entity\\' $this->className)->findOneBy($search);
  179.             $existe = ($this->accion=='CREATE' && $otraEntidad
  180.                       ||
  181.                       ( $otraEntidad && $entity->getId() != $otraEntidad->getId() );
  182.             if ($existe)
  183.             {
  184.               $this->session->getFlashBag()->set('danger'
  185.                                                $this->translator->trans(
  186.                                                     'error.unique.single',
  187.                                                     array('%className%' => strtoupper($this->translator->trans($this->routeClassName.'.singular',array(),'crud')),
  188.                                                           '%fieldname%' => strtoupper($this->translator->trans($this->routeClassName.'.fields.'.$campo['nombre'],array(),'crud'))),
  189.                                                     'crud'));
  190.               return false;
  191.             }   
  192.          } 
  193.        if (isset($constraints['composite']))
  194.          foreach ($constraints['composite'] as $nombre=>$columns)
  195.          {    
  196.            $search = array(); 
  197.            $camposStr '';
  198.            foreach ($columns as $campo)  
  199.            {    
  200.              if ($camposStr == '')
  201.                $camposStr .= $this->translator->trans($this->routeClassName.'.fields.'.$campo['nombre'],array(),'crud');
  202.              else
  203.                $camposStr .= ', '.$this->translator->trans($this->routeClassName.'.fields.'.$campo['nombre'],array(),'crud');
  204.              $value=$entity->getFieldValue($campo['nombre']);
  205.              if ($campo['association'] and $value)
  206.                $value=$value->getId();  
  207.              if ($value
  208.                  $search[$campo['nombre']]=$value;
  209.            } 
  210.            if (count($search)>1)
  211.            {
  212.                $otraEntidad $this->em->getRepository($this->bundleName '\\Entity\\' $this->className)->findOneBy($search);
  213.                $existe = ($this->accion=='CREATE' && $otraEntidad)
  214.                          ||
  215.                          ( $otraEntidad && $entity->getId() != $otraEntidad->getId() );
  216.                if ($existe)
  217.                {
  218.                  $this->session->getFlashBag()->set('danger'
  219.                                                    $this->translator->trans(
  220.                                                         'error.unique.composite',
  221.                                                         array('%className%' => strtoupper($this->translator->trans($this->routeClassName.'.singular',array(),'crud')),
  222.                                                               '%fieldname%' => strtoupper($camposStr)),
  223.                                                         'crud'));
  224.                  return false;
  225.                } 
  226.            }
  227.        }
  228.        return true;
  229.     }
  230.     protected function getNullableConstraints($entity)
  231.     {
  232.         //Singles Unique Constraints
  233.         $nullableFields = array();
  234.         $properties $this->em->getClassMetadata($this->classFullName)->fieldMappings;
  235.         $association $this->em->getClassMetadata($this->classFullName)->associationMappings;
  236.         $formulario $this->getFormulario($entity);
  237.         foreach ($formulario as $field=>$prop)
  238.         {
  239.             if ( isset($properties[$field]) && isset($properties[$field]['nullable']) && !$properties[$field]['nullable'])
  240.             {
  241.                 $nullableFields[$field]=$field;
  242.             }
  243.             if ( isset($association[$field]) &&
  244.                  ( (isset($association[$field]['joinColumns'][0]['nullable']) && !$association[$field]['joinColumns'][0]['nullable']) || (isset($association[$field]['joinTable']['joinColumns'][0]['nullable']) && !$association[$field]['joinTable']['joinColumns'][0]['nullable'])))
  245.             {
  246.                 $nullableFields[$field]=$field;
  247.             }
  248.         }    
  249.         return $nullableFields;
  250.     }
  251.     
  252.     protected function comunCheckNullableConstrains($entity)
  253.     {
  254.         $constraints $this->getNullableConstraints($entity);
  255.         if (count($constraints)>0)
  256.         foreach ($constraints as $key=>$campo)
  257.         {    
  258.             $valor $entity->getFieldValue($campo);
  259.             if ($valor===null || $valor==='' || ($valor instanceof  \Doctrine\Common\Collections\ArrayCollection && $valor->count()== 0))
  260.              {
  261.                   $this->session->getFlashBag()->set('danger'
  262.                                                    $this->translator->trans(
  263.                                                         'error.nullable',
  264.                                                         array('%fieldname%' => strtoupper($this->translator->trans($this->routeClassName.'.fields.'.$campo,array(),'crud'))),
  265.                                                         'crud'));
  266.                   return false;
  267.              }
  268.          } 
  269.        return true;
  270.     }
  271.     protected function checkNonUniqueConstrains($entity)
  272.     {
  273.         $formulario=  $this->getFormulario($entity);
  274.         foreach ($formulario as $campo)
  275.         {
  276.             if ($valor $entity->getFieldValue($campo['nombre']))
  277.             {    
  278.                 if ($campo['type']=='integer' || $campo['type']=='smallint')
  279.                 {
  280.                     if (!is_numeric($valor) || !is_integer($valor*1))
  281.                     {    
  282.                         $this->session->getFlashBag()->set('danger'
  283.                                                        $this->translator->trans(
  284.                                                             'error.integer',
  285.                                                             array('%fieldname%' => strtoupper($this->translator->trans($this->translatorBase.'.fields.'.$campo['nombre'],array(),'crud'))),
  286.                                                             'crud'));
  287.                         return false;
  288.                     }
  289.                 }
  290.                 else
  291.                 if ($campo['type']=='float')
  292.                 {
  293.                     if (!is_numeric($valor) || !is_float($valor*1))
  294.                     {    
  295.                         $this->session->getFlashBag()->set('danger'
  296.                                                        $this->translator->trans(
  297.                                                             'error.float',
  298.                                                             array('%fieldname%' => strtoupper($this->translator->trans($this->translatorBase.'.fields.'.$campo['nombre'],array(),'crud'))),
  299.                                                             'crud'));
  300.                         return false;
  301.                     }
  302.                 }
  303.             }
  304.         }    
  305.        return true;
  306.     }
  307.         
  308.     protected function comunParamsForForm($entity=null)
  309.     {
  310.         $params $this->comunParamsForFunctionsInEntity();
  311.         $params['accion'] = $this->accion;
  312.         $params['showIdInForm'] = $this->showIdInForm;
  313.         $params['entity'] = $entity;
  314.         return $params;
  315.     }
  316.     private function buildForm(&$params)
  317.     {
  318.         
  319.         $builder $this->createFormBuilder($params['entity'], array('allow_extra_fields'=>true));
  320.         
  321.         $formulario $this->getFormulario($params['entity']);
  322.         foreach ($formulario as $item)
  323.         {
  324.             $tipo null;
  325.             $atributos null;
  326.             if (isset($item['atributos']))
  327.             {
  328.                 if (isset($item['atributos']['attr']['data-url']))
  329.                 {
  330.                     $item['atributos']['attr']['data-url'] = $params['url'];
  331.                 }
  332.                 //en caso de que la entidad tenga una relacion ManyToOne con otra y este atributo se llene a partir de haber seleccionado
  333.                 //el valor del parent previamente, por lo que el valor de dicho padre no debe ser modificable y no se muestra
  334.                 if (isset($item['atributos']['attr']['isparent']) and isset($params['paramsRequest']['idParent']))
  335.                 {
  336.                     $idParent $params['paramsRequest']['idParent'];
  337.                     //creando una query que devuelve una lista con solo la entity que tenga el valor del parent seleccionado
  338.                     $item['atributos']['query_builder'] = function (EntityRepository $er) use ($idParent) {
  339.                         return $er->createQueryBuilder('e')
  340.                             ->where('e.id = :id')
  341.                             ->setParameter('id'$idParent);
  342.                     };
  343.                     //eliminando que ponga el placeholder para que seleccione automaticamente el unico valor que hay en la lista devuelta por la query anterior
  344.                     $item['atributos']['empty_value'] = false;
  345.                 }
  346.                 //para el caso de que exista una query_builder como atributo y ademas sea necesario reemplazar algun valor de esa query
  347.                 //y dicho valor debe venir dentro del array de $params
  348.                 if(isset($item['atributos']['attr']['query_builder']))
  349.                 {
  350.                     foreach ($item['atributos']['attr']['query_builder']['replace'] as $key){
  351.                         $item['atributos']['attr']['query_builder']['params'] = str_replace($key$params[$key], $item['atributos']['attr']['query_builder']['params']);
  352.                     }
  353.                     $item['atributos']['query_builder'] = $params['em']->getRepository($item['atributos']['attr']['query_builder']['entity'])->{$item['atributos']['attr']['query_builder']['funcion']}($item['atributos']['attr']['query_builder']['params']);
  354.                     unset($item['atributos']['attr']['query_builder']);
  355.                 }
  356.                 $atributos $item['atributos'];
  357.             }
  358.             if (isset($item['tipo']))
  359.                 $tipo $item['tipo'];
  360.             $nombre $item['nombre'];
  361.             switch ($tipo)
  362.             {
  363. /*                case 'time':
  364.                 $tipo = TimeType::class;
  365.                     break;*/
  366.                 case 'collection':
  367.                     $tipo CollectionType::class;
  368.                     break;
  369.                 case 'date':
  370.                 $tipo DateType::class;
  371.                     $atributos['html5'] = false;
  372. //                $builder->add($nombre, $tipo, $atributos);
  373. //                $builder->get($nombre)->addViewTransformer(new DateTimeToStringTransformer(null, null, 'd-m-Y'));
  374. //                $builder->add($builder->create($nombre,$tipo,$atributos)->addViewTransformer(new DateTimeToStringTransformer()));
  375.                     break;
  376.                 case 'geometria':
  377.                 $tipo "Symfony\Component\Form\Extension\Core\Type\HiddenType";
  378.   //              $builder->add($nombre, $tipo, $atributos);
  379.                     break;
  380.                 case 'biplane_enum':
  381.                     if (isset($atributos['attr']['class']))
  382.                     {
  383.                     $class str_replace('spinbox-input'''$atributos['attr']['class']);
  384.                     if ($class)
  385.                         {
  386.                         $atributos['attr']['class'] = $class;
  387.                         }
  388.                     else
  389.                         {
  390.                         unset($atributos['attr']['class']);
  391.                 }
  392.             }
  393.                     break;
  394.                 case 'subcriber':
  395.                     $builder->addEventSubscriber(new $item['atributos']['class_subcriber']($params['em'], $params['translator']));
  396.                     break;
  397.                 case 'Symfony\Component\Form\Extension\Core\Type\FileType':
  398.                     $params['file'][$nombre] = $atributos['attr']['class'];
  399.                     break;
  400.             }
  401.             if ($tipo != 'subcriber')
  402.             {
  403.                 if ($atributos && isset($atributos['attr']['class']))
  404.                     $atributos['attr']['class'].=' form-control';
  405.                 else
  406.                     $atributos['attr']['class']='form-control';
  407.                 if (strpos($atributos['attr']['class'],'chosen-select')!==false)
  408.                 {
  409.                     $atributos['attr']['class'].=' chosen-pending';
  410.                 }
  411.                 $builder->add($nombre$tipo$atributos);
  412.             }
  413.             }
  414.         return $builder->getForm();
  415.     }
  416.      
  417.     protected function comunParamsForFunctionsInEntity()
  418.     {
  419.         $params = array(
  420.             'em'              => $this->em,
  421.             'rol'             => $this->rol,
  422.             'routeClassName'  => $this->routeClassName,
  423.             'user'            => $this->getUser(),
  424.             'className'       => $this->classFullName,
  425.             'session'         => $this->session,
  426.             'translator'      => $this->translator,
  427.             'translatorBase'  => $this->translatorBase,
  428.             'filterData'      => $this->filterData,
  429.             'paramsRequest'   => $this->paramsRequest,
  430.             'viewWidth'       => $this->session->get('view_width'),
  431.             'logger'          => $this->logger,
  432.         );
  433.         unset($params['paramsRequest']['filterData']);
  434.         return $params;
  435.     }   
  436.     
  437.     protected function comunPersist($entity$flush=true)
  438.     {
  439.         if (!$this->em)
  440.           $this->em $this->getDoctrine()->getManager();
  441.         try 
  442.         {
  443.             $isNew $entity->getId()==null;
  444.             $this->em->persist($entity);
  445.             if($flush)
  446.             {
  447.                 $this->em->flush();
  448.                 if (!$this->ajax)
  449.                 {
  450.                 $texto $isNew 'persist.success.create' 'persist.success.update';
  451.                     $this->session->getFlashBag()->set(
  452.                         'info'
  453.                         $this->translator->trans($texto, array(), 'crud')
  454.                     );
  455.                 }
  456.             }
  457.             return true;
  458.         }
  459.         catch (\Exception $exc)
  460.         {
  461.             if (!$this->ajax)
  462.             {
  463.            $texto $isNew 'persist.fail.create' 'persist.fail.update';
  464.                 $this->session->getFlashBag()->set(
  465.                     'danger',
  466.                     $this->translator->trans($texto, array(), 'crud').' ( '.$exc->getMessage().' )'
  467.                 );
  468.             }
  469.            $this->logger->error($exc->getTraceAsString());
  470.            return false;
  471.         }
  472.     }
  473.   
  474.     protected function comunRemove($entity$flush=true)
  475.     {
  476.         if (!$this->em)
  477.           $this->em $this->getDoctrine()->getManager();
  478.         try {
  479.             $this->em->remove($entity);
  480.             if($flush){
  481.                 $this->em->flush();
  482.                 if (!$this->ajax)
  483.                 {
  484.                     $this->session->getFlashBag()->set('info'$this->translator
  485.                                                                        ->trans('persist.success.delete', array(), 'crud'));           
  486.                 }
  487.             }
  488.             return true;
  489.         } catch (\Exception $exc) {
  490.             if (!$this->ajax)
  491.             {
  492.             $msg $exc->getMessage();
  493.             if (strpos($msg,'Foreign')===false)
  494.                 {
  495.                     $this->session->getFlashBag()->set(
  496.                         'danger'
  497.                         $this->translator->trans('persist.fail.delete', array(), 'crud')
  498.                     );
  499.                 }
  500.             else
  501.                 {
  502.                     $this->session->getFlashBag()->set(
  503.                         'danger'
  504.                         $this->translator->trans('persist.fail.delete_foreign', array(), 'crud')
  505.                     );
  506.                 }
  507.                 
  508.             }
  509.             $this->logger->error($msg);
  510.             return false;
  511.         }
  512.     }
  513.     
  514.     protected function setClassMap($routeClassName)
  515.     {
  516.         $parseConfig = new ParseConfig();
  517.         $config $parseConfig->parse($this->container);
  518.         $this->booleans $config['crudBooleans'];
  519.         $this->buttons $config['crudButtons'];
  520.         $config $config['crudMapping'];
  521.         $this->inline false;
  522.         $inline strrpos($routeClassName'_inline');
  523.         if ($inline !== false)
  524.         {
  525.             $routeClassName substr($routeClassName0$inline);
  526.             $this->inline true;
  527.         }
  528. //        $config = $this->container->getParameter('crudmapping');
  529.         if (isset($config[$routeClassName]))
  530.         {
  531.             $this->routeClassName $routeClassName;
  532.             $properties $config[$routeClassName];
  533.             if (isset($properties['allowedRol']))
  534.             {
  535.                 $this->allowedRol $properties['allowedRol'];
  536.             }
  537.             if (isset($properties['allowedINDEX']))
  538.             {
  539.                 $this->allowedINDEX $properties['allowedINDEX'];
  540.             }
  541.             if (isset($properties['allowedCREATE']))
  542.             {
  543.                 $this->allowedCREATE $properties['allowedCREATE'];
  544.             }
  545.             if (isset($properties['allowedUPDATE']))
  546.             {
  547.                 $this->allowedUPDATE $properties['allowedUPDATE'];
  548.             }
  549.             if (isset($properties['allowedDELETE']))
  550.             {
  551.                 $this->allowedDELETE $properties['allowedDELETE'];
  552.             }
  553.             if (isset($properties['allowedSHOW']))
  554.             {
  555.                 $this->allowedSHOW $properties['allowedSHOW'];
  556.             }
  557.             
  558.             if (!$this->inline)
  559.             {
  560.                 $this->translatorBase $properties['translatorBase'];
  561.                 if (isset($properties['className']))
  562.                 {
  563.                     $this->className     $properties['className'];
  564.                 }
  565.                 if (isset($properties['fabricante']))
  566.                 {
  567.                     $this->fabricante    $properties['fabricante'];
  568.                 }
  569.                 if (isset($properties['bundle']))
  570.                 {
  571.                     $this->bundle        $properties['bundle'];
  572.                 }
  573.                 if (isset($properties['bundlename']))
  574.                 {
  575.                     $this->bundleName    $properties['bundlename'];
  576.                 }
  577.                 if (isset($properties['entityfolder']))
  578.                 {
  579.                     $this->entityFolder  $properties['entityfolder'];
  580.                 }
  581.                 if (isset($properties['classfullname']))
  582.                 {
  583.                     $this->classFullName $properties['classfullname'];
  584.                 }
  585.                 $this->modal $properties['modal'];
  586.                 $this->widthModalForm $properties['widthModalForm'];
  587.                 $this->heightModalForm $properties['heightModalForm'];
  588.                 $this->widthModalShow $properties['widthModalShow'];
  589.                 $this->heightModalShow $properties['heightModalShow'];
  590.                 if (isset($properties['indexInnerView']))
  591.                     $this->indexInnerView $properties['indexInnerView'];
  592.                 if (isset($properties['twigIndexName']))
  593.                     $this->twigIndexName $properties['twigIndexName'];
  594.                 else
  595.                     if (!$this->twigIndexName)
  596.                     $this->twigIndexName self::defaultTwigIndexName;
  597.                 if (isset($properties['twigNewName']))
  598.                 { 
  599.                     $this->twigNewName $properties['twigNewName'];
  600.                 }
  601.                 else
  602.                     if (!$this->twigNewName || $this->twigNewName==self::defaultTwigNewName)
  603.                     {
  604.                         if ($this->modal)
  605.                         {
  606.                             $this->twigNewName self::defaultModalTwigNewName;
  607.                         }
  608.                         else
  609.                         {
  610.                             $this->twigNewName self::defaultTwigNewName;
  611.                         }
  612.                     }
  613.                 if (isset($properties['twigEditName']))
  614.                     $this->twigEditName $properties['twigEditName'];
  615.                 else
  616.                     if (!$this->twigEditName || $this->twigEditName==self::defaultTwigEditName)
  617.                     {
  618.                         if ($this->modal)
  619.                             $this->twigEditName self::defaultModalTwigEditName;
  620.                         else
  621.                             $this->twigEditName self::defaultTwigEditName;
  622.                     }
  623.                 if (isset($properties['twigShowName']))
  624.                     $this->twigShowName $properties['twigShowName'];
  625.                 else
  626.                     if (!$this->twigShowName || $this->twigShowName==self::defaultTwigShowName)
  627.                     {
  628.                         if ($this->modal)
  629.                             $this->twigShowName self::defaultModalTwigShowName;
  630.                         else
  631.                             $this->twigShowName self::defaultTwigShowName;
  632.                     }
  633.                 if (isset($properties['twigexcelname']))
  634.                     $this->twigExcelName $properties['twigexcelname'];
  635.                 else
  636.                     if (!$this->twigExcelName || $this->twigExcelName==self::defaultTwigExcelName)
  637.                     {
  638.                         if ($this->modal)
  639.                             $this->twigExcelName self::defaultTwigExcelName;
  640.                         else
  641.                             $this->twigExcelName self::defaultTwigExcelName;
  642.                     }
  643.                 $this->filterColumns $properties['filterColumns'];
  644.                 if (!isset($this->showColumns))
  645.                 $this->showColumns $properties['showColumns'];
  646.                 if (!isset($this->formColumns))
  647.                 $this->formColumns $properties['formColumns'];
  648.                 if (isset($properties['showIdInForm']))
  649.                     $this->showIdInForm $properties['showIdInForm'];
  650.                 else
  651.                     if (!isset($this->showIdInForm))
  652.                         $this->showIdInForm false;
  653.                 if (isset($properties['showInIndex']))
  654.                 $this->showInIndex $properties['showInIndex'];
  655.                 else
  656.                     if (!isset($this->showInIndex))
  657.                         $this->showInIndex false;
  658.                 if (isset($properties['newInIndex']))
  659.                 $this->newInIndex $properties['newInIndex'];
  660.                 else
  661.                     if (!isset($this->newInIndex))
  662.                         $this->newInIndex true;
  663.                 if (isset($properties['deleteInIndex']))
  664.                 $this->deleteInIndex $properties['deleteInIndex'];
  665.                 else
  666.                     if (!isset($this->deleteInIndex))
  667.                         $this->deleteInIndex true;
  668.                 if (isset($properties['editInIndex']))
  669.                 $this->editInIndex $properties['editInIndex'];
  670.                 else
  671.                     if (!isset($this->editInIndex))
  672.                         $this->editInIndex true;
  673.                 if (isset($properties['showFilter']))
  674.                 $this->showFilter $properties['showFilter'];
  675.                 else
  676.                     if (!isset($this->showFilter))
  677.                         $this->showFilter true;
  678.                 if (isset($properties['showPaginator']))
  679.                     $this->showPaginator $properties['showPaginator'];
  680.                 else
  681.                     if (!isset($this->showPaginator))
  682.                         $this->showPaginator true;
  683.                 if (isset($properties['columnAction']))
  684.                     $this->columnAction $properties['columnAction'];
  685.                 else
  686.                     if (!isset($this->columnAction))
  687.                         $this->columnAction true;
  688.                 if (isset($properties['search']))
  689.                     $this->search $properties['search'];
  690.                 else
  691.                     if (!isset($this->search))
  692.                         $this->search true;
  693.                 if (isset($properties['tableInfo']))
  694.                     $this->tableInfo $properties['tableInfo'];
  695.                 else
  696.                     if (!isset($this->tableInfo))
  697.                         $this->tableInfo true;
  698.                 if (isset($properties['scrollY']))
  699.                     $this->scrollY $properties['scrollY'];
  700.                 else
  701.                     if (!isset($this->scrollY))
  702.                         $this->scrollY null;
  703.                 if (isset($properties['widthLabel']))
  704.                     $this->widthLabel $properties['widthLabel'];
  705.                 else
  706.                     if (!isset($this->widthLabel))
  707.                         $this->widthLabel '20%';
  708.             }
  709.             else
  710.             {
  711.                 $this->twigIndexName self::defaultTwigInlineIndexName;
  712.             }
  713.         }
  714.         else
  715.         {
  716.             throw new \RuntimeException(
  717.                 $this->translator->trans(
  718.                     'error.class_not_defined', array('%className%' => $this->routeClassName), 'crud'
  719.                 )
  720.             );
  721.         }
  722.         return $config;
  723.     }        
  724.     protected function comunSetFileFields($params$form$entity$uploadDir "uploads"$hashKey '')
  725.     {        
  726.         $deleteFiles = array();
  727.         if (isset($params['file']))
  728.         {
  729.             $oldfile=$this->request->get('oldfile');
  730.             foreach ($params['file'] as $fieldName=>$class
  731.             {
  732.                 if ($oldfile && isset($oldfile[$fieldName]) && $oldfile[$fieldName]=='deleted')
  733.                 {
  734.                     $deleteFiles[] = $fieldName;
  735.                 }
  736.                 $file $form->get($fieldName);
  737.                 $viewData $file->getViewData();
  738.                 if ($viewData instanceof \Symfony\Component\HttpFoundation\File\UploadedFile)
  739.                 {
  740.                     $fileName $this->comunUpload($viewData$uploadDir$hashKey);
  741.                     if ($fileName)
  742.                     {
  743.                         $adjunto = new $class();
  744.                         $adjunto->setArchivo($viewData->getClientOriginalName());
  745.                         $adjunto->setRuta($uploadDir);
  746.                         $adjunto->setArchivoHash($fileName);
  747.                         $adjunto->setSize(filesize($uploadDir.'/'.$fileName));
  748.                         $this->em->persist($adjunto);
  749.                         $this->em->flush();
  750.                         $setMethod 'set'.ucfirst($fieldName);
  751.                         $entity->$setMethod($adjunto);
  752.                     }
  753.                 }
  754.                 else
  755.                 {
  756.                     if ($oldfile && isset($oldfile[$fieldName]) && $oldfile[$fieldName]=='deleted')
  757.                     {
  758.                         $setMethod 'set'.ucfirst($fieldName);
  759.                         $entity->$setMethod(null);
  760.                     }
  761.                 }
  762.             }
  763.         }
  764.         return $deleteFiles;
  765.     }        
  766.     protected function setParamsRequest()
  767.     {
  768.         $this->paramsRequest = array();
  769.         $keys $this->request->query->keys();
  770.         foreach ($keys as $index=>$key)
  771.         {
  772.            $this->paramsRequest[$key]=$this->request->get($key); 
  773.         }
  774.         $keys $this->request->attributes->keys();
  775.         foreach ($keys as $index=>$key)
  776.         {
  777.             if (strpos($key,'_')!==&& $key!='id' && $key!='routeClassName' && $key!='filterdata')
  778.             {
  779.                 $this->paramsRequest[$key]=$this->request->get($key); 
  780.             }
  781.         }
  782.         $keys $this->request->request->keys();
  783.         foreach ($keys as $index=>$key)
  784.         {
  785.             if ($key!='crud_type')
  786.             {
  787.                 $this->paramsRequest[$key]=$this->request->get($key); 
  788.             }
  789.         }
  790.     }
  791.         
  792.     protected function setFilterData($routeClassName)
  793.     {
  794.         $this->filterData $this->request->get('filterData');
  795.         if (!$this->filterData)
  796.           $this->filterData=$this->session->get($routeClassName);
  797.         if (!$this->filterData)
  798.           $this->filterData=array();
  799.     }
  800.     
  801.     protected function setInitialValues($rol$routeClassName)
  802.     {
  803.         $this->rol $rol;
  804.         $this->ajax $this->request->get('_xml_http_request')==='true';
  805.         $this->setUtilProperties();
  806.         $this->setFilterData($routeClassName);
  807.         $this->setParamsRequest();
  808.         $this->setClassMap($routeClassName);
  809.     }   
  810.     protected function setUtilProperties()
  811.     {
  812.     }   
  813.     
  814.     protected function comunUpload($file$uploadDir$hashKey)
  815.     {
  816.         if ($file){
  817.             $extension pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
  818.             if (!$extension) {
  819.                 // no se puede deducir la extensión
  820.                 $extension 'bin';
  821.             }
  822.             $fileName $hashKey rand(199999999) . '.' $extension;
  823.             rtrim($uploadDir,"/");
  824.             $file->move($uploadDir,$fileName);
  825.             return $fileName;
  826.         }else{
  827.             return null;
  828.         }        
  829.     }
  830.     
  831.     /* 
  832.      * MÉTODOS ASOCIADOS A LA ACCIÓN INDEX
  833.      */
  834.     public function indexAction($rol$routeClassName)
  835.     {     
  836.         $this->setInitialValues($rol$routeClassName);
  837.         $this->accion 'INDEX';
  838.         if (!$this->allowActionExecution())
  839.         {
  840.             return $this->render('@crud\\accesDenied.html.twig');
  841.         }
  842.         if (!$this->inline)
  843.         {
  844.             $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  845.             $paramsForFunctionInEntity['showIdInForm'] = $this->showIdInForm;
  846.             $this->indexPrepareFilterForm($paramsForFunctionInEntity);
  847.             $paramsForFunctionInEntity['filterForm']= $this->formularioFiltro;
  848.             $this->entities $this->indexLoadEntities($paramsForFunctionInEntity);
  849.             $this->session->set($routeClassName,$this->filterData);
  850.             //$this->paginator = $this->indexCreatePaginator($this->entities);
  851.             $this->paginator null;
  852.         }
  853.         $params $this->indexParamsForTwig($this->em);
  854.         if (isset($this->paramsRequest['view']))
  855.             return $this->render($this->paramsRequest['view'], $params);
  856.         else
  857.             return $this->render($this->twigIndexName$params);
  858.         
  859.     }
  860.     
  861.     protected function getFormFilter()
  862.     {
  863.         $formulario = array();
  864.         $R = new \ReflectionClass($this->classFullName);
  865.         $fields $R->getProperties(\ReflectionProperty::IS_PRIVATE);
  866.         $properties $this->em->getClassMetadata($this->classFullName)->fieldMappings;
  867.         $association $this->em->getClassMetadata($this->classFullName)->associationMappings;
  868.         foreach ($fields as $field)
  869.         {
  870.             $fieldname $field->name;
  871.             $label $this->translator->trans($this->routeClassName.'.fields.'.$fieldname, array(), 'crud');
  872.             if ($label == $this->routeClassName.'.fields.'.$fieldname)
  873.             {
  874.                 $label $this->translator->trans($this->translatorBase.'.fields.'.$fieldname, array(), 'crud');
  875.             }
  876.             
  877.             if (isset($properties[$field->name]))
  878.             {
  879.                 $prop $properties[$fieldname];
  880.                 if (isset($prop['id']) && $prop['id'] && (!isset($this->showIdInForm) || !$this->showIdInForm))
  881.                 {
  882.                     continue;
  883.                 }
  884.                 $formulario[$fieldname]=array('nombre'   =>$fieldname,
  885.                                               'tipo'     => null,
  886.                                               'type'     => $prop['type'],
  887.                                               'atributos'=> array('label' => $label,
  888.                                                                   'required' => false,
  889.                                                                   'attr'=>array('style'=>'width: 100%')));
  890.                 if ($prop['type']=='integer' || $prop['type']=='smallint')
  891.                 {
  892.                     $this->getFormFilterInteger($fieldname$prop$formulario);
  893.                 }
  894.                 if ($prop['type']=='boolean')
  895.                 {    
  896.                     $this->getFormFilterBoolean($fieldname$prop$formulario);
  897.                 }   
  898.                 if ($prop['type']=='datetime')
  899.                 {
  900.                     $this->getFormFilterDateTime($fieldname$prop$formulario);
  901.                 }
  902.             }
  903.             if (isset($association[$field->name]))
  904.             {    
  905.                 $prop $association[$fieldname];
  906.                 if ((isset($prop['id']) && $prop['id'] && !$this->showIdInForm
  907.                     ||
  908.                     $this->isAdjunto($prop['targetEntity']))
  909.                     continue;
  910.                 $this->getFormFilterAssociation($fieldname$prop$formulario);
  911.             }  
  912.         }    
  913.         return $formulario;
  914.     }   
  915.     
  916.     protected function getFormFilterInteger($fieldname$prop, &$formulario)
  917.     {
  918.         $formulario[$fieldname]['atributos']['attr']['class'] = 'spinbox-input';                
  919.         $formulario[$fieldname]['atributos']['attr']['full_width'] = true;                
  920.     }   
  921.    
  922.     protected function getFormFilterBoolean($fieldname$prop, &$formulario)
  923.     {
  924.         $formulario[$fieldname]['tipo'] = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
  925.         $formulario[$fieldname]['atributos']['choices']=array_flip(array('true'=>$this->translator->trans('choice_value.yes', array(), 'crud'),
  926.                                                               'false'=>$this->translator->trans('choice_value.no', array(), 'crud')));
  927.         $formulario[$fieldname]['atributos']['placeholder'] = $this->translator->trans('choice_value.empty_value',array(),'crud');
  928.         $formulario[$fieldname]['atributos']['empty_data'] = null;
  929.     }   
  930.    
  931.     protected function getFormFilterDateTime($fieldname$prop, &$formulario)
  932.     {
  933.         $label $formulario[$fieldname]['atributos']['label'];
  934.         $formulario[$fieldname.'_WWdesdeWW']=array(
  935.             'nombre'    => $fieldname.'_WWdesdeWW',
  936.             'tipo'      => null,//'text',
  937.             'type'      => $prop['type'],
  938.             'atributos' => array(
  939.                 'label' => $label.
  940.                            ' '.
  941.                            $this->translator->trans('range_values.since', array(), 'crud').':',
  942.                 'required' => false,
  943.                 'attr'     => array(
  944.                     'style'=>'width: 100%'
  945.                 )
  946.             )
  947.         );
  948.         $formulario[$fieldname.'_WWhastaWW']=array(
  949.             'nombre'    =>$fieldname.'_WWhastaWW',
  950.             'tipo'      => null,//'text',
  951.             'type'      => $prop['type'],
  952.             'atributos' => array(
  953.                 'label' => $label.
  954.                            ' '.
  955.                            $this->translator->trans('range_values.to', array(), 'crud').':',
  956.                 'required' => false,
  957.                 'attr'     => array(
  958.                     'style'=>'width: 100%'
  959.                 )
  960.             )
  961.         );
  962.         if (isset($prop['columnDefinition']) && $prop['columnDefinition']=='fecha')
  963.         {    
  964.             $formulario[$fieldname.'_WWdesdeWW']['tipo'] = 'date';
  965.             $formulario[$fieldname.'_WWdesdeWW']['atributos']['attr']['class']='campo_fecha date-picker';
  966.             $formulario[$fieldname.'_WWdesdeWW']['atributos']['attr']['data-date-format']="dd-mm-yyyy";                  
  967.             $formulario[$fieldname.'_WWhastaWW']['tipo'] = 'date';
  968.             $formulario[$fieldname.'_WWhastaWW']['atributos']['attr']['class']='campo_fecha date-picker';
  969.             $formulario[$fieldname.'_WWhastaWW']['atributos']['attr']['data-date-format']="dd-mm-yyyy";                  
  970.         }
  971.         unset($formulario[$fieldname]);
  972.     }   
  973.    
  974.     protected function getFormFilterAssociation($fieldname$prop, &$formulario)
  975.     {
  976.         $label $this->translator->trans($this->routeClassName.'.fields.'.$fieldname, array(), 'crud');
  977.         if ($label == $this->routeClassName.'.fields.'.$fieldname)
  978.         {
  979.             $label $this->translator->trans($this->translatorBase.'.fields.'.$fieldname, array(), 'crud');
  980.         }
  981.         
  982.         $formulario[$fieldname]=array(
  983.             'nombre'          => $fieldname,
  984.             'tipo'            => EntityType::class,
  985.             'type'            => 'association',
  986.             'association'     => $prop['type'],
  987.             'atributos'       => array(
  988.                 'label'       => $label,
  989.                 'required'    => false,
  990.                 'class'       => $prop['targetEntity'],
  991.                 'placeholder' => $this->translator->trans('choice_value.empty_value', array(), 'crud'),
  992.                 'empty_data'  => null,
  993.                 'multiple'    => true,
  994.                 'attr'        => array(
  995.                     'class'   =>'chosen-select',
  996.                     'style'   =>'width: 100%',
  997.                     'data-placeholder' => $this->translator->trans('choice_value.empty_value', array(), 'crud')
  998.                 )
  999.             )
  1000.         );
  1001.     }   
  1002.    
  1003.     protected function isAdjunto($aClassName)
  1004.     {
  1005.        $r = new \ReflectionClass($aClassName);
  1006.        return $r->isSubclassOf('App\Crud\Entity\crudAdjunto');
  1007.     }   
  1008.     
  1009.     private function indexShowFields()
  1010.     {
  1011.         $showFields = array();
  1012.         $translator $this->translator;
  1013.         $className $this->classFullName;
  1014.         $R = new \ReflectionClass($className);
  1015.         $fields $R->getProperties(\ReflectionProperty::IS_PRIVATE);
  1016.         $properties $this->em->getClassMetadata($className)->fieldMappings;
  1017.         $association $this->em->getClassMetadata($className)->associationMappings;
  1018.         foreach ($fields as $field)
  1019.         {
  1020.             $fieldname $field->name;
  1021.             $label $translator->trans($this->routeClassName.'.fields.'.$fieldname, array(), 'crud');
  1022.             if ($label == $this->routeClassName.'.fields.'.$fieldname)
  1023.             {
  1024.                 $label $translator->trans($this->translatorBase.'.fields.'.$fieldname, array(), 'crud');
  1025.             }
  1026.             if (isset($properties[$field->name]))
  1027.             {
  1028.                 $prop $properties[$fieldname];
  1029.                 if (isset($prop['id']) && $prop['id'] && !$this->showIdInForm)
  1030.                     continue;
  1031.                 $showFields[$fieldname]=array('nombre' => $fieldname,
  1032.                                                 'type' => $prop['type'],
  1033.                                               'label'  => $label);
  1034.                 if (isset($prop['columnDefinition']))
  1035.                 {
  1036.                     $showFields[$fieldname]['type'] = $prop['columnDefinition'];
  1037.                 }        
  1038.                    
  1039.             }
  1040.             if (isset($association[$field->name]))
  1041.             {    
  1042.                 $prop $association[$fieldname];
  1043.                 if ((isset($prop['id']) && $prop['id'] && !$params['showIdInForm']) 
  1044.                     ||
  1045.                     (isset($prop['type']) && ($prop['type']==|| $prop['type']==4)))
  1046.                     continue;
  1047.                 $showFields[$fieldname]=array(
  1048.                     'nombre' => $fieldname,
  1049.                     'label'  => $label
  1050.                 );
  1051.                 if($this->isAdjunto($prop['targetEntity']))
  1052.                 {
  1053.                     $showFields[$fieldname]['type'] = 'attach';
  1054.                 }
  1055.             }    
  1056.         }    
  1057.         return $showFields;
  1058.     }
  1059.     
  1060.     protected function showGetFields($entity=null)
  1061.     {
  1062.         $showFields $this->indexShowFields();
  1063.         return $showFields;
  1064.     }   
  1065.     
  1066.     protected function indexGetFields()
  1067.     {
  1068.         $indexFields $this->indexShowFields();
  1069.         return $indexFields;
  1070.     }   
  1071.     
  1072.     protected function excelGetFields()
  1073.     {
  1074.         $excelFields $this->indexGetFields();
  1075.         
  1076.         return $excelFields;
  1077.     }   
  1078.     
  1079.     protected function indexParamsForTwig()
  1080.     {
  1081.         $params = array();
  1082.         $params['routeClassName'] = $this->routeClassName;
  1083.         $params['contenedor'] = $this->routeClassName;
  1084.         $params['imageWidth'] = '70px';
  1085.         foreach ($this->paramsRequest as $key=>$value)
  1086.         {
  1087.             if ($key!='filterData')
  1088.             {
  1089.                 $params[$key]=$value;
  1090.             }
  1091.         }
  1092.         $params['now']  = new \DateTime();
  1093.         if ($this->indexInnerView)
  1094.             $params['index_view'] = $this->indexInnerView;
  1095.         else
  1096.             if (!$this->modal)
  1097.                 $params['index_view'] = '@crud\crud\index_inner.html.twig';
  1098.             else
  1099.                 $params['index_view'] = '@crud\crud\index_inner_modal.html.twig';
  1100.         $params['inline'] = $this->inline;
  1101.         if (!$this->inline)
  1102.         {
  1103.            $className $this->classFullName;
  1104.            $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1105.            $paramsForFunctionInEntity['showIdInForm'] = $this->showIdInForm;
  1106.            $params['indexFields']    = $this->indexGetFields();
  1107.            $params['rol']            = $this->rol;
  1108.            $params['className']      = $this->classFullName;
  1109.            $params['formFilter']     = $this->formFilter->createView();
  1110.            $params['filterActive']   = $this->filterActive;
  1111.            $params['filterColumns']  = $this->filterColumns;
  1112.            $params['showInIndex']    = $this->showInIndex;
  1113.            $params['newInIndex']     = $this->newInIndex;
  1114.            $params['editInIndex']    = $this->editInIndex;
  1115.            $params['deleteInIndex']  = $this->deleteInIndex;
  1116.            $params['filterData']     = $this->filterData;
  1117.            $params['showFilter']     = $this->showFilter;
  1118.            $params['showPaginator']  = $this->showPaginator;
  1119.            $params['columnAction']   = $this->columnAction;
  1120.            $params['search']         = $this->search;
  1121.            $params['tableInfo']      = $this->tableInfo;
  1122.            $params['scrollY']        = $this->scrollY;
  1123.            $params['booleans']       = $this->booleans;
  1124.            $params['buttons']        = $this->buttons;
  1125.            $params['entities']       = $this->paginator $this->paginator->getCurrentPageResults() : ($this->entities instanceof \Doctrine\ORM\QueryBuilder $this->entities->getQuery()->getResult() : $this->entities);
  1126.            $params['paginator']      = $this->paginator;
  1127.            $params['paramsRequest']  = $this->paramsRequest;
  1128.            $params['heightModalForm']  = $this->heightModalForm;
  1129.            $params['widthModalForm']  = $this->widthModalForm;
  1130.            $params['heightModalShow']  = $this->heightModalShow;
  1131.            $params['widthModalShow']  = $this->widthModalShow;
  1132.            $params['widthLabel']    = $this->widthLabel;
  1133.            $paramsForFunctionInEntity['entities'] = $params['entities'];
  1134.            $paramsEntity $className::getParamsForIndexTwig($paramsForFunctionInEntity);
  1135.            $params array_merge($params$paramsEntity);
  1136.         }
  1137.        return $params;
  1138.     }
  1139.     protected function indexCreatePaginator($entities)
  1140.     {
  1141.         if ($this->showPaginator)
  1142.         {    
  1143.             $adapter = new DoctrineORMAdapter($entities);
  1144.             $pagerfanta = new Pagerfanta($adapter);
  1145.             $pagerfanta->setMaxPerPage($this->maxPerPage);
  1146.             if (!$page $this->request->get('page'))
  1147.             {
  1148.                 $page 1;
  1149.             }
  1150.             try
  1151.             {
  1152.                 $pagerfanta->setCurrentPage($page);
  1153.             } 
  1154.             catch (NotValidCurrentPageException $e)
  1155.             {
  1156.                 throw new NotFoundHttpException();
  1157.             }
  1158.             return $pagerfanta;
  1159.         }
  1160.         else
  1161.             return null;
  1162.     }
  1163.     
  1164.     protected function indexLoadEntities($params)
  1165.     {
  1166.         $params['logger'] = $this->logger;
  1167.         $query $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->loadResults($params$this->filterData);
  1168.         return $query->getQuery()->getResult();
  1169.     }
  1170.     protected function indexCleanFilterData()
  1171.     {
  1172.         foreach ($this->filterData as $key=>$valor)
  1173.         {
  1174.             if ((is_array($valor) && empty($valor)) || 
  1175.                 (($valor instanceof \Doctrine\Common\Collections\ArrayCollection) && $valor->count()==0) || 
  1176.                 $valor=='')
  1177.             {
  1178.                 unset($this->filterData[$key]);
  1179.             }
  1180.         }
  1181.     }
  1182.     
  1183.     public function indexPrepareFilterForm($params)
  1184.     {
  1185.         $this->indexCleanFilterData();
  1186.         if ($this->request->getMethod()=="POST")
  1187.         {
  1188.             $this->filterData=array();
  1189.             //Tomar los datos del request
  1190.             if ($this->request->get('form'))
  1191.             {
  1192.                 $this->filterData $this->request->get('form');
  1193.             }
  1194.             $this->indexCleanFilterData();
  1195.         }
  1196.         
  1197. //        $classFullName = $this->classFullName;
  1198. //        $classFullName::setFiltros($params, $this->filterData);
  1199.         $this->setFiltros();
  1200.         $this->formFilter $this->indexBuildFilterForm($this->filterData$params);
  1201.         
  1202.         $this->filterActive false//Para poner abierto o cerrado el panel de filtros
  1203.         foreach ($this->filterData as $value
  1204.         {
  1205.             if (!empty($value)) 
  1206.             {
  1207.                 $this->filterActive true;
  1208.                 break;
  1209.             }
  1210.         }    
  1211.     }   
  1212.     protected function allowActionExecution($entity=null)
  1213.     {
  1214.         if ($this->allowedRol)
  1215.         {
  1216.             return $this->isAllowed($this->allowedRol);
  1217.         }
  1218.         else
  1219.         {
  1220.             $var 'allowed'.$this->accion;
  1221.             if ($this->$var)
  1222.             {
  1223.                 return $this->isAllowed($this->$var);
  1224.             }
  1225.             else
  1226.             {
  1227.                 return false;
  1228.             }
  1229.         }
  1230.     }
  1231.     
  1232.     private function isAllowed($rule)
  1233.     {
  1234.         if (is_array($rule))
  1235.         {
  1236.             return in_array($this->rol$rule);
  1237.         }
  1238.         else
  1239.         {
  1240.             return $rule=='all' || $rule == $this->rol
  1241.         }
  1242.     }
  1243.     
  1244.     protected function setFiltros()
  1245.     {
  1246.         
  1247.     }
  1248.     
  1249.     private function indexBuildFilterForm($data$params)
  1250.     {
  1251.         $builder $this->createFormBuilder($data, array(
  1252.             'csrf_protection' => false,
  1253.             'validation_groups' => array('filtering'),
  1254.         ));
  1255.         $this->formularioFiltro $this->getFormFilter();
  1256.         foreach ($this->formularioFiltro as $item)
  1257.         {
  1258.             $tipo null;
  1259.             $atributos = array('mapped'=>false);
  1260.             if (isset($item['tipo']))
  1261.               $tipo $item['tipo'];
  1262.             if (isset($item['atributos']))
  1263.               $atributos array_merge ($atributos$item['atributos']);
  1264.             $nombre $item['nombre'];
  1265.             if ($data && isset($data[$nombre]) && $data[$nombre]!='null' && $data[$nombre]!='not null')
  1266.             {
  1267.                 if (isset($item['type']) && $item['type']=='association' && $data[$nombre] != '')
  1268.                 {
  1269.                     if (isset($atributos['multiple']) && $atributos['multiple']==true)
  1270.                     {
  1271.                         if ($data[$nombre] instanceof \Doctrine\Common\Collections\ArrayCollection)
  1272.                         {
  1273.                             $data[$nombre] = $data[$nombre]->toArray();
  1274.                         }
  1275.                         if (!is_array($data[$nombre]))
  1276.                             $data[$nombre]=array($data[$nombre]);
  1277.                         $atributos['data'] = new \Doctrine\Common\Collections\ArrayCollection();
  1278.                         foreach ($data[$nombre] as $key=>$option)
  1279.                         {
  1280.                             if ($option instanceof \Crud\Entity\crudEntity)
  1281.                                 $entidad $option;
  1282.                             else
  1283.                                 $entidad $this->em->getRepository($atributos['class'])->find($option);
  1284.                             $entidad $this->em->merge($entidad);
  1285.                             $atributos['data'][]=$entidad;
  1286.                         }    
  1287.                     }
  1288.                     else
  1289.                     {
  1290.                         $entidad $this->em->getRepository($atributos['class'])->find($data[$nombre]); 
  1291.                         $atributos['data']=$entidad;
  1292.                     }
  1293.                 }
  1294.                 else
  1295.                     if ($tipo=='Biplane\EnumBundle\Form\Type\EnumType' && isset($atributos['enum_class']) && $data[$nombre] != '' )
  1296.                     {
  1297.                         if (is_array($data[$nombre]))
  1298.                         {
  1299.                             foreach ($data[$nombre] as $valor)
  1300.                         {
  1301.                                 $enum $this->getEnumFilterData($atributos['enum_class'], $valor);
  1302.                                 $atributos['data'][] = $enum;
  1303.                         }
  1304.                         }
  1305.                         else
  1306.                         {
  1307.                             $enum $this->getEnumFilterData($atributos['enum_class'], $data[$nombre]);
  1308.                         $atributos['data']=$enum;
  1309.                         }    
  1310.                     }    
  1311.                     else
  1312.                         if (($tipo=='entity' || $tipo==EntityType::class) && isset($atributos['class']) && $data[$nombre] != '' )
  1313.                         {
  1314.                             if (isset($atributos['multiple']) && $atributos['multiple']==true)
  1315.                             {
  1316.                                 $collecion = new \Doctrine\Common\Collections\ArrayCollection();
  1317.                                 if (!is_array($data[$nombre]))
  1318.                                     $data[$nombre]=array($data[$nombre]);
  1319.                                 foreach ($data[$nombre] as $option)
  1320.                                 {
  1321.                                     $entidad $this->em->getRepository($atributos['class'])->find($option);
  1322.                                     $collecion[]=$entidad;
  1323.                                 }  
  1324.                                 $atributos['data']=$collecion;
  1325.                             }
  1326.                             else
  1327.                             {
  1328.                                 $entidad $this->em->getRepository($atributos['class'])->find($data[$nombre]); 
  1329.                                 $atributos['data']=$entidad;
  1330.                             }
  1331.                         }    
  1332.                         else
  1333.                         {    
  1334.                             $atributos['data']=$data[$nombre];
  1335.                         }
  1336.             }    
  1337.             if ($tipo=="date")
  1338.             {
  1339.                 $tipo=null;//"text";
  1340.                 $builder->add($nombre,$tipo,$atributos);
  1341.                 if (isset($data[$nombre]))
  1342.                 {
  1343.                     $atributos['data']=$data[$nombre];
  1344.                 }
  1345.                 //$builder->get($nombre)->addViewTransformer(new DateTimeToStringTransformer(null,null,'d-m-Y'));
  1346.             }
  1347.             else    
  1348.             if ($tipo=="Biplane\EnumBundle\Form\Type\EnumType")
  1349.             {
  1350.                 if (isset($atributos['attr']['class']))
  1351.                 {
  1352.                     $class str_replace('spinbox-input'''$atributos['attr']['class']);
  1353.                     if ($class)
  1354.                         $atributos['attr']['class']=$class;
  1355.                     else
  1356.                         unset($atributos['attr']['class']);
  1357.                 }    
  1358. /*                if (isset($atributos['enum_class']))
  1359.                 {
  1360.                     $atributos['choices'] = $atributos['enum_class']::getReadables();
  1361.                     unset($atributos['enum_class']);
  1362.                 }*/
  1363.                 $builder->add($nombre,'Biplane\EnumBundle\Form\Type\EnumType',$atributos);
  1364.             }
  1365.             else    
  1366.             {    
  1367.                 $builder->add($nombre,$tipo,$atributos);        
  1368.             }    
  1369.         }    
  1370.         return $builder->getForm();
  1371.     }
  1372.     
  1373.     private function getEnumFilterData($enumClass$valor)
  1374.     {
  1375.         try
  1376.         {
  1377.                 $enum $enumClass::create($valor);
  1378.         }
  1379.         catch (\Exception $exc)
  1380.         {
  1381.             if (is_numeric($valor))
  1382.                 $enum $enumClass::create((int)$valor);
  1383.         }
  1384.         return $enum;
  1385.     }
  1386.     /* 
  1387.      * MÉTODOS ASOCIADOS A LA ACCIÓN NEW
  1388.      */
  1389.     public function newAction($rol$routeClassName)
  1390.     {
  1391.         $this->setInitialValues($rol$routeClassName);
  1392.         $this->accion 'CREATE';
  1393.         if (!$this->allowActionExecution())
  1394.         {
  1395.             return $this->render('@crud\\accesDenied.html.twig');
  1396.         }
  1397.         
  1398.         
  1399.         $entity $this->createEntity();
  1400.             
  1401.         $this->setValuesBeforeForm($entity);
  1402.         $params $this->comunParamsForForm($entity);
  1403.         $this->formulario $this->buildForm($params);
  1404.         $paramsForTwigNew $this->newParamsForTwig($entity); 
  1405.         return $this->render($this->twigNewName$paramsForTwigNew);        
  1406.     }
  1407.     protected function newParamsForTwig($entity)
  1408.     {
  1409.         $params= array(
  1410.             'rol'            => $this->rol,
  1411.             'routeClassName' => $this->routeClassName,
  1412.             'contenedor'     => $this->routeClassName,
  1413.             'entity'         => $entity,
  1414.             'form'           => $this->formulario->createView(),
  1415.             'filterData'     => $this->filterData,
  1416.             'paramsRequest'  => $this->paramsRequest,
  1417.             'widthLabel'     => $this->widthLabel,
  1418.             'formColumns'    => $this->formColumns,
  1419.             'accion'         => $this->accion,
  1420.             'notShow'        => array('_token'=>'1'),
  1421.            );
  1422.        foreach ($this->paramsRequest as $key=>$value)
  1423.        {
  1424.            if ($key!='filterData' && $key!='form')
  1425.            {
  1426.                $params[$key]=$value;
  1427.            }
  1428.        }
  1429.        
  1430.        $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1431.        $paramsEntity $entity->newParamsForTwig($paramsForFunctionInEntity);
  1432.        return array_merge($params$paramsEntity);
  1433.     }
  1434.     /* 
  1435.      * MÉTODOS ASOCIADOS A LA ACCIÓN CREATE
  1436.      */
  1437.     public function backToListAction($rol$routeClassName$id)
  1438.     {
  1439.        $this->setInitialValues($rol$routeClassName);
  1440.        $aClassName $this->classFullName;
  1441.        if ($id == -1$id=null;
  1442.        $ruta $aClassName::backToList($routeClassName$this->em$id$this->filterData );
  1443.        $ruta['params']['rol'] = $rol;
  1444.        return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1445.     }
  1446.     
  1447.     /* 
  1448.      * MÉTODOS ASOCIADOS A LA ACCIÓN CREATE
  1449.      */
  1450.     public function createAction($rol$routeClassName)
  1451.     {
  1452.         $this->setInitialValues($rol$routeClassName);
  1453.         $this->accion 'CREATE';
  1454.         
  1455.         if (!$this->allowActionExecution())
  1456.         {
  1457.             return $this->render('@crud\\accesDenied.html.twig');
  1458.         }
  1459.         $entity $this->createEntity();
  1460. //        $this->setValuesBeforeForm('CREATE', $entity);
  1461.         $params $this->comunParamsForForm($entity);
  1462.         $this->formulario $this->buildForm($params);
  1463.         
  1464.         $this->formulario->handleRequest($this->request);
  1465.         if ($this->formulario->isSubmitted() && $this->formulario->isValid())
  1466.         {
  1467.             $this->setValuesAfterForm($entity);
  1468.             
  1469.             $this->comunSetFileFields($params$this->formulario$entity);
  1470.             
  1471.             if ($this->comunCheckConstrains($entity))
  1472.             {        
  1473.                 $this->beforeSave($entity);
  1474.                 if($this->comunPersist($entity))
  1475.                 {
  1476.                     $this->afterSave($entity);
  1477.                     return $this->createRedirectOnSuccess($entity);
  1478.                 }
  1479.             }
  1480.         }
  1481.         else
  1482.             $this->comunSetFormularioErrors();
  1483.         return $this->createRedirectOnFail($entity);
  1484.     }
  1485.     protected function createRedirectOnFail($entity)
  1486.     {
  1487.         if ($this->ajax)
  1488.         {
  1489.             $error $this->session->getFlashBag()->get('danger');
  1490.             if (count($error)>0)
  1491.               $error $error[0];
  1492.             else
  1493.               $error="Error";  
  1494.             $data= array('ok'=>false,'error'=>$error);
  1495.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1496.             $data->headers->set('Content-Type''application/json');
  1497.             return $data;        
  1498.         }
  1499.         else
  1500.         {
  1501.             $paramsForTwigNew $this->newParamsForTwig($entity); 
  1502.             return $this->render($this->twigNewName$paramsForTwigNew);   
  1503.         }
  1504.     }   
  1505.     
  1506.     protected function afterSave($entity)
  1507.     {
  1508.         $params $this->comunParamsForFunctionsInEntity(); 
  1509.         $params['request'] = $this->request;
  1510.         $params['entity'] = $entity;
  1511.         $params['accion'] = $this->accion;
  1512.         if ($this->accion=='UPDATE')
  1513.             $params['oldEntity'] = $this->oldEntity;
  1514.         
  1515.         $entity->afterSave($params);
  1516.     }
  1517.     
  1518.     protected function beforeSave($entity)
  1519.     {
  1520.         $params $this->comunParamsForFunctionsInEntity(); 
  1521.         $params['request'] = $this->request;
  1522.         $params['entity'] = $entity;
  1523.         $params['accion'] = $this->accion;
  1524.         if ($this->accion=='UPDATE')
  1525.             $params['oldEntity'] = $this->oldEntity;
  1526.         
  1527.         $entity->beforeSave($params);
  1528.     }
  1529.     
  1530.     protected function createEntity()
  1531.     {
  1532.         $entityFullName $this->classFullName;
  1533.         
  1534.         return new $entityFullName();
  1535.     }   
  1536.     
  1537.     protected function createRedirectOnSuccess($entity)
  1538.     {
  1539.         if ($this->ajax)
  1540.         {
  1541.             $data= array('ok'=>true,'id'=>$entity->getId(),'txt'=>$entity->__toString());
  1542.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1543.             $data->headers->set('Content-Type''application/json');
  1544.             return $data;        
  1545.         }
  1546.         else
  1547.         {
  1548.             $ruta $entity->createRedirectOnSuccess($this->em$this->request$this->routeClassName$this->rol );
  1549.             return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1550.         }
  1551.     } 
  1552.     
  1553.     protected function setValuesAfterForm($entity)
  1554.     {
  1555.     }
  1556.     
  1557.     protected function setValuesBeforeForm($entity)
  1558.     {
  1559.     }
  1560.     
  1561.     /* 
  1562.      * MÉTODOS ASOCIADOS A LA ACCIÓN SHOW
  1563.      */
  1564.     public function showAction($rol$id$routeClassName$tab=-1)
  1565.     {
  1566.         $this->setInitialValues($rol$routeClassName);
  1567.         $this->accion 'SHOW';
  1568.         $entity $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->find($id);
  1569.         if (!$entity
  1570.           throw new \RuntimeException($this->translator->trans(
  1571.                                                      'error.instance_not_found',
  1572.                                                      array('%className%' => $this->routeClassName.'/'.$this->className,
  1573.                                                            '%id%'        => $id),
  1574.                                                      'crud'));
  1575.         if (!$this->allowActionExecution('SHOW'$entity))
  1576.         {
  1577.             return $this->render('@crud\\accesDenied.html.twig');
  1578.         }
  1579.         
  1580.         $paramsForTwigShow $this->showCreateParamsForTwig($entity);
  1581.         $paramsForTwigShow['tab']=$tab;
  1582.         return $this->render($this->twigShowName$paramsForTwigShow);        
  1583.     }
  1584.     
  1585.     protected function showCreateParamsForTwig($entity)
  1586.     {
  1587.        $className $this->classFullName
  1588.        $page $this->request->get('page');
  1589.        $params= array(
  1590.            'routeClassName'            => $this->routeClassName,
  1591.            'rol' => $this->rol,
  1592.            //'readableSingularClassName' => $this->readableSingularClassName,
  1593.            'entity'                    => $entity,
  1594.            'booleans' => $this->booleans,
  1595.            'paramsRequest'  => $this->paramsRequest
  1596.            'widthLabel' => $this->widthLabel,
  1597.            'showColumns' => $this->showColumns,
  1598.            'editInIndex' => $this->editInIndex,
  1599.            'deleteInIndex' => $this->deleteInIndex,
  1600.         );
  1601.        foreach ($this->paramsRequest as $key=>$value)
  1602.            if ($key!='filterData')
  1603.                $params[$key]=$value;
  1604.        $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1605.        $paramsForFunctionInEntity['entity'] = $entity;
  1606.        $paramsForFunctionInEntity['showIdInForm'] = $this->showIdInForm;
  1607.        $params['showFields'] = $this->showGetFields($entity);
  1608.        $paramsEntity $entity->getParamsForShowTwig($this->comunParamsForFunctionsInEntity());
  1609.        return array_merge($params$paramsEntity);
  1610.     }
  1611.     
  1612.     /* 
  1613.      * MÉTODOS ASOCIADOS A LA ACCIÓN EDIT
  1614.      */
  1615.     public function editAction($rol$id$routeClassName)
  1616.     {
  1617.         $this->setInitialValues($rol$routeClassName);
  1618.         $this->accion 'UPDATE';
  1619.         
  1620.         $entity $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->find($id);
  1621.         if (!$entity
  1622.           throw new \RuntimeException($this->translator->trans(
  1623.                                                      'error.instance_not_found',
  1624.                                                      array('%className%' => $this->routeClassName.'/'.$this->className,
  1625.                                                            '%id%'        => $id),
  1626.                                                      'crud'));
  1627.         
  1628.         if (!$this->allowActionExecution($entity))
  1629.         {
  1630.             return $this->render('@crud\\accesDenied.html.twig');
  1631.         }
  1632.         
  1633.         $this->setValuesBeforeForm($entity);        
  1634.         $params $this->comunParamsForForm($entity);
  1635.         $this->formulario $this->buildForm($params);
  1636.         
  1637.         $paramsForTwigEdit $this->editParamsForTwig($entity); 
  1638.         return $this->render($this->twigEditName$paramsForTwigEdit);        
  1639.     }
  1640.     protected function editParamsForTwig($entity)
  1641.     {
  1642.         $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1643.  
  1644.         $paramsEntity $entity->editParamsForTwig($paramsForFunctionInEntity);
  1645.         $params= array(
  1646.             'rol'           => $this->rol,
  1647.             'routeClassName' => $this->routeClassName,
  1648.             'contenedor'     => $this->routeClassName,
  1649.             'entity'         => $entity,
  1650.             'form'           => $this->formulario->createView(),
  1651.             'filterData'     => $this->filterData,
  1652.             'paramsRequest'  => $this->paramsRequest,
  1653.             'widthLabel'     => $this->widthLabel,
  1654.             'formColumns'    => $this->formColumns,
  1655.             'accion'         => $this->accion,
  1656.             'editInIndex'    => $this->editInIndex,
  1657.             'deleteInIndex'    => $this->deleteInIndex,
  1658.             'notShow'        => array('_token'=>'1'),
  1659.         );
  1660.         foreach ($this->paramsRequest as $key=>$value)
  1661.             if ($key!='filterData')
  1662.                 $params[$key]=$value;
  1663.         return array_merge($params$paramsEntity);
  1664.     }
  1665.     /* 
  1666.      * MÉTODOS ASOCIADOS A LA ACCIÓN UPDATE
  1667.      */
  1668.     public function updateAction($rol$id$routeClassName)
  1669.     {
  1670.         $this->setInitialValues($rol$routeClassName);
  1671.         $this->accion 'UPDATE';
  1672.         $entity $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->find($id);
  1673.         if (!$entity
  1674.           throw new \RuntimeException($this->translator->trans(
  1675.                                                      'error.instance_not_found',
  1676.                                                      array('%className%' => $this->routeClassName.'/'.$this->className,
  1677.                                                            '%id%'        => $id),
  1678.                                                      'crud'));
  1679.         if (!$this->allowActionExecution($entity))
  1680.         {
  1681.             return $this->render('@crud\\accesDenied.html.twig');
  1682.         }
  1683.         
  1684.         $this->oldEntity = clone $entity;
  1685.         $params $this->comunParamsForForm($entity);
  1686.         $this->formulario $this->buildForm($params);
  1687.         $this->formulario->handleRequest($this->request);
  1688.         if ($this->formulario->isSubmitted() && $this->formulario->isValid())
  1689.         {
  1690.             $this->setValuesAfterForm($entity);
  1691.             $deleteFiles $this->comunSetFileFields($params$this->formulario$entity);
  1692.             if ($this->comunCheckConstrains($entity))
  1693.             {        
  1694.                 $this->beforeSave($entity);
  1695.                 if($this->comunPersist($entity))
  1696.                 {
  1697.                     $this->deleteFiles($entity$deleteFiles);
  1698.                     $this->afterSave($entity);
  1699.                     return $this->updateRedirectOnSuccess($entity);
  1700.                 }
  1701.             }  
  1702.         }
  1703.         else
  1704.         {
  1705.           $this->comunSetFormularioErrors();
  1706.         }
  1707.         
  1708.         return $this->updateRedirectOnFail($entity);        
  1709.     }
  1710.     protected function updateRedirectOnFail($entity)
  1711.     {
  1712.         if ($this->ajax)
  1713.         {
  1714.             $error $this->session->getFlashBag()->get('danger');
  1715.             if (count($error)>0)
  1716.               $error $error[0];
  1717.             else
  1718.               $error="Error";  
  1719.             $data= array('ok'=>false,'error'=>$error);
  1720.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1721.             $data->headers->set('Content-Type''application/json');
  1722.             return $data;        
  1723.         }
  1724.         else
  1725.         {
  1726.             $paramsForTwigEdit $this->editParamsForTwig($entity); 
  1727.             return $this->render($this->twigEditName$paramsForTwigEdit);        
  1728.         }
  1729.     }   
  1730.     
  1731.     protected function comunSetFormularioErrors()
  1732.     {
  1733.         $childs $this->formulario->getIterator();
  1734.         $childs $childs->getIterator();
  1735.         $error '';
  1736.         $childs->next();
  1737.         while ($error=='' && $child $childs->current())
  1738.         {
  1739.             $errors $child->getErrors();
  1740.             if (count($errors)>0)
  1741.             {    
  1742.                 $fieldName $this->translator
  1743.                                ->trans($this->routeClassName.'.fields.'.$child->getName(), array(), 'crud');
  1744.                 $errorMessage $errors[0]->getMessage();
  1745.                 $fieldValue $errors[0]->getMessageParameters();
  1746.                 $fieldValue $fieldValue['{{ value }}'];
  1747.                 $this->session->getFlashBag()
  1748.                                      ->set('danger'$fieldName.': '.$errorMessage.' "'.$fieldValue.'"');
  1749.                 $error 'error';
  1750.             }    
  1751.             $childs->next();
  1752.         } 
  1753.     }
  1754.     
  1755.     protected function deleteFiles($entity$deleteFiles)
  1756.     {
  1757.         foreach ($deleteFiles as $fieldName)
  1758.         {
  1759.             //borrar aqui el adjunto anterior
  1760.             $getMethod 'get'.ucfirst($fieldName);
  1761.             $adjunto $this->oldEntity->$getMethod();
  1762.             $filename $adjunto->getRuta().'/'.$adjunto->getArchivoHash();
  1763.             try
  1764.     {
  1765.                 $this->em->remove($adjunto);
  1766.                 $this->em->flush();
  1767.                 unlink($filename);
  1768.             }
  1769.             catch (\Exception $exc) {}
  1770.         }
  1771.     }
  1772.     
  1773.     protected function updateRedirectOnSuccess($entity)
  1774.     {
  1775.         if ($this->ajax)
  1776.         {
  1777.             $data= array('ok'=>true,'id'=>$entity->getId());
  1778.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1779.             $data->headers->set('Content-Type''application/json');
  1780.             return $data;        
  1781.         }
  1782.         else
  1783.         {
  1784.             $ruta $entity->updateRedirectOnSuccess($this->em$this->request$this->routeClassName$this->rol );
  1785.             return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1786.         }
  1787.     } 
  1788.     
  1789.     /* 
  1790.      * MÉTODOS ASOCIADOS A LA ACCIÓN DELETE
  1791.      */
  1792.     public function deleteAction($rol$id$routeClassName)
  1793.     {
  1794.         $this->setInitialValues($rol$routeClassName);
  1795.         $this->accion='DELETE';
  1796.         
  1797.         
  1798.         $entity $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->find($id);
  1799.         if (!$entity
  1800.           throw new \RuntimeException($this->translator->trans(
  1801.                                                      'error.instance_not_found',
  1802.                                                      array('%className%' => $this->routeClassName.'/'.$this->className,
  1803.                                                            '%id%'        => $id),
  1804.                                                      'crud'));
  1805.         if (!$this->allowActionExecution($entity))
  1806.         {
  1807.             return $this->render('@crud\\accesDenied.html.twig');
  1808.         }
  1809.         
  1810.         $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1811.         if($entity->checkNonReferentialIntegrityConstrains($paramsForFunctionInEntity))
  1812.         {
  1813.            $this->beforeDelete($entity$paramsForFunctionInEntity);
  1814.         
  1815.            if($this->comunRemove($entity))
  1816.            {
  1817.                $this->afterDelete($entity$paramsForFunctionInEntity);
  1818.                return $this->deleteRedirectOnSuccess($entity);
  1819.            }
  1820.            else{
  1821.                return $this->deleteRedirectOnFail($entity);
  1822.         }
  1823.         }
  1824.         else {
  1825.            return $this->deleteRedirectOnFail($entity);
  1826.         }
  1827.     }
  1828.     
  1829.     protected function afterDelete($entity$params null)
  1830.     {
  1831.         
  1832.     }
  1833.     
  1834.     protected function beforeDelete($entity$params)
  1835.     {
  1836.        $entity->beforeDelete($params);
  1837.     }   
  1838.    
  1839.     protected function deleteRedirectOnSuccess($entity)
  1840.     {
  1841.         if ($this->ajax)
  1842.         {    
  1843.             $data= array('ok'=>true,'id'=>$entity->getId(),'txt'=>$entity->__toString());
  1844.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1845.             $data->headers->set('Content-Type''application/json');
  1846.             return $data;        
  1847.         }
  1848.         else
  1849.         {
  1850.             $ruta $entity->deleteRedirectOnSuccess($this->em$this->request$this->routeClassName$this->rol );
  1851.             return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1852.         }
  1853.     }   
  1854.     
  1855.     protected function deleteRedirectOnFail($entity)
  1856.     {
  1857.         if ($this->ajax)
  1858.         {
  1859.             $error $this->session->getFlashBag()->get('danger');
  1860.             if (count($error)>0)
  1861.               $error $error[0];
  1862.             else
  1863.               $error="Error";  
  1864.             $data= array('ok'=>false,'error'=>$error);
  1865.             $data = new \Symfony\Component\HttpFoundation\Response(json_encode($data));
  1866.             $data->headers->set('Content-Type''application/json');
  1867.             return $data;            
  1868.         }
  1869.         else
  1870.         {
  1871.            $ruta $entity->deleteRedirectOnFail($this->em$this->request$this->routeClassName$this->rol );
  1872.            return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1873.         }
  1874.     }   
  1875.     
  1876.     public function paginatorAction($rol$routeClassName$page)
  1877.     {
  1878.        $this->setInitialValues($rol$routeClassName);
  1879.        $aClassName $this->classFullName;
  1880.        $ruta $aClassName::paginator($routeClassName$page$this->filterData );
  1881.        return $this->redirect($this->generateUrl($ruta['ruta'], $ruta['params']));
  1882.     }
  1883.     
  1884.     public function getNestedAction($bundleName$className$fieldName$value$sel=-1)
  1885.     {
  1886.         $em $this ->em;
  1887.         if ($value==-1)
  1888.             $childs $em->getRepository($bundleName.'\\Entity\\'.$className)->findAll();
  1889.         else
  1890.         {
  1891.             $childs $em->getRepository($bundleName.'\\Entity\\'.$className)->createQueryBuilder('p')
  1892.                            ->leftJoin('p.'.$fieldName,$fieldName)
  1893.                            ->where($fieldName.'.id='.$value)
  1894.                            ->getQuery()->getResult();
  1895.         }    
  1896.         return $this->render('@crud\Common\comboreloaded.html.twig', array("entities"=>$childs'value'=>$sel));
  1897.     }
  1898.     
  1899.     public function getDependientesAction($className$fieldName$value$sel=-1)
  1900.     {
  1901.         $className str_replace('()','\\',$className);
  1902.         $em $this ->em;
  1903.         if ($value==-1)
  1904.             $childs $em->getRepository($className)->findAll();
  1905.         else
  1906.         {
  1907.             $childs $em->getRepository($className)->createQueryBuilder('p')
  1908.                            ->leftJoin('p.'.$fieldName,$fieldName)
  1909.                            ->where($fieldName.'.id='.$value)
  1910.                            ->getQuery()->getResult();
  1911.         }    
  1912.         return $this->render('@crud\Common\comboreloaded.html.twig', array("entities"=>$childs'value'=>$sel));
  1913.     }
  1914.     
  1915.     public function getAllItemsAction($routeClassName$sel=-1)
  1916.     {
  1917.         $this->setInitialValues($routeClassName);
  1918.         $items $this->em->getRepository($this->bundleName.'\\Entity\\'.$this->className)->findAll();
  1919.         return $this->render('@crud\Common\comboreloaded.html.twig', array("entities"=>$items'value'=>$sel));
  1920.     }
  1921.     
  1922.     protected function excelCreateParamsForTwig()
  1923.     {
  1924.         $params $this->indexParamsForTwig();
  1925.         
  1926.         $params['indexFields'] = $this->excelGetFields(); 
  1927.  
  1928.         return $params;
  1929.     }
  1930.     public function excelAction($rol$routeClassName)
  1931.     {
  1932.         $this->setInitialValues($rol$routeClassName);
  1933.         $this->accion='INDEX';
  1934.         if (!$this->allowActionExecution())
  1935.         {
  1936.             return $this->render('@crud\\accesDenied.html.twig');
  1937.         }
  1938.         $paramsForFunctionInEntity $this->comunParamsForFunctionsInEntity();
  1939.         $paramsForFunctionInEntity['showIdInForm'] = $this->showIdInForm;
  1940.         $this->indexPrepareFilterForm($paramsForFunctionInEntity);
  1941.         $paramsForFunctionInEntity['filterForm']= $this->formularioFiltro;
  1942.         $this->entities $this->indexLoadEntities($paramsForFunctionInEntity);
  1943.         $spreadSheet $this->generateSpreadSheet();
  1944.         $contentType 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  1945.         $xlsxWriter = new Xlsx($spreadSheet);            
  1946.         $fileName str_replace(' ','',$this->translator->trans($this->translatorBase.'.plural', [], 'crud')).'.xlsx';
  1947.         $response = new StreamedResponse();
  1948.         $response->headers->set('Content-Type'$contentType);
  1949.         $response->headers->set('Content-Disposition''attachment;filename="'.$fileName.'"');
  1950.         $response->setPrivate();
  1951.         $response->headers->addCacheControlDirective('no-cache'true);
  1952.         $response->headers->addCacheControlDirective('must-revalidate'true);
  1953.         $response->setCallback(function() use ($xlsxWriter) {
  1954.             $xlsxWriter->save('php://output');
  1955.         });
  1956.         return $response;            
  1957.     }
  1958.     
  1959.     protected function getExcelValue($entity$field)
  1960.     {
  1961.         if (is_object($entity))
  1962.         {
  1963.             return $entity->getFieldValue($field['nombre']);
  1964.         }
  1965.         else
  1966.         {
  1967.             return $entity[$field['nombre']];
  1968.         }
  1969.     }
  1970.     
  1971.     protected function generateSpreadSheet()
  1972.     {
  1973. //        $fields = $this->excelGetFields();
  1974.         $params $this->excelCreateParamsForTwig();
  1975.         $fields $params['indexFields'];
  1976.         
  1977.         $spreadSheet = new Spreadsheet();
  1978.         $sheet $spreadSheet->getActiveSheet();
  1979.         $sheet->setCellValue('A1'$this->translator->trans($this->translatorBase.'.plural', [], 'crud'))->mergeCells('A1:D1');
  1980.         $sheet->getStyle('A1')->getFont()->setBold(true);
  1981.         $sheet->getStyle('A1')->getFont()->setSize(16);
  1982.         $col 'A';
  1983.         foreach ($fields as $field)
  1984.         {
  1985.             $sheet->setCellValue($col.'3'$field['label']);
  1986.             $sheet->getStyle($col.'3')->getFont()->setBold(true);
  1987.             $sheet->getStyle($col.'3')->getFont()->setSize(12);
  1988.             $col++;
  1989.         }
  1990.         $row 4;
  1991.         foreach ($this->entities as $entity)
  1992.         {
  1993.             $col 'A';
  1994.             foreach ($fields as $field)
  1995.             {
  1996.                 $value $this->getExcelValue($entity$field);
  1997.                 if (is_object($value))
  1998.                 {
  1999.                     if ($value instanceof \DateTime)
  2000.                     {
  2001.                         $value $value->format('Y/m/d');
  2002.                     }
  2003.                     else
  2004.                     {
  2005.                         $value $value->__toString();
  2006.                     }
  2007.                 }
  2008.                 $sheet->setCellValue($col.$row$value);
  2009.                 $col++;
  2010.             }
  2011.             $row++;
  2012.         }
  2013.         return $spreadSheet;
  2014.     }
  2015.     
  2016.     protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
  2017.     {
  2018.         if (isset($_ENV[$name]))
  2019.         {
  2020.             $value $_ENV[$name];
  2021.         }
  2022.         else
  2023.         {
  2024.             $value parent::getParameter($name);
  2025.             if (!$value)
  2026.             {
  2027.                 throw new \Exception('Parameter '.$name.' is not defined');
  2028.             }
  2029.         }
  2030.         return $value;
  2031.     }
  2032.     
  2033.     protected function getFormulario($entity)
  2034.     {
  2035.         $formulario = array();
  2036.         $R = new \ReflectionClass($this->classFullName);
  2037.         $fields $R->getProperties(\ReflectionProperty::IS_PRIVATE);
  2038.         $properties $this->em->getClassMetadata($this->classFullName)->fieldMappings;
  2039.         $association $this->em->getClassMetadata($this->classFullName)->associationMappings;
  2040.         foreach ($fields as $field)
  2041.         {
  2042.             $fieldname $field->name;
  2043.             $label $this->translator->trans($this->routeClassName.'.fields.'.$fieldname, array(), 'crud');
  2044.             if ($label == $this->routeClassName.'.fields.'.$fieldname)
  2045.             {
  2046.                 $label $this->translator->trans($this->translatorBase.'.fields.'.$fieldname, array(), 'crud');
  2047.             }
  2048.             if (isset($properties[$field->name]))
  2049.             {
  2050.                 $prop $properties[$fieldname];
  2051.                 if (isset($prop['id']) && $prop['id'] && (!isset($this->showIdInForm) || !$this->showIdInForm))
  2052.                 {
  2053.                     continue;
  2054.                 }
  2055.                 $formulario[$fieldname]=array(
  2056.                     'nombre'   =>$fieldname,
  2057.                     'tipo'     =>null,
  2058.                     'type'     =>$prop['type'], 
  2059.                     'atributos'=>array(
  2060.                         'label' => $label,
  2061.                         'required' => !$prop['nullable'],
  2062.                         'attr'=>array(
  2063.                             'style'=>'width: 100%'
  2064.                         )
  2065.                     )
  2066.                 );
  2067.                 $tip $this->translator->trans($this->translatorBase.'.tips.'.$fieldname, array(), 'crud');
  2068.                 if ($tip != $this->translatorBase.'.tips.'.$fieldname)
  2069.                 {
  2070.                     $formulario[$fieldname]['atributos']['attr']['tip']=$tip;
  2071.                 }
  2072.                 if ($prop['type']=='boolean')
  2073.                 {
  2074.                     $formulario[$fieldname]['atributos']['attr']['class'] = 'ace ace-switch ace-switch-5';                
  2075.                 }
  2076.                 if ($prop['type']=='text')
  2077.                 {
  2078.                     $formulario[$fieldname]['atributos']['attr']['rows'] = '2';                
  2079.                 }
  2080.                 if ($prop['type']=='integer' || $prop['type']=='smallint')
  2081.                 {
  2082.                     $formulario[$fieldname]['atributos']['attr']['class'] = 'spinbox-input';                
  2083.                     $formulario[$fieldname]['atributos']['attr']['full_width'] = true;                
  2084.                     $formulario[$fieldname]['tipo'] = 'Symfony\Component\Form\Extension\Core\Type\IntegerType';                
  2085.                 }
  2086.                 if ($prop['type']=='float')
  2087.                 {
  2088.                     if (isset($prop['columnDefinition']) && $prop['columnDefinition']=='dolar')
  2089.                     {    
  2090.                         $formulario[$fieldname]['tipo'] = 'number';
  2091.                         $formulario[$fieldname]['atributos']['attr']['class']='dolar form-control-currency';
  2092.                         $formulario[$fieldname]['atributos']['attr']['min']="0"
  2093.                         $formulario[$fieldname]['atributos']['attr']['step']="0.01"
  2094.                         $formulario[$fieldname]['atributos']['attr']['data-number-to-fixed']="2"
  2095.                         $formulario[$fieldname]['atributos']['attr']['data-number-step-factor']="100"
  2096.                         $formulario[$fieldname]['atributos']['attr']['style'].="; text-align: right"
  2097.                     }
  2098.                 }
  2099.              /*   if ($prop['type']=='time')
  2100.                 {
  2101.                     $formulario[$fieldname]['tipo'] = 'time';
  2102.                 }*/
  2103.                 if ($prop['type']=='datetime')
  2104.                 {
  2105.                     if (isset($prop['columnDefinition']) && $prop['columnDefinition']=='fecha')
  2106.                     {    
  2107.                         $formulario[$fieldname]['tipo'] = 'date';
  2108.                         $formulario[$fieldname]['atributos']['widget'] = 'single_text';
  2109.                         $formulario[$fieldname]['atributos']['format'] = 'dd-MM-yyyy';
  2110.                         $formulario[$fieldname]['atributos']['attr']['class']='campo_fecha date-picker';
  2111.                         $formulario[$fieldname]['atributos']['attr']['data-date-format']="dd-mm-yyyy"
  2112.                         //$formulario[$fieldname]['atributos']['attr']['data-uk-datepicker']="{format:'DD-MM-YYYY', pos: 'bottom'}";
  2113.                     }
  2114.                     
  2115.                     if (isset($prop['columnDefinition']) && $prop['columnDefinition']=='fechaHora')
  2116.                     {    
  2117.                         $formulario[$fieldname]['tipo'] = 'date';
  2118.                         $formulario[$fieldname]['atributos']['attr']['class']='campo_hora_fecha date-picker';
  2119.                         $formulario[$fieldname]['atributos']['attr']['data-date-format']="dd-mm-yyyy"
  2120.                         //$formulario[$fieldname]['atributos']['attr']['data-uk-datepicker']="{format:'DD-MM-YYYY', pos: 'bottom'}";
  2121.                     }
  2122.                 }
  2123.                 if (isset($prop['columnDefinition']))
  2124.                 {                    
  2125.                     switch ($prop['columnDefinition'])
  2126.                     {
  2127.                         case 'geometria_punto':
  2128.                             $formulario[$fieldname]['tipo'] = 'geometria';
  2129.                             $formulario[$fieldname]['atributos']['attr']['class']='geometria_punto';                                     
  2130.                         break;    
  2131.                         case 'geometria_poligono':
  2132.                             $formulario[$fieldname]['tipo'] = 'geometria';
  2133.                             $formulario[$fieldname]['atributos']['attr']['class']='geometria_poligono';                                     
  2134.                         break;    
  2135.                         case 'email':
  2136.                             $formulario[$fieldname]['tipo'] = 'Symfony\Component\Form\Extension\Core\Type\EmailType';
  2137.                         break;    
  2138.                     }
  2139.                 }   
  2140.             }
  2141.             if (isset($association[$field->name]))
  2142.             {    
  2143.                 $prop $association[$fieldname];
  2144.                 if ((isset($prop['id']) && $prop['id'] && !$this->showIdInForm
  2145.                     || (!$prop['isOwningSide'] && !$entity->getNotOwningSideInForm($field->name)))
  2146.                 {
  2147.                     continue;
  2148.                 }
  2149.                 $formulario[$fieldname]=array(
  2150.                     'nombre'   =>$fieldname,
  2151.                     'tipo'     =>null,
  2152.                     'type'     =>'association',
  2153.                     'atributos'=>array(
  2154.                         'label' => $label,
  2155.                         'required' => (isset($prop['joinColumns'][0]['nullable']) && !$prop['joinColumns'][0]['nullable']) || (isset($prop['joinTable']['joinColumns'][0]['nullable']) && !$prop['joinTable']['joinColumns'][0]['nullable']),
  2156.                         'placeholder' => $this->translator->trans('choice_value.empty_value', array(), 'crud'),
  2157.                         'empty_data' => null,
  2158.                         'attr' => array(
  2159.                             'class'=>'chosen-select',
  2160.                             'style'=>'width: 100%',
  2161.                             'data-placeholder'=>$this->translator->trans('choice_value.empty_value',array(),'crud')
  2162.                         )
  2163.                     )
  2164.                 );
  2165.                 if (isset($prop['joinColumns'][0]['columnDefinition']))
  2166.                 {
  2167.                     if (strpos($prop['joinColumns'][0]['columnDefinition'],'relation/')===0)
  2168.                     {
  2169.                         $formulario[$fieldname]['atributos']['attr']['relation']=str_replace('relation/','',$prop['joinColumns'][0]['columnDefinition']);
  2170.                     }
  2171.                     if (strpos($prop['joinColumns'][0]['columnDefinition'],'dependiente{')===0)
  2172.                     {
  2173.                         $dependiente str_replace('dependiente{','',$prop['joinColumns'][0]['columnDefinition']);
  2174.                         $dependiente str_replace('}','',$dependiente);
  2175.                         $dependiente explode(','$dependiente);
  2176.                         if (count($dependiente)==3)
  2177.                         {
  2178.                             $dependiente[1] = str_replace('\\','()',$dependiente[1]);
  2179.                             $formulario[$fieldname]['atributos']['attr']['dependiente_parent']=$dependiente[0];
  2180.                             $formulario[$fieldname]['atributos']['attr']['dependiente_class']=$dependiente[1];
  2181.                             $formulario[$fieldname]['atributos']['attr']['dependiente_field']=$dependiente[2];
  2182.                         }
  2183.                         else
  2184.                         {
  2185.                             throw new \RuntimeException('Crud - The column definition for property "'.$fieldname.'" is not correct.');
  2186.                         }
  2187.                     }
  2188.                 }
  2189.                 $tip $this->translator->trans($this->translatorBase.'.tips.'.$fieldname, array(), 'crud');
  2190.                 if ($tip != $this->translatorBase.'.tips.'.$fieldname)
  2191.                 {
  2192.                     $formulario[$fieldname]['atributos']['attr']['tip']=$tip;
  2193.                 }
  2194.                 if($prop['type']==8//Many to many association
  2195.                 {
  2196.                     $formulario[$fieldname]['atributos']['attr']['class'] = 'chosen-select form-control';
  2197.                 }
  2198.                 else
  2199.                 if($prop['type']==4//One to Many (not owning side)
  2200.                 {
  2201.                     $formulario[$fieldname]['tipo'] = 'collection';
  2202.                     $formulario[$fieldname]['atributos']['entry_type'] = $prop['targetEntity'];
  2203.                     $formulario[$fieldname]['atributos']['entry_options'] = ['label' => false];
  2204.                     $formulario[$fieldname]['atributos']['allow_add'] = true;
  2205.                     $formulario[$fieldname]['atributos']['attr']['containerclass'] = 'full-row';
  2206.                     unset($formulario[$fieldname]['atributos']['placeholder']);
  2207.                 }
  2208.                 else
  2209.                 {
  2210.                     if(isset($prop['joinColumns'][0]['columnDefinition']) && $prop['joinColumns'][0]['columnDefinition']=='chosen')
  2211.                     {
  2212.                         $formulario[$fieldname]['atributos']['attr']['class'] = 'chosen-select form-control';
  2213.                     }
  2214.                 }
  2215.                 if($this->isAdjunto($prop['targetEntity']))
  2216.                 {
  2217.                     $formulario[$fieldname]['tipo'] = 'Symfony\Component\Form\Extension\Core\Type\FileType';
  2218.                     unset($formulario[$fieldname]['atributos']['placeholder']);
  2219.                     unset($formulario[$fieldname]['atributos']['empty_data']);
  2220.                     $formulario[$fieldname]['atributos']['mapped'] = false;
  2221.                     $formulario[$fieldname]['atributos']['attr']['class'] = $prop['targetEntity'];
  2222.                     unset($formulario[$fieldname]['atributos']['attr']['style']);
  2223.                     unset($formulario[$fieldname]['atributos']['attr']['data-placeholder']);
  2224.                     if (isset($prop['joinColumns'][0]['columnDefinition']))
  2225.                     {
  2226.                         $formulario[$fieldname]['atributos']['attr']['accept'] = $prop['joinColumns'][0]['columnDefinition'];
  2227.                     }
  2228.                 }   
  2229.             }  
  2230.         }  
  2231.         return $formulario;
  2232.     }   
  2233.     public function quickUpdateAction()
  2234.     {
  2235.         $ret= array('ok'=>true);
  2236.         try
  2237.         {
  2238.             $data $this->request->get('quick');
  2239.             $entity $this->em->getRepository('App\\Entity\\'.$data['class'])->find($data['id']);
  2240.             if ($entity)
  2241.             {
  2242.                 if ($data['association'])
  2243.                 {
  2244.                     $valor $this->em->getRepository('App\\Entity\\'.$data['association'])->find($data['valor']);
  2245.                 }
  2246.                 else
  2247.                 {
  2248.                     $valor $data['valor'];
  2249.                 }
  2250.                 $setFunction 'set'.ucfirst($data['field']); 
  2251.                 $entity->$setFunction($valor);
  2252.                 $this->em->persist($entity);
  2253.                 $this->em->flush();
  2254.             }
  2255.             else
  2256.             {
  2257.                 $ret['ok'] = false;
  2258.                 $ret['msg'] = 'No se encontro a un '.$data['class'].' con el identificador envíado'
  2259.             }
  2260.         }
  2261.         catch(\Exception $exc)
  2262.         {
  2263.             $ret['ok'] = false;
  2264.             $ret['msg'] = $exc->getMessage(); 
  2265.         }
  2266.         $data = new \Symfony\Component\HttpFoundation\Response(json_encode($ret));
  2267.         $data->headers->set('Content-Type''application/json');
  2268.         return $data;        
  2269.     }
  2270.     
  2271.     public function quickDeleteAction($className$id)
  2272.     {
  2273.         try
  2274.         {
  2275.             $habilidad $this->em->getRepository('App\\Entity\\'.$className)->find($id);
  2276.             $this->em->remove($habilidad);
  2277.             $this->em->flush();
  2278.             $ret = ['ok'=>true];
  2279.         }
  2280.         catch (\Exception $exc)
  2281.         {
  2282.             $ret = ['ok'=>false'msg'=>$exc->getMessage()];
  2283.         }
  2284.         $data = new \Symfony\Component\HttpFoundation\Response(json_encode($ret));
  2285.         $data->headers->set('Content-Type''application/json');
  2286.         return $data;        
  2287.     }
  2288.         
  2289. }