hook_form_FORM_ID_alter: Pre select a checkbox from an exposed filter in a drupal 8 view - drupal-8

I have a view that lists blog articles. The blog content type has a taxonomy reference field to the 'tags' vocabulary, authors can select 1 or multiple tags. The view exposes the 'Has taxonomy terms (with depth) (exposed)' filter (as a list of checkboxes) so that users can search for blog articles containing 1 or more tags.
Now, i'm trying to pre-select 1 of the checkboxes that are exposed to the user in the hook_form_FORM_ID_alter() hook. It should be a simple as the code below but it just doesn't work. The tag i'm trying to pre-select has the ID 288.
What am i doing wrong? Thx...
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
$form['tags']['#default_value'] = [288 => 288];
}
}

You have to set user input like this:
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
if (is_null(\Drupal::request()->get('tags'))) {
// Avoid overriding the filter values selected by user
$input = $form_state->getUserInput();
$input['tags'] = [288 => 288];
$form_state->setUserInput($input);
}
}
}

Related

Custom form field in views

I'm trying to create a custom field for a view in Drupal 8 which allows to perform an action without changing the page (link). I guess I have to create a form inside that custom field but I do not know how to achieve it.
Any idea on how to do it or other alternative without redirecting to a route?
The view will be a list of custom entities and I need a button for each of the lines.
Thanks in advance!
Finally I solved it by following this steps:
I created a view custom field (generate:plugin:views:field with
drupal console)
I created a form (generate:form)
Then, in the view custom field render function return the form:
$form = \Drupal::formBuilder()->getForm('Drupal\test_module\Form\TestForm', $values->_entity->ID());
return $form;
It's important to notice that an incremental (dynamic) formId is needed for things to work properly. I did that by creating a static variable and a __construct() method as follows:
protected static $instanceId;
public function getFormId() {
return 'my_form_id_' . self::$instanceId;
}
public function __construct(){
if (empty(self::$instanceId)) {
self::$instanceId = 1;
}
else {
self::$instanceId++;
}
}

Is there an easy solution to export a filtered backendlist

I have a list with products and locations. I've created a filterdefinition and can filter products based on a location.
Now I want to export te filtered selection to print it to an pdf.
I've tried to acces the filtered items with the ajax framework, but can't find any information on how to retrieve the filtered id's.
My printhandler works fine, I only need to get the ID's of selected items in the filter.
scopes:
location:
label: Location
modelClass: XXX\xxxx\Models\Location
conditions: location_id in (:filtered)
nameFrom: location
As always, found a solution after asking for one;
Found a piece of code:
function getCurrentFilters() {
$filters = [];
foreach (\Session::get('widget', []) as $name => $item) {
if (str_contains($name, 'Filter')) {
$filter = #unserialize(#base64_decode($item));
if ($filter) {
//$filters[] = $filter;
array_push($filters, $filter);
}
}
}
return $filters;
}

APEX row selector part 2

