Clear posted values before returning the view - forms

I implemented a feature to automatically load the next record after finishing the current one. On the server, I can get the next record and load it into the model fine. The problem is, when I return the view, MVC favors the posted values from the previous record over the model values from the current record.
Public Function Update(model As UpdateModel) As ActionResult
'... save changes to the model
If model.LoadNext Then
Dim nextRecord As UpdateModel = GetNextRecord()
Return View(nextRecord)
Else
Return RedirectToAction("Index")
End If
End Function
I've confirmed in the debugger that I am passing the nextRecord properly. The view is reading the posted values (from the Request I guess?) instead of using the model.
Is there a way to avoid this behavior. Request.Form, Request.Params, and Request.QueryString are all read only so I cannot clear them.

You should call ModelState.Clear() before returning the view. Keep in mind Post-Redirect-Get is also an option if you don't want to break user navigation.

Related

Get field values in record.js

I override the record view, by creating in custom/modules/myModule/clients/base/views/record/record.js this file record.js. I want to get the value of a field for the current object and I use this.model.get('duration'), but I get nothing.The only field available is "id". How can I retrieve the values for others fileds?
When the record.js script is initially called, the model won't have fully loaded, so the only available field with be the id.
Your best bet is probably to override the _renderHtml function; by the the time the view is being rendered all the model details will have fully loaded:
_renderHtml: function() {
// custom code involving this.model.get('duration')
// call parent
app.view.View.prototype._renderHtml.call(this);
}
Note that you may find _renderHtml is called multiple times, sometines before the model is fully loaded. This is just a quirk of Sugar so it may be best to add a check in your code:
if (this.model.get('duration')) {
// custom code involving this.model.get('duration')
}
Dont forget that app.model.get('myfield') only delivers the right content (from this field) when your field is already displayed in detailview - else you will get "undefined"!
So you
Have to call the rest api (rest/v10/yourmodel/yourid) - than you
have all the values available
Display your fields (even you dont want to) to be able to use it in app.model.get('yourfield'), an alternative you could append your record.js (after rendering) with $('div [data-name="yourfield"]').hide();
I know this question is quite old already (but if someone else run into this he could find this useful).

Zend Framework 1.12, execution of raw SQL inserts the same record twice

I know there´s a similar situation in stack, and I´ve already checked it out and the answers have not guided me to mine.
Here´s the deal:
I need to execute raw SQL, an INSERT to be precise. I have multiple values to insert as well. No problem since Zend let´s you use "query" from Zend_Db_Table (I use my default adapter, initialized in my application.ini file).
$db_adapter = Zend_Db_Table::getDefaultAdapter();
....query gets built...
$stmt = $db_adapter->query($query);
$stmt->execute();
When doing var_dump($query); this is what I see:
INSERT INTO tableName (col1,col2,col3) VALUES ('value1', 'value2', 'value3')
I have already tried the following:
I have no "manifesto" attribute on the html page rendered
I have looked at the network both with Chrome and Firefox to see the POSTS/GETS getting sent, and the controller whose actions does
this INSERT gets called once with a POST.
It is true that I call a viewscript from another action to be rendered, like so:
$this->renderScript('rough-draft/edit.phtml');
I don´t see how that could affect the statement getting executed twice.
I know it gets executed twice:
Before the POST is sent, the data base has nothing, clean as a whistle
POST gets sent, logic happens, from is rendered again
Data base now has the same record twice (with the name that has been inserted from the POST), so it´s not a rendering problem
It has to do with the way I am executing raw SQL, because if I use ->insert($data) method that comes with Zend_Db_Table_Abstract (obviously I declare a class that extends from this abstract one and bind it to the appropriate table) it does not insert the record twice. Thing is, I want to use raw SQL.
I really appreciate your help!
Expanded as requested:
Controller code:
public function saveAction()
{
$request = $this->getRequest();
if (!$request->isPost())
$this->_sendToErrorPage();
$this->_edit_roughdraft->saveForm($request->getPost());
$this->view->form = $this->_edit_roughdraft->getForm();
$this->renderScript('rough-draft/edit.phtml');
}
Code from model class (in charge of saving the form from the data in POST):
public function saveForm($form_data) {
$db = new Application_Model_DbTable_RoughDrafts();
$id = $form_data['id'];
$db->update($this->_get_main_data($form_data), array('id=?' => $id));
/* Main data pertains to getting an array with the data that belongs to yes/no buttons
* and text input. I need to do it as so because the other data belongs to a dynamically
* built (by the user) multi_select where the options need to be deleted or inserted, that
* happens below
*/
$multi_selects = array('responsables', 'tareas', 'idiomas', 'habilidades', 'perfiles');
foreach($multi_selects as $multi_select){
if(isset($form_data[$multi_select]) && !empty($form_data[$multi_select])){
$function_name = '_save_'.$multi_select;
$this->$function_name($form_data[$multi_select], $id);
}
}
$this->_form = $this->createNewForm($id, true);
//The createNewForm(..) simply loads data from data_base and populates form
}
I do want to make clear though that I have also used $db->insert($data), where $db is a class that extends from Zend_Db_Table_Abstract (associated to a table). In this case, the record is inserted once and only once. That´s what leads me to believe that the problem lies within the execution of my raw sql, I just don´t know what is wrong with it.
I should have done this from the beginning, thanks for the help everyone, I appreciate your time.
I knew the problem was with my syntax, but I didn´t know why. After looking at different examples for how people did the raw sql execution, I still didn´t understand why. So I went ahead and opened the class Zend_Db_Adapter_Abstract in Zend library and looked for the 'query()' method I was using to get the statement to execute.
public function query($sql, $bind = array())
{
...some logic...
// prepare and execute the statement with profiling
$stmt = $this->prepare($sql);
**$stmt->execute($bind);**
// return the results embedded in the prepared statement object
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
So the ->query(..) method from the Zend_Db_Adapter already executes said query. So if I call
->execute() on the statement that it returns, I'll be the one causing the second insert.
Working code:
$db_adapter = Zend_Db_Table::getDefaultAdapter();
....query gets built...
$db_adapter->query($query);

Symfony form gets messy when calling getObject() in form configuration

I have a Strain model that has a belongsTo relationship with a Sample model, i. e. a strain belongs to a sample.
I am configuring a hidden field in the StrainForm configure() method this way:
$defaultId = (int)$this->getObject()->getSample()->getTable()->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));
Whenever I create a new Strain, the $form->save() fails. The debug toolbar revealed that it tries to save a Sample object first and I do not know why.
However, if I retrieve the default sample ID using the table it works like a charm:
$defaultId = (int)Doctrine_Core::getTable('Sample')->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));
My question here is what can be happening with the getObject()->getSample()... sequence of methods that causes the StrainForm to think it has to save a Sample object instead of Strain.
I tried to debug with xdebug but I cannot came up with a clear conclusion.
Any thoughts?
Thanks!!
When you call getSample its creating a Sample instance. This is automatically attached to the Strain object, thus when you save you also save the Sample.
An altenrative to calling getSample would be to chain through Strain object to the Sample table since i assume youre only doing this so your not hardcodeing the Sample's name in related form:
// note Sample is the alias not necessarily the Model name
$defaultId = Doctrine_Core::getTable($this->getObject()->getTable()->getRelation('Sample')->getModel())->getDefaultId();
Your solution probably falls over because you can't use getObject() on a new form (as at that stage the object simply doesn't exist).
Edit: Why don't you pass the default Sample in via the options array and then access it from within the form class via $this->getOption('Sample') (if I remember correctly)?

