Given a Symfony 2.7 formType object with an added choice field, how can I access the choice strings? - forms

I have created a form object in symfony, which is meant to process an api request. It is created in a controller via:
$myForm = new MyFormType($foo, $bar);
$form = $this->createForm($myForm, $entity, array('method' => 'POST', 'csrf_protection' => false));
Once these objects are created, I pass them into an external service which converts api data into data that's meant to be consumed by the form, like the following:
//I pass this in, so that, our api users don't have to pass in
//{uglyAPIVariable45: 721}, but rather {pretty_variable: "go left"}
$goodData = $this->convertOldData($form->getBuilderDataCopy(), $oldData);
One of the things this service does, is if the form has a choice, like a select tag, it attempts to convert any string passed to the api into the value in select tag. This way, if the user can pass over "East" if the select field has the options "North", "West", "South" and "East" associated with the values 0, 4, 5 and 10 and the converter should return 10. The user doesn't have to pass over one of those random values, they can just pass over the string. And if they passed over "Foo", it would return an error along with a description of what good choices they could pass over.
My problem is that, in production, I'm not able to get ahold of those values.
In development, I found that I could get my options using,
foreach($formBuilderDataCopy as $formElement){
$options = $formElement->getAttributes()['data_collector/passed_options']['choices'];
}
But when we moved to production, this code broke. The method, getAttributes, returned null suddenly. Admittedly, it seemed kind of janky to begin with, so I wanted to find a more valid approach to getting these choices, possibly even allowing me to bypass a different approach for 'choice', 'entity', 'timezone' et. al.
Unfortunately, looking through the source code and exploring it with get_class_methods and friends hasn't provided me with a solution this issue. Even when I get choices, the most I can get are values, but not the string options in the select box.
What's the appropriate approach to acquiring such information from my symphony forms?
As a side note, I have also tried:
$form->get('elementName')->getConfig()->getOption('choices');
But it also just returns a list of the ids to single numbers and not the strings that replace those numbers. e.g.
{3: 0, 5: 1, 10: 2, 11: 3...}

Create an entity Object for the form type. Then you can use the data as object. It must not been a doctrine entity.

Related

Ag-grid setFilter in server side filtering

I just want to check if it's possible to give setFilter values in callback, in form of complex objects instead of array of strings. Reason why we need setFilter to have complex objects is because we are using server side filtering and we would like to show labels in filter, but send back keys to server to perform filtering.
If we have for example objects like {name: 'some name', id: 1} we would like to show 'some name' in filter UI but when that filter is selected we need associated id (in this case 1).
By looking into source code of setFilter and corresponding model, it seems like this is not possible.
Is there a way maybe I am missing that this could work?
ag-Grid version 23.2.0
I have exactly the same problem, from the interface it seems impossible indeed because of expected string[] values
interface SetFilterValuesFuncParams {
// The function to call with the values to load into the filter once they are ready
success: (values: string[]) => void;
// The column definition object from which the set filter is invoked
colDef: ColDef;
}

Symfony 4 : $form->getData() returns empty array where same array is filled in $request->request->all()

