How do I display data from an external database in Drupal? - drupal

I am building a custom module that will allow my users to do a simple query against an MS SQL database. I've built the form using hook_form() and have gotten validation to work.
I'm planning on retrieving the data from hook_form_submit(), but once I've done that, how do I append it below the form? It does not appear that I have access to $output from hook_form_submit(). I'm at a loss as to what to do next.
Thanks
Dana

When you are rendering the form you should check for $form_state['values'] to see if the user has already submitted a form when you're rendering the form. Then you could paint the form results in the same step as painting the form.
The first time the user loads the form page the $form_state variable won't contain any submitted form info so you can render an empty results table.
There's a good illustration of the Drupal Form API workflow on Drupal.org here: Form API Internal Workflow Illustration

The problem in trying to output data in the hook_form() method is that the method gets invoked twice which clears the post values the second time through. Throw a dpm($form_state) in the hook_form() function and you'll see two sets of post data. One with values and one without.
So after dissecting the built in Search module, which pretty much operates exactly the way I want my form to work, I figured out how this is done. Well, at least one way you can do it.
What Search module does is take the values from $form_state in hook_form_submit() and pastes them into the URL, then it sets the $form_state['redirect'] to that new URL, effectively storing those variables in the URL and changing the POST to a GET.
Now, in the callback, they extract those values from the URL, do the search on them, THEN they call drupal_get_form(), append the results to the end and return it.
There's another solution HERE where they use SESSION to store the values until the second trip through. Weird, but it works.

Related

How to get data once on WordPress page template and access it across multiple shortcodes that are used in same page

Have a requirement to create a WordPress dynamically based on multiple apis data, And we want to use that response data chunks as short code in page builder while designing backed with template.
We want to retrieve data only once in page template and how to make it available something $post without having to fetch on each short code.
Ex: $system_data -> which might contain name, description, performance etc, more attributes
And want to make common short code which takes attribute and get the relevant information.
[system-data attr="performance"]
What is the best way to achieve this, without loading whole data on each short code
you can use global variable to store data from first short code and use in other short code for entire page but you should check value is empty or not in every short code before use it

Algolia - WordPress - how can I get the actual query into JS variable to work with it further in the hits template?

I would like to do some interesting stuff with the hits that are being displayed based on the search query that user is not only typing into search box but actually filtering using the instant search filters. I have filter based on hierarchical events_location taxonomy. Based on what user selected I would get the info in JS variable that I can then further use to do other operations in the hits div, specifically on each hit card.
So my URL when searching updates like this:
/what-to-see/?q=&idx=sdbeta_posts_events&p=0&hFR%5Btaxonomies_hierarchical.events_calendar.lvl0%5D%5B0%5D=JUL%204&hFR%5Btaxonomies_hierarchical.events_category.lvl0%5D%5B0%5D=All&hFR%5Btaxonomies_hierarchical.events_locations.lvl0%5D%5B0%5D=Paddock%20Stage
I could potentially take the URL and extract the data from it, but I am sure there is more elegant way of working with the query.
In InstantSearch.js, the state is managed by another library called the algoliasearch-helper. Through this library you can read and write the search parameters.
The cleanest to access the helper is to build a custom widget, which is a plain object with lifecycle hooks (initial rendering and the other renderings). You can read more about custom widgets there.
Once you've accessed the helper, you can read and write with the helper API.
This can be found under search.searchParameters
So:
console.log(search.searchParameters);
Will give you whole object that you can then work with.
There is however one issue with this and that is that it works only on initial load. I was unable to make this work or get any data after starting to selecting categories. So if anyone knows how to use this so it updates after each selection please comment bellow.

Add to Form Results from External Form

Is there an API for adding to the Form Results that results from standard Forms are added to from an External Form?
I want to try avoid adding to the tables btform, btformanswers, etc. manually
No.
See https://github.com/concrete5/concrete5/blob/master/web/concrete/core/controllers/blocks/form.php#L354-L415 -- the core's form block updates the table manually.
As johjoh says, you could theoretically mimic a post to a form block, by instantiating it and then calling action_submit_form(), but that's just as fraught with difficulty, too... you'd have to keep the "form" in sync with your data, and possibly worry about the token and block ID and all that....
What's your exact use case? New block type? Some sort of external API? The form viewing interface in the dashboard is nice, but nothing that special. I think most people want to get data out of it, not in....

Drupal 7 - Form API Custom Module