MVC 2 partial for edit/create return error

I got a question about MVC 2 and returning views for partials:
I got two views for creating and editing a user, the views both uses a partial so i can reuse the form fields.
UserPartial.ascx, EditUser.aspx, CreateUser.aspx
I got some logic in the controller post method (EditCreateUser) which finds out if its a new or existing user which is beeing submitted and this works fine.
The problem is when I try to return the edited user: return View(user). MVC complains about EditCreateUser file not existing. But thats only the method name, i want to return the object to the EditUser view which I am already on.
I could use RedirectToAction but i rather not because this problem would occur also if i want to return the same object when some errors has occured.
Any ideas on how to do this or some pointers in the right direction would be awesome.
Thanks
Within an action method named EditCreateUser, the statement return View(user) will by default look for a view with the same name as the action. You need return View("EditUser", user)

EF4 POCO - Updating a navigation property

I have a Recommendation object and a FeedbackLevel object and the FeedbackLevel object is a navigation property inside a Recommendation object
Recommendation
int EntityKey;
FeedbackLevel Level;
Inserting a new one works just fine with AddObject(). Here's what I'm trying with the update, which doesn't work.
recommendation.Level = myRepository.GetFeedbackLevel(newLevel);
_context.Recommendations.Attach(new Recommendation { EntityKey = recommendation.EntityKey });
_context.Recommendations.ApplyCurrentValues(recommendation);
_context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
The code above is basically a compact version of what I have. Updating a scalar property works just fine, but I can't update a new navigation property as the avove code succeeds without any changes!
I've also tried a few other methods like getting an existing Recommendation first and then re-assigning the FeedbackLevel to it without any luck.
UPDATE:
Here is what I captured from the sql profiler during the save call:
exec sp_executesql N'update [dbo].[Recommendation]
set [FeedbackComment] = #0, [LastUpdatedDate] = #1
where ([RecommendationKey] = #2)
',N'#0 varchar(255),#1 datetime,#2 int',#0='This is cool',#1='2010-01-08 10:06:06.5400000',#2=11
It looks like it does not even know that the FeedbackLevel needs to be saved. How can I get it to trigger it?
Not sure exactly what your trying to do here,
but if your trying to do an update, simple way is to
1) do a, GET [entityName] by id, use include to get any child properties
2) update the attributes
3) make sure the entity state is modified
4) Save changes
By doing a GET first, you wont need to get attach it to the context before you update, as it will be already in there.