Processing of form with redirect [plesk/zend] - zend-framework

I am using Plesk Sample 1.5-1 as a base, but stuck on how to process POST w/parameters.
My form is a 'text' element and 'ok' submit button and below that is a list that will change based on the value of the 'text' element (external XML call).
Inside IndexController, in the ->getRequest->isPost() area, I have a redirect line:
$this->_helper->json(array('redirect' => pm_Context::getBaseUrl()));
Do I have to manually pass the parameters on this line? Or does the controller know because I created a pm_Form_Simple() and added elements? Right now if I am outside the ->isPost block, the parameters are null, so that is why I am thinking I have to manually pass them along.
Do I need something like this?
$this->_redirector->gotoSimple('my-action',
'my-controller',
null,
array('exampleText' => $form->getValue('exampleText'));
I guess am just not understanding how the POST works.
I have looked at the Zend Guestbook example, but it is different enough from Plesk that I can't mentally translate it...and it doesn't redirect to the same page, it redirects some where else.
Ultimately, I want to set the 'exampleText' parameter with a "start date" and after the POST call, make an external XML call and fill out the list... I can make the XML call, but can't get the workflow around empty form -> fill out form and press "ok" -> post processing
thx!

Turns out that the pm_Form_Simple needs JSON I didn't notice that my orig code had JSON but didn't encode the new code...

Related

Adding a confirmation form before the add form of a content type

One of our customers wants to add a terms of service page that has to be shown every time a user adds some specific content type, before the add form.
Any suggestions on how to implement this?
If it's a Dexterity content type, you can do this:
Create a custom form with your terms of service. In the form's button handler, redirect to the add form:
self.request.response.redirect(self.context.absolute_url() + '/++add++name.of.content.type')
Now in your type's factory info in portal_types, set the add_view_expr like this:
<property name="add_view_expr">string:${folder_url}/##terms-of-service</property>
so it goes to the custom TOS form when you click the type in the factory menu, instead of directly to the add form.
(Note: a downside of this approach is that if the user enters the URL of the add form directly, they can bypass the TOS form.)
A possible solution could be to use a cookie/session_data_manager/token/you-name-it that on the custom AddForm for that content type checks if exists.
If it doesn't redirect to that Terms of Service form that redirects back to the Addform where, now it will accept to proceed becuase the cookie/session_data_manager/token/you-name-it will be there.
An idea: when you are adding new content types (AT based content types, this will not work for Dexterity ones) you are calling
http://something/createObject?type_name=Document
You can transform the createObject script into an view that display you disclaimer form, with validation on submit.
When user accept the disclaimer you will redirect the use to something like
http://plone4.gest.unipd.it:8080/gest/it/realCreateObject?type_name=Document
where realCreateObject is a copy/paste of the original Plone createObject script.
However: the suggestion of Mathias above is really good: just add a fake checkbox field with a validation.
As mentioned in the comment of the question. I would advise adding a checkbox to the content.
For AT content you can add a BooleanField
...
atapi.BooleanField(
name='acceptConditions',
schemata='default',
required=False,
default=False,
validators=('acceptConditions', ),
widget=atapi.BooleanWidget(
label=_(u'label_accept_conditions', default='Conditions'),
description=_(
u'help_accept_conditions',
default='Please accept the <a target="_blank" '
'href="./conditions_view">'
'conditions<a/>.')
),
)
...
With a condition on the widget (In this case a browser view, which checks if the boolean field should be visible or not).
YourSchema['acceptConditions'].widget.setCondition(
'python: here.restrictedTraverse("##show_condition_field").show()')

using Ajax , dropdownlist and page validation

using Ajax I filled Country, State and city dropdownlist. On land change state is filled and on state change city is filled properly.
Then when I try to save page I face this :Invalid postback or callback argument.
Searched and found out that this is due to change in ddl.selectedvalu change from initial value that is assigned by asp.net.
Now my question is that how can I let asp.net know that the new ddl value is valid?
Thank you.
In many pages it is recommended to use EnableEventValidation="false", but I prefer not to use it.
Some say that use Render and add value to notify .Net like this:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation("ddlLanguages ", "English");
ClientScript.RegisterForEventValidation("ddlLanguages ", "Tamil");
ClientScript.RegisterForEventValidation("ddlLanguages ", "Hindi");
base.Render(writer);
}
but how to use it? where to put it?
for a better understanding I put here a sample code including Database script :
hesab20.com/DownLoad/Ajax.zip
in this sample Javascript is used to fill drop-down list . But when click button is executed and a post back occur, error happen.
Please help if you have experience with this.
Regards.
Please run the sample code and change the drop down lists , automatically the other is filled , meaning that list item text and value is completely changed. finally click button for a post back.
you must see that error happens:
Invalid postback or callback argument. Event validation ....
and note : EnableEventValidation="true"
Thanks

Zend creating forms based on requests within one controller/action