I have a form that calculates two values, form works perfectly, however i'm having some problems working out how I can calculate the two values and return the answer as rendered HTML so I can style it all nice and pretty for the user to see.
All help will much appreciated. Thanks.
In a Drupal form there are three types of callback that are normally necessary to create a form:
The form builder is the function that builds the form using an array the form API understands
The form validation handler is the function that validates the values submitted from the users
The form submission handler is the function that acts on the values submitted from the users
Of those functions, the one that outputs the result of the calculation done on the values submitted from the users is the last one. Normally, the form submission handler saves the data in the database, and show a message to the users through drupal_set_message(), but it could also simply show the result of the operations done on the entered data.
Since Drupal 7, the output of a form submission handler, as well as the output produced from a menu callback, can be a rendering array, and not a string. A rendering array has the pro of being easily altered from third-party modules through hook_page_build(), or hook_page_alter().
node_view() is an example of menu callback that returns a rendering array, and not a string.
If it's just a message you want then you should look into drupal_set_message. It allows you to set a message like this:
drupal_set_message(t('Hello, world.'),'myClass');
Which outputs HTML like this:
<div class="messages myClass">Hello, world</div>
That would be a very simple way to set a message for the user to see once the form is submitted. If you need something a little more advanced, look into my answer here and this Drupal answer here.

What is the best alternative for QueryString

We heard a lot about the vulnerabilities of using QueryStrings and the possible attacks.
Aside from that, yesterday, an error irritated me so much that i just decide to stop using QueryStrings, i was passing something like:
Dim url As String = "pageName.aspx?type=3&st=34&am=87&m=9"
I tried to
Response.Write(url)
in the redirecting page, it printed the "type" as 3, then i tried it in the target page, it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0 in the next page's load to take my action accordingly???
So what should we use? what is the safest way to pass variables, parameters...etc to the next page?
You could use Cross-Page Postbacks.
Check also this article:
How to: Pass Values Between ASP.NET Web Pages
There are many options you can use, most of them requires you to build a strategy to pass variables between pages.
In most projects I use this strategy, I create a formVariables class to hold currently active items. it has properties which you will need to pass by querystring. and I store this class at session. and in my base page I read it from session. so in every page I get values over this object. the only negative thing about this method is to clean up items when you finished your work on it..
hope this helps.
I would sugest you avoid using Session to pass variables between pages as this breaks the stateless model of the web.
if you have just stored some values in session that relate to a certain page then the user uses their browsers back button to go back to the same page whcih should have a different state then you are not going to know about it.
It leads to the possibility of reading session values that are not relevant to the page the user is currently viewing - Which is potentially very confusing for the end user.
You will also run into issues with session expiration if you rely on it too much.
I personally try to avoid using session where possible in preference of hidden form values + query strings that can be read on postback + navigation.
The best / most secure way to pass info between pages is to use the session.
// On page 1:
this.Session["type"] = 3;
// On Page 2:
int type = (int)this.Session["type"];
You can store any kind of object in the session and it is stored on the server side, so the user can't manipulate it like a query string, viewstate, or hidden field
You said:
it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0
There's a difference between "3,0" (three comma oh) and "3.0" (three point oh). You also said that you were "passing something like".
In a query string, if you pass multiple values in the same key, they will be seperated with commas.
As all values are passed as strings there's no way that an int "3" is going to magically become decimal "3.0" unless you parse it as such when you request it.
I'd go back and double check what you are passing into your URL, if it ends up as something like:
pageName.aspx?type=3&st=34&am=87&m=9&type=0
Then when you read back
Request.QueryString["type"]
You'll get "3,0" back as the comma seperated list of values in that key.
First, in asp .net you can use several strategys to pass values between pages. You have viewstate too, however the viewstate store the value and the use is in different scenarios , you can use it too. Sessions instead, and of course by post in a form.
If your problem is the security, I recommended you to create 2 users for accesing the data. One user with read only access, this for accessing the pages ( Sql Inyection prevent ) and validate the data throw the querystring. And One with write access for your private zone.
Sorry, for my unreadeable English.
I like to use query string as I like users to be able to bookmark things like common searches and the like. E.g. if a page can work stand-alone then I like to it to be able to work stand-alone.
Using session/cross-page postbacks is cool if you needed to come from another page for the page you're on to make sense, but otherwise I generally find querystrings to be the better solution.
Just remember that query strings are unvalidated input and treat them with the caution you would treat any unvalidated input.
If you do proper security checks on each page load then the querystring is fine and most flexible IMHO.
They provide the most flexibility as the entry poitn to a page is not dependant on the sender as in some other options. You can call a page from any point within your own app or externally if needed via querystrings. They can also be bookmarked and manually modified for testing or direct manipulation.
Again the key is adding proper security and validation to the querystring, and not processing it blindly. Keep in mind that the seucirty goes beyond having edit or read access, depending on the data and user, they may not have access to the data with thos paranters at all, in cases where data is owned and private to specific users.
We have tried various methods, in an attempt to hide the querystring but in the end have gone back to it, as it is easier to do, debug, and manage.

Resources