Ajax method for ordering fields

@EXT\Route("/{panel}/fields/order",
name="claro_admin_field_facet_order",
options = {"expose"=true}
)
338975
public function moveFieldFacetsAction(PanelFacet $panel)
    {
        $params = $this->request->query->all();
        $ids = [];

        foreach ($params['ids'] as $value) {
            $ids[] = (int) str_replace('field-', '', $value);
        }

        $this->facetManager->orderFields($ids, $panel);

        return new Response('success');
    }
466075
public function index() {            
        HookProvider::getInstance()->updateHooks();
        
        $action = Filter::post('action');        
        if($action == 'update' && Filter::checkCsrf()) $this->update();
        
        Theme::theme(new AdministrationTheme)->init(Globals::getTree());        
        $ctrl = new PageController();
        $ctrl
            ->restrictAccess(Auth::isAdmin())
            ->setPageTitle($this->module->getTitle());
        
        $table_id = 'table-installedhooks-' . Uuid::uuid4();

        $view_bag = new ViewBag();
        $view_bag->set('title', $ctrl->getPageTitle());
        $view_bag->set('table_id', $table_id);
        $view_bag->set('hook_list', HookProvider::getInstance()->getRawInstalledHooks());
        
        $ctrl
        ->addExternalJavascript(WT_JQUERY_DATATABLES_JS_URL)
        ->addExternalJavascript(WT_DATATABLES_BOOTSTRAP_JS_URL)
        ->addInlineJavascript('
		  	jQuery(document).ready(function() {
				jQuery("#'.$table_id.'").dataTable( {
					'.I18N::datatablesI18N().',		
					sorting: [[ 2, "asc" ], [ 3, "asc" ]],
					displayLength: 10,
					pagingType: "full_numbers",
					columns: [
						/* 0 Enabled 		*/	{ dataSort: 1, class: "center" },
						/* 1 Enabled sort	*/	{ visible: false},
						/* 2 Hook function	*/	null,
						/* 3 Hook context	*/	null,
						/* 4 Module name	*/	null,
						/* 5 Priority		*/	{ dataSort: 6, class: "center" },
						/* 6 Priority sort	*/	{ type: "num", visible: false}
					]
			  });
			});
		');
        
        ViewFactory::make('AdminConfig', $this, $ctrl, $view_bag)->render();
    }
463388
public function indexAction()
    {
        $this->initializeScaffolding();

        $paginator = $this->scaffolding->doPaginate($this->request->get('page', 'int', 1));
        $this->view->page = $paginator->getPaginate();
        $this->view->fields = $this->indexFields;
    }
1002383
public function fieldFormAction(PanelFacet $panelFacet)
    {
        $form = $this->formFactory->create(new FieldFacetType(), new FieldFacet());

        return array('form' => $form->createView(), 'panelFacet' => $panelFacet);
    }
539366
function render() {

		$this->autocompletefield();
		$this->fieldtemplate !== null or $this->fieldtemplate = ':field';

		if ($this->fieldconfigurer_callback !== null) {
			call_user_func($this->fieldconfigurer_callback, $this);
		}

		return strtr($this->fieldtemplate, $this->fieldfillers());
	}
562499
def get_fields(self, request, obj=None):
        
        fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)
        if issubclass(self.model, Orderable):
            fields = list(fields)
            try:
                fields.remove("_order")
            except ValueError:
                pass
            fields.append("_order")
        return fields