This is a follow on to "APEX row selector" posted 5 days ago.
The problem was collecting multiple values from an interactive grid. From the excellent links to post supplied I was able to achieve this. However, the next part of the project is to open an edit dialog page and update multiple values.
I added this code to the attribute of the interactive grid:
function (config)
{
var $ = apex.jQuery,
toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(),
toolbarGroup = toolbarData.toolbarFind("actions3");
toolbarGroup.controls.push(
{
type: "BUTTON",
action: "updateCar",
label: "Edit Selected Cars",
hot: true,
});
config.toolbarData = toolbarData;
config.initActions = function (actions)
{
// Defining the action for activate button
actions.add(
{
name: "updateCar",
label: "Edit Selected Cars",
action: updateCar
});
}
function updateCar(event, focusElement)
{
var i, records, model, record,
view = apex.region("ig_car").widget().interactiveGrid("getCurrentView");
var vid = "";
model = view.model;
records = view.getSelectedRecords();
if (records.length > 0)
{
for (i = 0; i < records.length; i++)
{
record = records[i];
alert("Under Development " + record[1]);
vid = vid + record[1] + "||";
apex.item("P18_CAR").setValue(vid);
// need to open next page here and pass parameters
}
}
}
return config;
}
I need to know how to open a form and have the parameter values available to pass to an oracle update script.
Thank you for any help you can provide. I did find some posts but I really need a good example. I have tried everything to no avail.
There are various ways you could do this. Here's one way, perhaps someone else will offer a more efficient option.
The JavaScript options for navigation in APEX are documented here:
https://docs.oracle.com/en/database/oracle/application-express/19.1/aexjs/apex.navigation.html
Since you're trying to open a separate page, you probably want to use apex.navigation.dialog, which is what APEX automatically uses when opening modal pages from reports, buttons, etc.
However, as noted in the doc, the URL for the navigation must be generated server-side for security purposes. You need a dynamic URL (one not known when the page renders), so you'll need a workaround to generate it. Once you have the URL, navigating to it is easy. So how do you get the URL? Ajax.
Create an Ajax process to generate the URL
Under the processing tab of the report/grid page, right-click Ajax Callback and select Create Process.
Set Name to GET_FORM_URL.
Set PL/SQL code to the following
code:
declare
l_url varchar2(512);
begin
l_url := apex_page.get_url(
p_application => :APP_ID,
p_page => 3,
p_items => 'P3_ITEM_NAME',
p_values => apex_application.g_x01
);
apex_json.open_object();
apex_json.write('url', l_url);
apex_json.close_object();
end;
Note that I'm using apex_item.get_url to get the URL, this is an alternative to apex_util.prepare_url. I'm also using apex_json to emit JSON for the response to the client.
Also, the reference to apex_application.g_x01 is important, as this will contain the selected values from the calling page. You'll see how this was set in the next step.
Open the URL with JavaScript
Enter the following code in the Function and Global Variable Declaration attribute of the calling page:
function openFormPage(ids) {
apex.server.process(
'GET_FORM_URL',
{
x01: ids.join(':')
},
{
success: function (data) {
var funcBody = data.url.replace(/^"javascript:/, '').replace(/\"$/,'');
new Function(funcBody).call(window);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
// handle error
}
}
);
}
In this case, I'm using apex.server.process to call the server-side PL/SQL process. Note that I'm passing the value of ids.join(':') to x01. That value will become accessible in the PL/SQL code as apex_application.g_x01. You can use additional items, or you can pass a colon-delimited string of values to just one item (as I'm doing).
The URL that's returned to the client will not be a standard URL, it will be a JavaScript snippet that includes the URL. You'll need to remove the leading and trailing parts and use what's left to generate a dynamic function in JavaScript.
This is generally frowned upon, but I believe it's safe enough in this context since I know I can trust that the response from the process call is not malicious JavaScript code.
Add a security check!!!
Because you're creating a dynamic way to generate URLs to open page 3 (or whatever page you're targeting), you need to ensure that the modal page is protected. On that page, create a Before Header process that validates the value of P3_ITEM_NAME. If the user isn't supposed to be able to access those values, then throw an exception.

Get data from db, using multiple checkboxes in laravel 5.5

I have a table called history in which i have a column called PRODUCTS in which the products are saved.
I have a search screen with products using checkboxes, I can get the data if i use only checkbox.
How can i get data if i tick more than one checkboxes.
Displaying the checkboxes using below code
#foreach($products as $product)
#if (in_array($product->name, explode(" , ",$user->products)) !== false)
<input type="checkbox" name="products[]" value="{{$product->name}}"
#if(in_array($product->name, explode(" , ",$user->products))) #endif>
{{$product->name2}}
#endif
#endforeach
Controller
public function usersSearch(Request $request, Repair_History $query)
{
$query = $query->newQuery();
if ($request->has('products')) {
$query->where('proc_doc', $request->input('products'));
}
return $query->get();
}
Fixed it by using below code in my controller, posting as it might help someone.
$friends_checked = $request->input('products');
if (count($friends_checked) > 1 && is_array($friends_checked)) {
$query->whereIn('proc_doc', $friends_checked)
}

Adding a search box to filter a list of results in Symfony?

I need to put a search box within a list of objects as a result of a typical indexSuccess action in Symfony. The goal is simple: filter the list according to a criteria.
I've been reading the Zend Lucene approach in Jobeet tutorial, but it seems like using a sledge-hammer to crack a nut (at least for my requirements).
I'm more interested in the auto-generated admin filter forms but I don't know how to implement it in a frontend.
I could simply pass the search box content to the action and build a custom query, but is there any better way to do this?
EDIT
I forgot to mention that I would like to have a single generic input field instead of an input field for each model attribute.
Thanks!
I'm using this solution, instead of integrating Zend Lucene I manage to use the autogenerated Symonfy's filters. This is the way i'm doing it:
//module/actions.class.php
public function executeIndex(sfWebRequest $request)
{
//set the form filter
$this->searchForm = new EmployeeFormFilter();
//bind it empty to fetch all data
$this->searchForm->bind(array());
//fetch all
$this->employees = $this->searchForm->getQuery()->execute();
...
}
I made a search action which does the search
public function executeSearch(sfWebRequest $request)
{
//create filter
$this->searchForm = new EmployeeFormFilter();
//bind parameter
$fields = $request->getParameter($this->searchForm->getName());
//bind
$this->searchForm->bind($fields);
//set paginator
$this->employees = $this->searchForm->getQuery()->execute();
...
//template
$this->setTemplate("index");
}
It's important that the search form goes to mymodule/search action.
Actually, i'm also using the sfDoctrinePager for paginate setting directly the query that the form generate to get results properly paginated.
If you want to add more fields to the search form check this :)
I finally made a custom form using the default MyModuleForm generated by Symfony
public function executeIndex {
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
but displaying only a custom field:
<div id="search_box">
<input type="text" name="criteria" id="search_box_criteria" value="Search..." />
<?php echo link_to('Search', '#my_module_search?criteria=') ?>
</div>
Then I created a route named #my_module_search linked to the index action:
my_module_search:
url: my_module/search/:criteria
param: { module: my_module, action: index }
requirements: { criteria: .* } # Terms are optional, show all by default
With Javascript (jQuery in this case) I append the text entered to the criteria parameter in the href attribute of the link:
$('#search_box a').click(function(){
$(this).attr('href', $(this).attr('href') + $(this).prev().val());
});
And finally, back to the executeIndex action, I detect if text was entered and add custom filters to the DoctrineQuery object:
public function executeIndex {
...
// Deal with search criteria
if ( $text = $request->getParameter('criteria') ) {
$query = $this->pager->getQuery()
->where("MyTable.name LIKE ?", "%$text%")
->orWhere("MyTable.remarks LIKE ?", "%$text%")
...;
}
$this->pager->setQuery($query);
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
Actually, the code is more complex, because I wrote some partials and some methods in parent classes to reuse code. But this is the best I can came up with.