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

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);

Related

Shopware 6 Forms

Newbie question. How to handle Storefront Form Submit in Shopware 6? How to save the data from form to database? I have an entity, form shown in storefront and a controller but i have no idea how to save the data to entity. Thanks in advance.
you would have to be more specific with the description, of what exactly you are trying to achieve.
But in general, if you already have a controller, that receives the data, then you can get them from the request like this:
$data = $request->request->all();
By this, you have all the values from your form saved in an array $data. You have written, that you already have an entity, so from that I assume, that your entity is already mapped to your database table. So the only thing you have to do, is to use the repository to save the data. For thta, you just need to inject it into your class and get a context. The context depends on where you currently are, so for the purpose of the example, I have just created the default context.
It should look like this:
class MyClass
{
protected $myEntityRepository;
public function __construct(
MyEntityRepository $myEntityRepository
)
{
$this->myEntityRepository = $myEntityRepository;
$this->context = \Shopware\Core\Framework\Context::createDefaultContext();
}
public function myMethod ($data)
{
$this->myEntityRepository->upsert($data, $this->context);
}
}
Hope this helps. I have actually written an article on repositories in Shopware 6, so if you want to get some more information and examples, you can check it here: https://shopwarian.com/repositories-in-shopware-6/.

TYPO3: repository->findAll() not working

I am building an extension with a backend module. When I call the findAll() method it returns a "QueryResult" object.
I tried to retrieve objects with findByUid() and it does work.
I set the storage pid in the typoscript:
plugin.tx_hwforms.persistence.storagePid = 112
I can also see it in the typoscript object browser.
I also added this to my repository class:
public function initializeObject()
{
$defaultQuerySettings = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings::class);
$defaultQuerySettings->setRespectStoragePage(false);
$this->setDefaultQuerySettings($defaultQuerySettings);
}
so that the storage pid is ignored ...
It's still not working, findAll doesn't return an array of entites as it should
Repository must return a QueryResult from the findAll methods. Only methods which return a single object (findOneByXYZ) will return anything else.
All of the following operations will cause a QueryResult to load the actual results it contains. Until you perform one of these, no results are loaded and debugging the QueryResult will yield no information except for the original Query.
$queryResult->toArray();
$queryResult->offsetGet($offset); and $queryResult[$offset];
$queryResult->offsetExists($offset);
$queryResult->offsetSet($offset, $value); and $queryResult[$offset] = $value; (but be aware that doing this yourself with a QueryResult is illogical).
$queryResult->offsetUnset($offset); and unset($queryResult[$offset]); (again, illogical to use this yourself)
$queryResult->current(), ->key(), ->next(), ->prev(), ->rewind() and ->valid() which can all be called directly or will be called if you begin iterating the QueryResult.
Note that ->getFirst() and ->count() do not cause the original query to fire and will not fill results if they are not already filled. Instead, they will perform an optimised query.
Summa summarum: when you get a QueryResult you must trigger it somehow, which normally happens when you begin to render the result set. It is not a prefilled array; it is a dynamically filled Iterator.
This should work.there must be issue with your storage page in FindAll() extbase check for storage but in findByXXX() it ignore storage.
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\Extbase\\Object\\ObjectManager');
$querySettings = $objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->cityRepository->setDefaultQuerySettings($querySettings);
$cities = $this->cityRepository->findAll();
Use additionally typoscript module configuration, like
module.tx_hwforms.persistence.storagePid = 112
Ensure your Typoscript is loaded in root. For BE modules I prefere to use
EXT:hwforms/ext_typoscript_setup.txt
where you write your module and extbase configuration.
Try to debbug like below and check findAll() method present for this repositry. I think this is useful for you click here
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(get_class_methods($this->yourRepositryName)); exit();
Afetr added all your changes once you need to uninsatll/install extension.
I would inspect the generated query itself. Configure the following option in the install tool:
$GLOBALS["TYPO3_CONF_VARS"]["sqlDebug"]
Note: dont do this in production environemnt!!
Explanation for sqlDebug:
Setting it to "0" will avoid any information being print on screen.
Setting it to "1" will show errors only.
Setting it to "2" will print all queries on screen.
So in Production you want to keep it at "0", in development environments you should set it to "1", if you want to know why some result is empty, configure it to "2".
I would guess that some enablefield configuration causes your problem.
If you retrieve an object by findByUid you will have the return because enablefields are ignored. In every other case enablefields are applied and that may cause your empty result.