866456
public function index()
    {
        if (!userHasPermission('admin:invoice:customer:manage')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Set method info
        $this->data['page']->title = 'Manage Customers';

        // --------------------------------------------------------------------------

        $oInput         = Factory::service('Input');
        $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
        $sTableAlias    = $oCustomerModel->getTableAlias();

        //  Get pagination and search/sort variables
        $page      = $oInput->get('page') ? $oInput->get('page') : 0;
        $perPage   = $oInput->get('perPage') ? $oInput->get('perPage') : 50;
        $sortOn    = $oInput->get('sortOn') ? $oInput->get('sortOn') : $sTableAlias . '.organisation';
        $sortOrder = $oInput->get('sortOrder') ? $oInput->get('sortOrder') : 'asc';
        $keywords  = $oInput->get('keywords') ? $oInput->get('keywords') : '';

        // --------------------------------------------------------------------------

        //  Define the sortable columns
        $sortColumns = [
            $sTableAlias . '.organisation' => 'Organisation',
            $sTableAlias . '.first_name'   => 'Customer Name',
            $sTableAlias . '.created'      => 'Created Date',
            $sTableAlias . '.modified'     => 'Last Modified Date',
        ];

        // --------------------------------------------------------------------------

        //  Define the $data variable for the queries
        $data = [
            'expand'   => ['invoices'],
            'sort'     => [
                [$sortOn, $sortOrder],
            ],
            'keywords' => $keywords,
        ];

        //  Get the items for the page
        $totalRows               = $oCustomerModel->countAll($data);
        $this->data['customers'] = $oCustomerModel->getAll($page, $perPage, $data);

        //  Set Search and Pagination objects for the view
        $this->data['search']     = Helper::searchObject(true, $sortColumns, $sortOn, $sortOrder, $perPage, $keywords);
        $this->data['pagination'] = Helper::paginationObject($page, $perPage, $totalRows);

        // --------------------------------------------------------------------------

        //  Add a header button
        if (userHasPermission('admin:invoice:customer:create')) {

            Helper::addHeaderButton(
                'admin/invoice/customer/create',
                'Create Customer'
            );
        }

        // --------------------------------------------------------------------------

        Helper::loadView('index');
    }
1345679
public function indexAction()
    {
        /* @todo: move this into a listener.
         *
         * The following lines allow to override get param[q] with the
         * param from route. This feature is needed for a landing-page feature, where
         * human readable urls like http://yawik.org/demo/de/jobs/sales.html
         *
         * move the Logic into a Listener, which can be activated, if needed
         */
        $request = $this->getRequest();
        $getParams = $request->getQuery();
        $routeParams = $this->params()->fromRoute();
        if (isset($routeParams['q']) && !isset($getParams['q'])) {
            $getParams['q']=$routeParams['q'];
        }

        $result = $this->pagination([
                'params' => ['Jobs_Board', [
                    'q',
                    'count' => $this->options['count'],
                    'page' => 1,
                    'l',
                    'd' => 10]
                ],
                'form' => ['as' => 'filterForm', 'Jobs/JobboardSearch'],
                'paginator' => ['as' => 'jobs', 'Jobs/Board']
            ]);

        $organizationImageCache = $this->imageFileCacheManager;

        $result['organizationImageCache'] = $organizationImageCache;

        return new ViewModel($result);
    }
47558
public function displayOrders(Request $request)
    {
        $page = (int) $request->query->get('page', 1);
        $perPage = (int) $request->query->get('per-page', 10);
        $offsetStart = 0;

        $todo = $request->query->get('todo', Order::STATUS_TODO);
        $start = $request->query->get('start', Order::STATUS_NO_FILTER);
        $limit = $request->query->get('limit', []);

        if ($page > 0) {
            $offsetStart = ($page - 1) * $perPage;
        }

        $sort = $request->query->get('sort');

        $baseIds = array_keys($this->getAclForUser()->get_granted_base([\ACL::ORDER_MASTER]));

        $ordersListTodo = $this->getOrderRepository()->listOrders($baseIds, $offsetStart, $perPage, $sort,
            ['todo' => Order::STATUS_TODO, 'created_on' => $start, 'limit' => $limit]);
        $ordersListProcessed = $this->getOrderRepository()->listOrders($baseIds, $offsetStart, $perPage, $sort,
            ['todo' => Order::STATUS_PROCESSED, 'created_on' => $start, 'limit' => $limit]);
        $totalTodo = $this->getOrderRepository()->countTotalOrders($baseIds, ['todo' => Order::STATUS_TODO, 'created_on' => $start, 'limit' => $limit]);
        $totalProcessed = $this->getOrderRepository()->countTotalOrders($baseIds, ['todo' => Order::STATUS_PROCESSED, 'created_on' => $start, 'limit' => $limit]);

        return $this->render('prod/orders/order_box.html.twig', [
            'page'         => $page,
            'perPage'      => $perPage,
            'totalTodo'        => $totalTodo,
            'totalProcessed' => $totalProcessed,
            'orders_todo'       => new ArrayCollection($ordersListTodo),
            'orders_processed'       => new ArrayCollection($ordersListProcessed),
            'todo' => $todo,
            'start' => $start,
            'date' => $limit ?  $limit['date']: null
        ]);
    }
515765
public function getCMSFields()
    {
        $self = $this;
   
        $this->beforeUpdateCMSFields(function ($fields) use ($self) {
            $siteconfig = SiteConfig::current_site_config();

            $fields->removeByName("StartDate");
            $fields->removeByName("CustomerID");
            $fields->removeByName("EndDate");
            $fields->removeByName("Number");
            $fields->removeByName("Ref");
            $fields->removeByName("AccessKey");
            $fields->removeByName("Items");
            $fields->removeByName("Prefix");
            
            $fields->addFieldsToTab(
                "Root.Main",
                [
                    // Items field
                    ReadOnlyGridField::create(
                        "Items",
                        "",
                        $this->Items(),
                        $config = GridFieldConfig::create()
                            ->addComponents(
                                new GridFieldButtonRow('before'),
                                new GridFieldTitleHeader(),
                                new GridFieldEditableColumns(),
                                new GridFieldEditButton(),
                                new GridFieldDetailForm(),
                                new GridFieldDeleteAction(),
                                new AddLineItem()
                            )
                    ),

                    LiteralField::create(
                        "ItemsDivider",
                        '<div class="field form-group"></div>'
                    ),
                    
                    // Totals and settings
                    CompositeField::create(
                        CompositeField::create(
                            DateField::create("StartDate", _t("OrdersAdmin.Date", "Date")),
                            DateField::create("EndDate", _t("OrdersAdmin.Expires", "Expires")),
                            ReadonlyField::create("FullRef", "#"),
                            TextField::create("Ref", $this->fieldLabel("Ref"))
                        )->setName("OrdersDetailsInfo")
                        ->addExtraClass("col"),
                        CompositeField::create([])
                            ->setName("OrdersDetailsMisc")
                        ->addExtraClass("col"),
                        CompositeField::create(
                            ReadonlyField::create("SubTotalValue", _t("OrdersAdmin.SubTotal", "Sub Total"))
                                ->setValue($this->obj("SubTotal")->Nice()),
                            ReadonlyField::create("TaxValue", _t("OrdersAdmin.Tax", "Tax"))
                                ->setValue($this->obj("TaxTotal")->Nice()),
                            ReadonlyField::create("TotalValue", _t("OrdersAdmin.Total", "Total"))
                                ->setValue($this->obj("Total")->Nice())
                        )->setName("OrdersDetailsTotals")
                        ->addExtraClass("col")
                    )->setName("OrdersDetails")
                    ->addExtraClass("orders-details-field")
                    ->setColumnCount(2)
                    ->setFieldHolderTemplate("SilverCommerce\\OrdersAdmin\\Forms\\OrderDetailsField_holder")
                ]
            );

            $fields->addFieldsToTab(
                "Root.Customer",
                [
                    HasOneButtonField::create(
                        $this,
                        'Customer'
                    ),
                    TextField::create("Company"),
                    TextField::create("FirstName"),
                    TextField::create("Surname"),
                    TextField::create("Address1"),
                    TextField::create("Address2"),
                    TextField::create("City"),
                    TextField::create("County"),
                    TextField::create("PostCode"),
                    DropdownField::create(
                        'Country',
                        _t('OrdersAdmin.Country', 'Country'),
                        i18n::getData()->getCountries()
                    )->setEmptyString(""),
                    TextField::create("Email"),
                    TextField::create("PhoneNumber")
                ]
            );

            $fields->addFieldsToTab(
                "Root.Delivery",
                [
                    HeaderField::create(
                        "DeliveryDetailsHeader",
                        _t("Orders.DeliveryDetails", "Delivery Details")
                    ),
                    TextField::create("DeliveryCompany"),
                    TextField::create("DeliveryFirstName"),
                    TextField::create("DeliverySurname"),
                    TextField::create("DeliveryAddress1"),
                    TextField::create("DeliveryAddress2"),
                    TextField::create("DeliveryCity"),
                    TextField::create("DeliveryCounty"),
                    TextField::create("DeliveryPostCode"),
                    DropdownField::create(
                        'DeliveryCountry',
                        _t('OrdersAdmin.Country', 'Country'),
                        i18n::getData()->getCountries()
                    )->setEmptyString("")
                ]
            );

            $fields->addFieldToTab(
                "Root.History",
                VersionHistoryField::create(
                    "History",
                    _t("SilverCommerce\VersionHistoryField.History", "History"),
                    $self
                )->addExtraClass("stacked")
            );
            
            $root = $fields->findOrMakeTab("Root");

            if ($root) {
                $root->addextraClass('orders-root');
            }
        });
        
        return parent::getCMSFields();
    }
505306
def ajax_forms options={}
      default_options = {
          quick_new_partial: nil,
          quick_create_partial: nil,
          model: config.resource_class,
          search_fields: ['name'],
          display_column: 'name',
          search_condition: 'cont_all'
      }
      options = default_options.deep_merge(options)

      @ajax_form_enabled = true

      # XXX: usar reflect on association para definir los collection_actions en los modelos
      # relacionados donde se quieren buscar los datos
      # Por ejemplo, si product belongs_to invoice_line, y quiero crear dinámicamente un producto
      # solo hace falta definir en invoice_line que se quiere usar ajax_forms. Automáticamente
      # se crean los collection_actions en products para realizar las búsquedas.

      #todo: Posibilidad de especificar los atributos a devolver en el método find. Si no se especifica nada devolver todas las columnas
      collection_action :find, :method => :get do
        model = resource_class
        search_term = params[:q]
        groupping_condition = params[:q][:g] rescue nil
        ransack_search = options[:search_fields].join('_or_').concat('_').concat(options[:search_condition]).to_sym

        if params[:q_id].present?
          params[:q]={:id_equals => params[:q_id]} #selected element
        elsif groupping_condition.nil?
          params[:q]={
            :g=>{
              "0"=>{ransack_search=>search_term.split(" ")}
            }
          }

          # if this search depends on the result of another select box
          # we need to add the filter to the existing ransack options
          if params[:dependentSelect] and !params[:dependentSelect][:selectorValue].empty?
            params[:q][:g]["1"]={params[:dependentSelect][:ransackFilter].to_sym=>params[:dependentSelect][:selectorValue]}
          end
        end

        q = model.search(params[:q])
        @items = q.result.order('id asc', 'name asc').limit(100).map { |item| {:id => item.id, :text => item.to_s} }
        respond_to do |format|
          format.json { render :json => @items }
        end
      end

      collection_action :quick_new, :method => :get do
        @model = resource_class.new(:name => Base64.decode64(params[:name]))
        options[:selector]=params[:selectorid]
        #crea una variable de instancia con el nombre del recurso para compatibilidad con partials normales
        instance_variable_set("@#{resource_instance_name.to_s}", @model)
        @remote = true
        @form_url = eval "quick_create_admin_#{resource_collection_name.to_s}_path"

        @id="#{Time.now.to_i.to_s}_#{resource_instance_name.to_s}"
        options[:id]=@id

        #todo: tiene que renderizar un formulario por defecto
        if options.fetch(:quick_new_partial).nil?
          render :nothing => true
        else
          render partial: options.fetch(:quick_new_partial), layout: 'application'
        end
      end

      collection_action :quick_create, :method => :post do
        @model = resource_class.new(params[resource_instance_name])
        @selector=options[:selector]
        @model.save
        @id=options[:id]
        render file: 'quick_response', layout: false
      end
    end
1041158
public function orders($page = 1, $perPage = 30, $saleSystem = null, array $statuses = [])
    {
        /** @var OrderHandler $handler */
        $handler = $this->requestHandler();
        return $handler->orders($page, $perPage, $saleSystem, $statuses);
    }
463533
public function index() {
        if ($this->overrideAction('index')) {
            return;
        }

        $this->paginate = array_merge(array(
            'limit' => 25,
            'order' => array($this->Model->alias . '.' . $this->Model->displayField => 'ASC'),
            'contain' => array_keys($this->Model->belongsTo)
        ), $this->Model->admin['paginate']);

        $this->AdminToolbar->setBelongsToData($this->Model);

        // Filters
        if (!empty($this->request->params['named'])) {
            $this->paginate['conditions'] = $this->AdminToolbar->parseFilterConditions($this->Model, $this->request->params['named']);
        }

        // Batch delete
        if ($this->request->is('post')) {
            if (!$this->Model->admin['batchProcess']) {
                throw new ForbiddenException(__d('admin', 'Batch Access Protected'));
            }

            $action = $this->request->data[$this->Model->alias]['batch_action'];
            $items = $this->request->data[$this->Model->alias]['items'];
            $processed = array();

            foreach ($items as $id) {
                if (!$id) {
                    continue;
                }

                if ($action === 'delete_item') {
                    if ($this->Model->delete($id, true)) {
                        $processed[] = $id;
                    }
                } else {
                    if (call_user_func(array($this->Model, $action), $id)) {
                        $processed[] = $id;
                    }
                }
            }

            $count = count($processed);

            if ($count > 0) {
                $this->AdminToolbar->logAction(ActionLog::BATCH_DELETE, $this->Model, '', sprintf('Processed IDs: %s', implode(', ', $processed)));
                $this->AdminToolbar->setFlashMessage(__d('admin', '%s %s have been processed', array($count, mb_strtolower($this->Model->pluralName))));

                $this->request->data[$this->Model->alias] = array();
            }
        }

        $this->set('results', $this->paginate($this->Model));
        $this->overrideView('index');
    }
910201
public function orderFields() {
        $result = $this->orderElements($this->fields);
        if ($result) {
            $this->setFields($result);
            return true;
        } else {
            return false;
        }
    }
625073
public function indexAction()
    {
        if ($this->getRequest()->isAjax()) {
            try {
                $this->loadLayout(null, false, false);
                $this->getLayout()->getUpdate()->setCacheId(null);
                $this->getLayout()->getUpdate()->addHandle(strtolower($this->getFullActionName()) . '_AJAX');
            } catch (Exception $e) {
                Mage::logException($e);
                $this->getResponse()->setHeader('Content-Type', 'application/json');
                $this->getResponse()->setBody(Zend_Json::encode(['error' => true, 'message' => $e->getMessage()]));
            }
        }

        $this->loadLayout();
        $this->renderLayout();
    }
84010
private void exposeExposedFieldsToJs() {
    if (fieldsWithNameExposed.isEmpty()) {
      return;
    }

    MethodSpec.Builder exposeFieldMethod = MethodSpec
        .methodBuilder("vg$ef")
        .addAnnotation(JsMethod.class);

    fieldsWithNameExposed
        .forEach(field -> exposeFieldMethod
            .addStatement("this.$L = $T.v()",
                field.getName(),
                FieldsExposer.class)
        );

    exposeFieldMethod
        .addStatement(
            "$T.e($L)",
            FieldsExposer.class,
            String.join(
                ",",
                fieldsWithNameExposed.stream()
                    .map(ExposedField::getName)
                    .collect(Collectors.toList())
            )
        );
    componentExposedTypeBuilder.addMethod(exposeFieldMethod.build());
  }
1370439
public function index() {
        $data = $this->request->data;

        if ($this->request->is('post')) {
            $data['FileUpload']['user_id'] = $this->Auth->user('id');

            try {
                if ($this->Model->save($data, true)) {
                    $this->Model->set($data);
                    $this->AdminToolbar->logAction(ActionLog::CREATE, $this->Model, $this->Model->id);

                    $this->AdminToolbar->setFlashMessage(__d('admin', 'Successfully uploaded a new file'));
                    $this->request->data = array();

                    if ($data[$this->Model->alias]['redirect_to'] === 'read') {
                        $this->redirect(array('plugin' => 'admin', 'controller' => 'crud', 'action' => 'read', 'model' => $this->Model->urlSlug, $this->Model->id));
                    }
                }
            } catch (Exception $e) {
                $this->AdminToolbar->setFlashMessage($e->getMessage(), 'is-error');
            }
        }

        if (empty($this->request->data)) {
            $this->request->data['FileUpload'] = Configure::read('Admin.uploads');
        }
    }