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

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

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

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

How to customize register and contact forms in PrestaShop?

I need to know how to customize my contact and register forms. How to add new fileds ( and ) and make the information from these fields required or not required.
I need to know which files I must edit for these forms...
I use prestashop 1.4.7.0
This is really two separate questions as there are major differences in how you would handle each case.
Answer 1
For the registration form you can write a module which contains two hook handler functions. These will be:
public function hookCreateAccountForm() {}
public function hookCreateAccount($params) {}
The first function allows you to add additional fields to the registration form (by default these are inserted at the end of the form authentication.tpl, although you could move them all as a single group elsewhere). It should simply return the additional form html you require.
The second function provides you with two parameters to handle the account creation process. This is executed after the standard fields have been validated and the new customer has been created. Unfortunately you cannot do validation on your additional fields using this (you would need to either use javascript or override AuthController to perform your own authentication in the preProcess() member function). In one of my own custom modules for a site I have the following, for example:
public function hookCreateAccount($params)
{
$id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$customer = $params['newCustomer'];
$address = new Address(Address::getFirstCustomerAddressId((int)$customer->id));
$membership_number = $params['_POST']['membership_number'];
....
....
}
$params['newCustomer'] is a standard Prestashop element in the array and contains the newly created customer object. Your fields will be in the $params['_POST'] array - in my case it was an input field called membership_number.
Answer 2
For the contact form it's a whole lot more complicated I'm afraid. The simplest method for the html is to just hard-code your additional fields in the template file contact-form.tpl.
To actually process the form you will need to create an override for the controller by ceating a file called ContactController.php in /<web-root>/<your-optional-ps-folder>/override/controller containing something like:
<?php
class ContactController extends ContactControllerCore {
function preProcess()
{
if (Tools::isSubmit('submitMessage'))
{
// The form has been submitted so your field validation code goes in here.
// Get the entered values for your fields using Tools::getValue('<field-name>')
// Flag errors by adding a message to $this->errors e.g.
$this->errors[] = Tools::displayError('I haven't even bothered to check!');
}
parent::preProcess();
if (Tools::isSubmit('submitMessage') && is_empty($this->errors))
{
// Success so now perform any addition required actions
// Note that the only indication of success is that $this->errors is empty
}
}
}
Another method would be to just copy the entire preProcess function from controllers\ContactController and just hack away at it until it does what you want....

Symfony 2 Form validation with dependencies

I have an entity with 2 fields (of course some more, but for simplicity only 2 :) ):
class Entity
{
// boolean type
protected $is_public;
// hashed string
protected $password;
}
Now I need a form in symfony 2 for that entity with the following dependencies on the password field:
When the user clicks the checkbox for $is_public, he does not have to enter a password. On the other hand, when the user wants the entity (in my case a user-group) as non-public, he must enter a password with at least N characters.
How would you do that with the validators shipped with symfony2 framework? Is there a way to achieve my goals?
Thank you in advance,
Andi
The unique way i have found is to create a custom Constraint, with a class constraint you can access all properties of your object.
Look at these classes:
UniqueEntityValidator.php
UniqueEntity.php
and create your own with your logic.
You can specify a callback function that is called at validation time, and have it do pretty much whatever you want. Here are the docs:
http://symfony.com/doc/current/reference/constraints/Callback.html
Note that if you are using translations, you can also specify a string-key in the addViolation call.
$context->addViolation(
'Acme\DemoBundle\Entity\MyEntity.entityField.validationErrorString1',
array(), null);

Can I do more than one form for the same model class in symfony?

Well, imagine that we have a register form of a class Customer and we only ask three fields (name,surname,email) and after, when this user logged first time we want to complete this information.
First, we have in lib/form/doctrine a file called 'CustomerForm.class.php' wich is generated automatic on command line. In this file we 'setup' only 3 fields and validators and if we wanna use we do something like that:
$this->form = CustomerForm();
Second, we create manual another form named 'CustomerFormStep1.class.php' where we can setup for validate the other fields. But when we do..
$this->form = CustomerFormStep1();
it returns error: Fatal error: Class 'CustomerFormStep1' not found
What is wrong?
Thanks.
Assuming you have the form defined as:
class CustomerFormStep1 extends sfForm
or similar (sfFormDoctrine etc), and named correctly like you say (CustomerFormStep1.class.php) and in lib/form, then Symfony should just pick the definition up fine. Did you clear the cache after creating and placing it in the right place? (symfony cc).
Create the new CustomerFormStep1 class as #richsage instructed. Then, in your actions you can write something like:
public function executeLogin(){
//before login
$this->form = new CustomerForm();
}
public function executeLoggedIn(){
$this->form = new CustomerFormStep1();
//other steps
}
Haven't you read the tutorial? Extending forms is perfectly described in context with reh admin generator and can of course be applied to any case.