I'm facing a weird issue right now
Here is my code :
$data = [];
$form = $this->createFormBuilder($data, ["allow_extra_fields" => true,])
->add("attributes", FormType::class, ["allow_extra_fields" => true,])
->add('save', SubmitType::class, ['label' => 'Save'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return new Response("<pre>".print_r($request->request->all(),1).print_r($data,1)."</pre>");
}
As you can see, for debug purposes, I'm displaying the whole $request->request and $form->getData().
Surprisingly, the first one is totally filled with correct information, the second one is empty.
I'm a bit lazy to censor the information in this array (company information) by hand so here is a censored screenshot of the result :
Any idea why the form is not parsed ?
Thanks !
the standard symfony Form class stores extra data in one place, the extraData property, which can be accessed via getExtraData(). This is obviously not particularly helpful in the case of sub forms (it would probably have to be called on the sub form then). I assume, the allow_extra_fields flag is primarily meant to prevent the form from erroring out in case of extra data, since nobody in their right mind would use the Form class for no fields (hence no validation, and none of the perks of using the form class in the first place). So your usage is ... "innovative".
The proper way to do it, would be to very well define the structure which attributes can have within your form (optionally with required set to false), solving most of the actual problems people try to solve with forms. - This is what forms are meant to be, an object that recursively handles the fields/sub forms. If you just want to ignore / circumvent that ... well
The improper way would be, to probably teach some form type - via some datamapper or datatransformer or event handling stuff - to handle any arbitrary data provided.
The easiest way to do it: just use $request->request->all() possibly a deserializer.

Add rows in smartsheets using python

How do I take a list of values, iterate through it to create the needed objects then pass that "list" of objects to the API to create multiple rows?
I have been successful in adding a new row with a value using the API example. In that example, two objects are created.
row_a = ss_client.models.Row()
row_b = ss_client.models.Row()
These two objects are passed in the add row function. (Forgive me if I use the wrong terms. Still new to this)
response = ss_client.Sheets.add_rows(
2331373580117892, # sheet_id
[row_a, row_b])
I have not been successful in passing an unknown amount of objects with something like this.
newRowsToCreate = []
for row in new_rows:
rowObject = ss.models.Row()
rowObject.cells.append({
'column_id': PM_columns['Row ID Master'],
'value': row
})
newRowsToCreate.append(rowObject)
# Add rows to sheet
response = ss.Sheets.add_rows(
OH_MkrSheetId, # sheet_id
newRowsToCreate)
This returns this error:
{"code": 1062, "errorCode": 1062, "message": "Invalid row location: You must
use at least 1 location specifier.",
Thank you for any help.
From the error message, it looks like you're missing the location specification for the new rows.
Each row object that you create needs to have a location value set. For example, if you want your new rows to be added to the bottom of your sheet, then you would add this attribute to your rowObject.
rowObject.toBottom=True
You can read about this location specific attribute and how it relates to the Python SDK here.
To be 100% precise here I had to set the attribute differently to make it work:
rowObject.to_bottom = True
I've found the name of the property below:
https://smartsheet-platform.github.io/smartsheet-python-sdk/smartsheet.models.html#module-smartsheet.models.row
To be 100% precise here I had to set the attribute differently to make it work:
Yep, the documentation isn't super clear about this other than in the examples, but the API uses camelCase in Javascript, but the same terms are always in snake_case in the Python API (which is, after all, the Pythonic way to do it!)

Add ‘subscription_date’ and ‘user_ip_address’ fields for Newsletter Subscriber and show it in admin panel in Magento

I want to add two custom fields for newsletter subscriber at which date customer subscribed and its ip address:
1) I had added two columns in ‘newsletter_subscriber’ table.
How this can be achieved?
In the file app/code/core/Mage/Newsletter/Model/Subscriber.php
I found the the functions like:
$this->setSubscriberEmail($email);
$this->setStoreId(Mage::app()->getStore()->getId());
$this->setCustomerId(0);
But i did not found its code.
I think I also save data like that but how it will be possible ? where I have to define and declare code for the function like $this->seSubscriptionDate();
And how to display in Admin panel under Newsletter->Newsletter Subscriber ?
I had not find the solution or help from any person.
I bang my head and find the solution its very simple hope in future may some one’s time save by this post:
1) Add columns in the table “newsletter_subscriber” say in my case “subscription_date” and “sub_ip_address”
2) Add following two lines in the file # two places
app\code\core\Mage\Newsletter\Model\Subscriber.php
**$this->setSubscriptionDate(date("d-m-Y"));
**$this->setSubIpAddress($_SERVER['REMOTE_ADDR']);
One place: in the function: public function subscribe($email)
Before: $this->save();
Second place: in the function: public function subscribeCustomer($customer)
Before: $this->save();
Now data will be added in the table
Now to show in admin panel
1) Open the file app\code\core\Mage\Adminhtml\Block\Newsletter\Subscriber\Grid.php
Just add two required columns in it like
$this->addColumn('subscription_date', array(
'header' => Mage::helper('newsletter')->__('Subscription Date'),
'index' => 'subscription_date',
'default' => '----'
));
$this->addColumn('sub_ip_address', array(
'header' => Mage::helper('newsletter')->__('IP Address'),
'index' => 'sub_ip_address',
'default' => '----'
));
Now finish.
** This is the point where I spent my time and at the end I added this function on hit and trieal basis but it works.
Someone from Core magento team plz explain why this {setSubscriptionDate()}function work ? I had not declared anybody of this function.
It seems it shows intellisense to detect table field?
I also had the similar problem. However, in my case I am supposed to add a "country" and "gender" field in the newsletter form. So, on digging into the core for hours I figured this out. Below is the explaination:
In the app/design/frontend//default/template/newsletter/subscribe.phtml,
the form has getFormActionUrl() ?> in its action field. This referes to app/code/core/Mage/Newsletter/Block/Subscribe.php
The $this object used in the subscirbe.phtml file referes to this class (i.e. Mage_Newsletter_Block_Subscribe) and thus $this->getFormActionUrl() in the subscribe.phtml file refers to the function getFormActionUrl() of this class.
Now, this getFormActionUrl() is returning a method $this->getUrl('newsletter/subscriber/new', array('_secure' => true)) which belongs to its parent Mage_Core_Block_Template (I mean the method getURL()). This part is not improtant to us.
See the parameter passed to the getURL() function which is newsletter/subscriber/new
The first part "newsletter" is the module name (app/code/code/Mage/newsletter), the second part "subscriber" is the controller name (app/code/code/Mage/newsletter/controllers/SubscriberController) and the third part "new" is the method newAction in the controller SubscriberController.
Controller names are suffixed with Controller and function names are suffixed by Action. (Thanks to Phalcon framework to help understand this)
Now in the newAction() method you can see that by default, only the email is being posted
as
$email = (string) $this->getRequest()->getPost('email');
What I did was, I cloned the subscribe.phtml template with a name custom-newsletter.phtml and add two fields with name "country" and "gender". Then added the following lines in the newAction():
$country = (string) $this->getRequest()->getPost('country');
$gender = (string) $this->getRequest()->getPost('gender');
Now at line number 67 of the SubscriberController (inside the newAction() method) there is a code :
$status = Mage::getModel('newsletter/subscriber')->subscribe($email);
This line is calling the subscribe method of app/code/code/Mage/newsletter/Model/Subscriber.php and is passing the $email that is posted from newsletter form into it. I modified the line as:
$status = Mage::getModel('newsletter/subscriber')->subscribe($email,$country,$gender);
Now, I have to edit the app/code/code/Mage/newsletter/Model/Subscriber.php
When we talk about Models, we are talking about the database table the Model refers to. The model name is Subscriber and it belongs to module Newsletter so, the database table that this model affects is newsletter_subscriber
From this part on #Hassan Ali Sshahzad's question will be answered.
I added two new columns there with the name: subscriber_country and subscriber_gender.
Now, Magento' system automatically makes available a getter and a setter function to these columns with the following name:
function getSubscriberCountry(){}
function setSubscriberCountry($country_name){}
So, all I had to do in the model was:
Edit the method subscribe($email) to subscribe($email,$country,$gender)
add the following code in the subscribe($email,$country,$gender) function right before the try statement as follows:
$this->setSubscriberCountry($country);
$this->setSubscriberGender($gender);
try{
$this->save()
Hassan's method played a key role in my understanding of the MVC of Magento so its a return from my side.

Symfony: Model Translation + Nested Set

I'm using Symfony 1.2 with Doctrine. I have a Place model with translations in two languages. This Place model has also a nested set behaviour.
I'm having problems now creating a new place that belongs to another node. I've tried two options but both of them fail:
1 option
$this->mergeForm(new PlaceTranslationForm($this->object->Translation[$lang->getCurrentCulture()]));
If I merge the form, what happens is that the value of the place_id field id an array. I suppose is because it is waiting a real object with an id. If I try to set place_id='' there is another error.
2 option
$this->mergeI18n(array($lang->getCurrentCulture()));
public function mergeI18n($cultures, $decorator = null)
{
if (!$this->isI18n())
{
throw new sfException(sprintf('The model "%s" is not internationalized.', $this->getModelName()));
}
$class = $this->getI18nFormClass();
foreach ($cultures as $culture)
{
$i18nObject = $this->object->Translation[$culture];
$i18n = new $class($i18nObject);
unset($i18n['id']);
$i18n->widgetSchema['lang'] = new sfWidgetFormInputHidden();
$this->mergeForm($i18n); // pass $culture too
}
}
Now the error is:
Couldn't hydrate. Found non-unique key mapping named 'lang'.
Looking at the sql, the id is not defined; so it can't be a duplicate record (I have a unique key (id, lang))
Any idea of what can be happening?
thanks!
It looks like the issues you are having are related to embedding forms within each other, which can be tricky. You will likely need to do things in the updateObject/bind methods of the parent form to get it to pass its values correctly to its child forms.
This article is worth a read:
http://www.blogs.uni-osnabrueck.de/rotapken/2009/03/13/symfony-merge-embedded-form/comment-page-1/
It gives some good info on how embedding (and mergeing) forms work. The technique the article uses will probably work for you, but I've not used I18n in sf before, so it may well be that there is a more elegant solution built in?