How to force the Drupal form to clear previous results - ajax

Recently im working on a project and im trying to generate form elements with the help of ajax technology (implementing a form with codes). the situation is that the user should be able to select from a list of options and then due to his select another list of options should be appeared, then due to his/her select from the second sets of options he/she should see the third series of options. now the problem is that when the user tries to change the first option in the first set, the second option will be regenerate but the third one still sticks on the page. I was trying to use the form_sate['rebuild'] = TRUE
but it did not work and all form elements disappeared. can any one help me to see which code should be implemented and where it should be used?

Without any code it's almost impossible to help, except to say check out the examples modules, specifically the ajax_example module.
The basic principle is that you need a <div> container surrounding your 2nd and 3rd select elements, which will be replaced by the #ajax set on the first element. Then you need another container inside that one surrounding only the 3rd select element, which will be replaced by the #ajax set on the 2nd select element.
Hope that helps.

well.. the form page may contains previous values because of $_POST fields variables..
for example if I want to display clear "add" form on POST submit,
I do this tric to clear drupal previous form values via ajax:
<?php
// AJAX POST handler...
....
$my_form = drupal_render(drupal_get_form("the_form", ...));
$errors = form_get_errors();
if (!$errors) {
// re-render clean form, unset your POST fields....
unset($_POST['link_path']);
unset($_POST['link_title']);
unset($_POST['parent']);
unset($_POST['weight']);
$my_form = drupal_render(drupal_get_form("the_form", ...));
}
?>

Related

Link directly to a notebook page in a view

I have an view that extends the current project view, where we add multiple tabs (notebook pages) to show information from other parts of a project.
One of these pages is an overview page that summarizes what is under the other tabs, and I'd like to link the headlines for each section directly to each displayed page. I've currently solved this by using the index of each tab and calling bootstrap's .tab('show') method on the link within the tab:
$(".overview-link").click(function (e) {
e.preventDefault();
var sel = '.nav-tabs a:eq(' + $(this).data('tab-index') + ')';
$(sel).tab('show');
});
This works since I've attached a data-tab-index="<int>" to each header link in my widget code, but it's brittle - if someone adds a tab later, the current indices will be broken. Earlier I relied on the anchor on each tab, but that broke as well (and would probably break if a new notebook page were inserted as well).
Triggering a web client redirect / form link directly works, but I want to show a specific page in the view:
this.do_action({
type: 'ir.actions.act_window',
res_model: 'my.model.name',
res_id: 'my.object.id',
view_mode: 'form',
view_type: 'form',
views: [[false, 'form']],
target: 'current'
});
Is there any way to link / redirect the web client directly to a specific notebook page tab through the do_action method or similar on FormWidget?
If I understood well you want to select the tab from the JavaScript (jQuery) FormWidget taking into account that the id could change if anybody install another module that adds another tab
Solution 0
You can add a class to the page in the xml form view. You can use the id of the element selected by this class name in order to call the right anchor and select the right tab item. This should happen when the page is completely loaded:
<page class="nb_page_to_select">
$('a[href=#' + $('.nb_page_to_select').attr('id') + ']').click()
NOTE: As you have said the following paragrah I assume that you know where to run this instruction. The solution I suggest is independent of the index.
This works since I've attached a data-tab-index="<int>" to each
header link in my widget code, but it's brittle - if someone adds a
tab later, the current indices will be broken. Earlier I relied on the
anchor on each tab, but that broke as well (and would probably break
if a new notebook page were inserted as well).
Solution 1
When the page is loaded you can get the tab list DOM object like this:
var tablist = $('ul[role="tablist"]')
And then you can click on the specifict tab, selecing by the text inside the anchor. So you don't depend on the tab index:
tablist.find('a:contains("Other Information")').click()
I think if you have two tabs with the same text does not make any sense, so this should be sufficient.
Solution 2
Even if you want to be more specific you can add a class to the notebook to make sure you are in the correct notebook
<notebook class="nt_to_change">
Now you can use one of this expressions in order to select the tab list
var tablist = $('div.nt_to_change ul.nav-tabs[role="tablist"]')
// or
var tablist = $('div.nt_to_change ul[role="tablist"]')
Solution 3
If the contains selector doesn't convince you because it should be equal you can do this as well to compare and filter
tablist.find('a').filter(function() {
return $.trim($(this).text()) === "Other Information";
}).click();
Where "Other Information" is the string of the notebook page
I didn't tried the solution I'm giving to you, but if it doesn't work at least may be it makes you come up with some idea.
There's a parameter for XML elements named autofocus (for buttons and fields is default_focus and takes 1 or 0 as value). If you add autofocus="autofocus" to a page in XML, this page will be the displayed one when you open the view.
So, you can try to add this through JavaScript, when the user clicks on the respective link -which honestly, I don't know how to achieve that by now-. But you can add a distinctive context parameter to each link in XML, for example context="{'page_to_display': 'page x'}". When you click on the link, I hope these context keys will arrive to your JS method.
If not, you can also modify the fields_view_get method (here I wrote how to do that: Odoo - Hide button for specific user) to check if you get the context you've added to your links and add the autofocus parameter to the respective page.
As you said:
This works since I've attached a data-tab-index="" to each header
link in my widget code, but it's brittle - if someone adds a tab
later, the current indices will be broken.
I assume that your app allow multi-user interaction in realtime, so you have to integrate somewhere in your code, an update part function.
This function will trig if something has changed and cleanout the data to rebuilt the index in order to avoid that the current indices will be broken.

How do clear words/images upon form validation? (AngularJS)