Clear posted values before returning the view

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.

What is correctness in symfony to fill a form in two steps?

Hy,
What is correctness in symfony to fill a form in two steps? Imagine that we have a entity called Enterprise and we want to create a form with only required fields and another form, that when the user login can fill the other non-required fields.
How is the correctness form? Now i have a form to registration ('lib/form/doctrine/EnterpriseForm.class.php') and another ('lib/form/doctrine/EnterpriseCompleteForm.class.php').In every class we set labels, validators, ... but the problem is in the second form. When i try to submit it gives me an error because i have'nt post required fields defined in model. How can i do that? Is that way correct? How can i fix this?
thanks.
You should unset every non needed form field in the second form (of course you should keep a hidden field with the ID of the record).
Basically you just update the record with the second form so every required field in your database already as a value.
It would help if you post the code of the second form.
So in summary your approach is valid (maybe there are better ways I don't know), just make sure that your code is correct.
Edit:
So if I got you correctly then the form you use in your code updates an existing object. You should pass this object to the form knows, that the object already exists and can validate the values accordingly:
public function executeStepOne(sfWebRequest $request){
$this->customer = Doctrine::getTable('Customer')->find(1);
$this->forward404Unless($this->customer);
$this->form = new CustomerFormStepOne($this->customer);
if ($request->isMethod(sfRequest::POST)){
$this->processRegisterForm($request, $this->form,'paso2');
}
For the duplicate key error, check your database definition if the primary key of this table gets incremented automatically.
Well Felix, i do it "unset" changes and it works fine... but i have a problem. I try to do update on the same action. My code looks like that.
in actions
public function executeStepOne(sfWebRequest $request){
$this->form = new CustomerFormStepOne();
if ($request->isMethod(sfRequest::POST)){
$this->processRegisterForm($request, $this->form,'paso2');
}else{
$this->customer = Doctrine::getTable('Customer')-> find(1);
$this->forward404Unless($this->customer);
}
}
where processRegisterForm code is :
protected function processRegisterForm(sfWebRequest $request, sfForm $form,$route)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$customer = $form->save();
$this->redirect('customer/'.$route);
}
}
if i try to do this they returns me an error 'primary key duplicate'.

correct usage of Zend_Db

I'm currently using the Zend_Db class to manage my database connections.
I had a few questions about it.
Does it manage opening connections smartly? (eg, I have a connection already open, does it know to take use of it - or do I have to constantly check if theres' already an open connection before I open a new one?)
I use the following code to fetch results (fetching in FETCH_OBJ mode):
$final = $result->fetchAll();
return $final[0]->first_name;
for some reason, fetchRow doesn't work - so I constantly use fetchAll, even when I'll only have one result (like searching WHERE id= number and id is a PK)
My question is - how much more time/memory am I sacrificing when I use fetchAll and not fetchRow, even when there's only result?
I've created the following class to manage my connections:
require 'Zend/Db.php';
class dbconnect extends Zend_Db
{
function init ()
{
$params = array (......
return Zend_Db::factory ( 'PDO_MYSQL', $params );
}
}
and then I call
$handle = dbconnect::init
$handle->select()....
is this the best way? does anyone have a better idea?
Thanks!
p.s. I'm sorry the code formatting came out sloppy here..
Lots of questions!
Does it manage opening connections
smartly?
Yes, when you run your first query, a connection is created, and subsequent queries use the same connection. This is true if you're reusing the same Zend_Db adapter. I usually make it available to my entire application using Zend_Registry:
$db = Zend_Db::factory(...) // create Db instance
Zend_Registry::set('db', $db);
//in another class or file somewhere
$db = Zend_Registry::get('db');
$db->query(...)//run a query
The above code usually goes in your application bootstrap. I wouldn't bother to extend the Zend_Db class just to initialise and instance of it.
Regarding fetchRow - I believe the key difference is that the query run is limited to 1 row, and the object returned is a Zend_Db_Table_Row rather than a Zend_Db_Table_Rowset (like an array of rows), and does not perform significantly slower.
fetchRow should be fine so post some code that's not working as there's probably a mistake somewhere.
addition to dcaunt's answer:
FetchAll returns array OR Zend_Db_Talbe_Rowset - depending on if you execute $zendDbTableModel->fetchAll() or $dbAdapter->fetchAll()
Same goes for fetchRow(). If you fail to make fetchRow working for models, it's easier to use $model->getAdapter()->fetchRow($sqlString);