Object storage alternatives in Wordpress - wordpress

so I am developing a Quiz plugin for Wordpress.
I have defined a shortcode which is replaced by my html, and I also have enqueued javascript and styles. So far all good.
At this point, I want to visualize each question using ajax and jquery. My quiz has some sophisticated logic - some quiz question-trees can fall off depending on the answers and on the settings of the plugin.
Thus, I am trying to achieve a solution, where javascript uses ajax call to fetch one next question at a time. On the backend, I created controller-class which is responsible for handling the logic and outputing the fetched-question's html code. Thus, whenever a starts the quiz, the backend will generate some controller object.
My question is, how can i store multiple controller objects persistently? So that i can get the current use's progress.
To do that, i need some kind of persistent storage for all the running quizzes. Here, as far as I understand, i have 2 alternatives: put serialized controller objects into the database, or use some sort of WP_CACHE.
So now I have some questions:
1) Is there any other alternative for storing a set of objects in Wordpress?
2) Is the approach I am using for the quiz implementation - okay? Like maybe I am doing something unconventional?
3) Is having ajax calls communicating to the DB a good idea?
* Edit *
Thanks to #cabrerahector, who pointed out the set_transient() wordpress API.
I was able to store an object in the db with the following code:
...
$base64_serial = base64_encode(serialize($report_controller));
set_transient($report_id, $base64_serial, 60*60*12);
...
and then retreive the object with the following code:
...
$report_controller = unserialize(base64_decode( get_transient( $_GET['report_id'] )));
...
I know it's kind of hacky, but does anybody know a better way? Please don't tell me to create an array with all fields of the class...

Related

Using getInitialProps with an optional Parameter with NextJS

I have a page which allows a user to update a record, lets call it /edit-record, I want to support /edit-record/1 as a route which would load the data (I tried using getInitialProps) but I also want to make it so /edit-record is a page (ideally the same page) but without the API call to fetch the details happening.
So if I pass /edit-record/3 it should fetch record 3, if the url is /edit-record it just awaits user events.
The issue being I tried a conditional in getInitialProps, a if(query.recordId) {} but the else clause returns a null which NextJS doesnt like; it also just feels a bit wrong in terms of the approach.
What is the better way? Ideally I don't want to create two page files to handle the two conditions as all of the logic is the same.

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....

How do I display data from an external database in 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.

Looking for a good technique for storing email templates

I am building a site in which we are making moderate use of email templates. As in, HTML templates which we pass tokens into like {UserName}, {Email}, {NameFirst}, etc.
I am struggling with where to store these, as far as best practice goes. I'll first show the approach I took, and I'd be really excited to hear some expert perspective as a far as alternate approaches.
I created HTML templates in a folder called /Templates/.
I call a static method in my service layer, which takes in the following arguments:
UserName
UserID
Email
TemplatePath ("~/Templates")
Email Subject
Within the service layer I have my static method SendUserEmail() which makes use of a Template class - which takes a path, loads it as a string, and has a AddToken() Method.
Within my static SendUserEmail(), I build the token list off of the method signature, and send the email.
This makes for a quite long method call in my actual usage, especially since I am calling from the web.config the "TemplatePath", and "Email Subject". I could create a utility that has a shorter method call than the ConfigurationManager.AppSettings, but my concern is more that I don't usually see method signatures this long and I feel like it's because I'm doing something wrong.
This technique works great for the emails I have now, which at the most are using the first 3 tokens. However in the future I will have more tokens to pass in, and I'm just wondering what approach to take.
Do I create methods specific to the email needing to be sent? ie. SendNewUserRegistration(), SendMarketingMaterial(), and each has a different signature for the parameters?
I am using ASP.NET Membership, which contains probably the extend of all the fields I'll ever need. There are three main objects, aspnet_User, aspnet_Mebership and aspnet_profile. If it was all contained in one object, I would have just passed that in. Is there performance concerns with passing in all 3, to get all the fields I need? That is versus just passing in aspnet_User.UserID, aspnet_User.Email, etc?
I could see passing in a dictionary with the token entries, but I'm just wondering if that is too much to ask the calling page?
Is there a way to stick these in a config file of it's own called Templates.config, which has tags like -
<Templates>
<EmailTemplate Name="New User Registration">
<Tokens>
<UserName>
<UserID>
<Email>
</Tokens>
<Message Subject="Hi welcome...">
Hi {UserName}...
</Message>
</EmailTemplate>
</Templates>
I guess the main reason I'm asking, is because I'm having a hard time determining where the responsibility should be as far as determining what template to use, and how to pass in parameters. Is it OK if the calling page has to build the dictionary of TokenName, TokenValue? Or should the method take each in as a defined parameter? This looks out of place in the web.config, because I have 2 entries for and , and it feels like it should look more nested.
Thank you. Any techniques or suggestions of an objective approach I can use to ask whether my approach is OK.
First of all I would like to suggest you to use NVelocity as a template engine. As for main problem I think you can create an abstract class MailMessage and derive each one for every needed message (with unique template). So you will use this like following:
MailMessage message = new UserRegistrationMessage(tokens);
//some code that sends this message
Going this way you force each concrete XXXMessage class to be responsible for storing a template and filling it with the given tokens. How to deal with tokens? The simpliest way is to create a dictionary before passing it to the message, so each concrete message class will know how to deal with passed dictionary and what tokens it should contain, but you also need to remember what tokens it should contain. Another way (I like it more) is to create a general abstract type TokenSet and a derived one for every needed unique set of tokens. For example you can create a UserMessageTokenSet : TokenSet and several properties in it:
UserNameToken
SomeUserProfileDataToken
etc. So using this way you will always know, what data you should set for each token set and
UserRegistrationMessage will know what to take from this tokenSet.
There are a lot of ways to go. If you will describe you task better I think I will try suggest you something more concrete. But general idea is listed above. Hope it helps =)

Resources