I don't really know how to word the title well, but here's my issue. I decided instead of having 25 controllers to handle pages, I have one PageController with a viewAction that takes in a :page parameter - for example, http://localhost/website/page/about-us would direct to PageController::viewAction() with a parameter of page = about-us. All of the pages are stored in a templates folder, so the viewrenderer is set to render application\templates\default\about-us.phtml.
I did this so I can consolidate and it seemed like a better approach. My question is the following: lets say when the page request is contact-us, I would need a Zend_Form to be used within the contact page. So, I would need a way within PageController::viewAction() to recognize that the page needs to have a form built, build the form, and also upon submission the need to process it (maybe this should be handled in an abstract process method - not sure).
I have no idea how to implement this. I thought maybe I can store a column with the name of a form and a connecting page identifier. Even better, create a one-to-many page to forms, and then in the submission loop through the forms and check if submitted and if so then process it (maybe there is a isSubmitted() method within zend_form. I really don't know how to handle this, and am looking for any help i can get.
Thanks!
Here is something that came to mind that may work or help point you in a direction that works for you.
This may only work well assuming you were to have no more than one form per page, if you need more than one form on a page, you would have to do something beyond this automatic form handling.
Create a standard location for forms that are attached to pages (e.g. application/forms/page). This is where the automatic forms associated with pages will be kept.
In your viewAction, you could take advantage of the autoloader to see if a form for that page exists. For example:
$page = $this->getParam('page');
$page = ucfirst(preg_replace('/-(\w)/ie', "strtoupper('$1')", $page)); // contact-us -> ContactUs
$class = 'Application_Form_Page_' . $page;
// class_exists will invoke the autoloader to map a class to a file
if (class_exists($class)) {
// a form is defined for this page
$form = new $class();
// check if form was posted
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost()) {
// form is valid - determine how to process it
}
}
// assign the form to the view
$this->view->pageForm = $form;
}
All this really leaves out is the action you take to process a specific form. Since the contact form will likely generate an email, and another form may insert data into a database, you will need some sort of callback system or perhaps another class that can be mapped automatically which contains the form processor code.
Anyway something along those lines is what came to mind first, I hope that helps give you some more ideas.

I'm not specifying the form action but it (automatically) gives different values in some cases

I'm creating my form using the Form helper, so the action of the form is specified automatically....
this form is used for editing a post..
so, the URL has the structure: mywebsite.com/posts/edit/id
and the form's action should be automatically generated as posts/edit/id
but the problem is, in some cases, I open the HTML code and I find that the form's action is only posts/edit without the id which causes the update to fail...
I spent a lot of time to figure out what situation brings this wrong action:
i'm generating fields dynamically (using javascript & ajax) depending on the post's category..
when the value of one of the dynamically generated fields is invalid, the generated action becomes posts/edit !!
I really need help, cuz I don't know why this is happening !!!
and I don't wanna waste more time digging into the core of cakephp...
so, if any of cakephp experts has an idea about this, plz help me !!
thank you in advance !
Use the url parameter, which allows you to explicitly define a url for the form:
echo $form->create('Post', array('url' => $html->url(array('action'=>'edit', $id))));
It sounds like $id probably isn't getting set, because it should be getting passed along if it is. You need to make sure it's set to edit the record in question. Make sure your javascript is including the hidden field with the record's id in it.
Normally done like this, with the form helper: echo $this->Form->input('id');
Also, if one of the fields is invalid, the form shouldn't actually be submitting properly, if you are using cake's validation, so this is to be expected.

MVC Html.textbox/dropdown/whatever won't refresh on postback

OK, let's start with the Html.Textbox. It is supposed to contain text read from a file. The file read is based on what the user picks from a dropdown list.
The first time it is fine. The user picks a value from the dropdown list. The controller uses that value to read some text from a file, and returns that text to the view via the view model. Everything is fine.
THen the user picks another value from the dropdown list. The controller reads a new value from a file and returns it via the view model. Debugging to the LINE BEFORE THE HTML.TEXTBOX is set in the view shows that the model contains the correct value. However, the textbox itself still shows the PREVIOUS value when the page displays!
If I switch from Html.Textbox to a plain input, type="text" html control, everything works fine. That's not so hard, but the same thing happens with my dropdown list -- I can't set the selected value in code. It always reverts to whatever was chosen last. Rendering a "select" tag with a dynamically-generated option list is a pain. I would love to be able to use Html.Dropdown.
What am I missing here?? This is such a simple thing in webforms!
When you post a form, the values that are posted are put into ModelState. When the HtmlHelper renders an html iunput element, e.g. Html.TextBoxFor(x => x.FirstName), it'll search various locations to get the value for the textbox... ModelState is before ViewData.Model in the list of locations. So there for, the previously posted value will appear in your textbox.
To fix this you could clear the ModelState value or update the ModelState value. BUT I would kinda view that as a hacky way of getting around the problem.
The real issue has more to do with the flow of the posts and requests. I would personally look into that and maybe implement the PRG (Post Redirect Get) pattern.
HTHs,
Charles
Following on from what Charles/Charlino said:
Model binding updates the ModelState object, which contains validation and model binding errors that are collected during model binding.
Inside an action method, model binding has occurred already to update the model, and generated the ModelState object. If you now update the value on the model inside the action, you must also manually update the model state (since the helpers use it to generate their HTML). Below is an example:
model.CaptchaIsValid = CaptchaService.ValidateAndExpireCaptcha(model.CaptchaAttempt);
if (!model.CaptchaIsValid)
{
ModelState.AddModelError("CaptchaAttempt", "Incorrect - please try again");
}
// I'll clear the value on each attempt, to force them to re-enter a CAPTCHA.
model.CaptchaAttempt = string.Empty;
// Since I updated the model, I must create a new ValueProvider result...
ValueProviderResult clearedValue = new ValueProviderResult(
model.CaptchaAttempt,
model.CaptchaAttempt,
CultureInfo.CurrentCulture);
// ... and update the ModelState's value.
ModelState.SetModelValue("CaptchaAttempt", clearedValue);
The biggest issue I see here is that you are trying to do a postback within MVC. That model is really not supported, and is actually way more trouble than it is worth (as it seems you are finding out). I would recommend using Ajax to update the contents of the dropdown dynamically.