Just to be clear, in the subject line, it says "words/images". The "words" part is not about clearing the words in the form, but rather the word "required". As for images, these are validation images, like the green checkmark.
I just realized that I had no clue how to clear words/images upon form completion in AngularJS. Basically, the checkmark stays, and the word "required" appears after submitting the validated form. It does so, because now the form is empty. I tried using the $setPristine in the script page,
$scope.imgHolderComments.$setPristine(true);
knowing that it would probably not work. I looked for a workaround, so I checked out this impressive thread (but realized this was more for the validation itself and not added words/images).
Reset form to pristine state (AngularJS 1.0.x)
Then I tried using this code which I had used prior to today for the pre-validation. Or if you will, for the live validation, before submitting the form. I thought I could recycle this, but no.
$scope.checkUrl = 'images/validation/y_square_trans.png';
$scope.loadUrl = 'images/validation/loading.gif';
$scope.crossUrl = 'images/validation/loading_wrong.gif';
$scope.imgHolderComments = '';
$scope.comments = "";
$scope.timeout = null;
$scope.imgHolderComments = ($scope.reviewForm.comments.$invalid) ? $scope.crossUrl : $scope.crossUrl;
That looked so dirty, but thought it could work after pushing the data in. But the image stayed there (as you can see, I tried replacing the checkmark with a cross instead, as I did not want to create a blank pic).
I also googled it, but everything I could find had to do with two things: clearing the form AND removing the coloured frame (red/green). of course, my form already does that. So, I'm still trying to find a way to remove the word "required" and the gif image in my form upon successful validation.
In any case, I created a plunker. You'll have to click on the word "Reviews" to show the form.
http://embed.plnkr.co/QZT1Jzgg9elMMRHwhYel/preview
Have a look at the directives ng-show and ng-hide.
You can set $scope.allGood = true; somewhere in your controller (after validation) and use this directive: <span ng-hide="allGood">Required</span>
Edit:
You might also want to look at the ng-class directive. Example:
<span ng-class="{green: allGood == 1}">Name:</span> and obviously style the class green to your needs.

Triggering Ajax onchange on a select list

I am working on a Drupal project which is using the Editable fields module.
Using that module I'm exposing a dropdown list of text options. It works just great. You click on the list, select an option and the option is updated via Ajax.
My challenge is I'm trying to change the options programmatically via jQuery. Using the following code:
jQuery('select#edit-field-status-0-field-status-und').val(1);
... my browser console area is happy with the code but the Ajax update does not take place.
I tried:
jQuery('select#edit-field-status-0-field-status-und').val(1).change();
Again no errors but the Ajax event still did not execute.
$('#edit-field-status-0-field-status-und').val("1");
will do the trick, as the only reason it wouldn't work would be that you have your select values as strings instead of numbers.
Alternatively the following is more detailed:
$('#edit-field-status-0-field-status-und option').eq(1).prop('selected', true);
Also this is not an 'AJAX' function, it's simply Jquery updating the DOM for the particular element.
The code I was using as recreated below was correct:
jQuery('select#edit-field-status-0-field-status-und').val(1).change();
I found out the reason why it wasn't working was because the ID of the target element changed dynamically.
So when I first inspected and found edit-field-status-0-field-status-und, the same element would change IDs to something like edit-field-status-0-field-status-und--1.
That was throwing things off and gave the impression my code wasn't working.
Thanks to #gts for your input.

Reload width ajax and keep the current class

I have an issue about ajax.
make an example: I have a menu list (ul li) and by default the first one has class 'current'.
if I click the second item assign class 'current' to him with jquery and remove it from the previous one.
Now, I need reload the menu list with ajax, so I call the ajax function that calls a php function that return an update html list.
But in this way I lose the 'current' class from the second list, that before I assigned with jquery.
Happens to me many times to have this type of problems.. What is the correct solution to solve it?
one way of doing it is to get the index of the li with the class current and in the ajax success callback assign the current class to the appropriate index
look at this fiddle to get the index of the li http://jsfiddle.net/3nigma/zyayj/
in your success callback
success:function(data){
var i = index -1; // index is zero based and eq() is 1 based
$("ul li:eq(i)").addClass("current");
}
I think your question indicates that you don't already know that web pages are "stateless", meaning that they do not "automatically" hold or store anything that you do with them.
Please see my answer ho a privious question which summarizes the ways to deal with retaining the state of things - the principles would remain the same for your menus.
Stateless HTML

Getting Ajax return to replace whole page

This is a followup question to the one I posted last week "Ajax.ActionLink not Posting". I did finally get it to Post, and it properly calls my Delete action and deletes the record. The Delete method returns a RedirectToAction("List") so that the new data set minus the deleted record is re-listed. Except that what actually happens is - NOTHING. The listing doesn't change. And I'm pretty sure I know why: calling Ajax.ActionLink returns an Ajax result which is only supposed to replace a designated element (the UpdateTargetId option parameter) in the document. And since I haven't designated any, it doesn't replace anything, even though it's a whole fresh page.
My question is, what do I pass to the AjaxOption.UpdateTargetId to get it to wipe the whole page and reload with the new result, just as though Html.ActionLink had been called (recalling that the only reason for using Ajax.ActionLink was that I wanted the method invoked with a POST instead of a GET)? (And since this page uses a Master Page, I don't have the option of just putting an ID on the body element.)
You can do a POST without Ajax. You would need to use a Form and change your ActionLink to a Submit button. That might be the simplest way.
Otherwise, you need to change your List action to return a PartialView. This is what renders to your UpdateTargetId, which you can just set as an outer div on your page.
Do you really need to reload your list at all? You can do your Ajax POST to delete the row in the database, and use the OnSuccess property of the AjaxOptions to call a JavaScript function which then removes the row from the html on the page.

Resources