Symfony FileFormField - Testing (WebTestCase) multiple file upload - forms

In my Symfony web application I have a form allowing multiple file upload (easily done by setting the multiple property of the FileType equal to true). And this works fine: I can select multiple files and upload them. Processing the form and getting all uploaded files also goes fine. But of course, I want to foresee an integration test (WebTestCase) but I don't find any possibility to simulate a multiple file upload.
What I have now:
...
$uploadedFile = new UploadedFile(...);
$form = ...; // get the form from the crawler
$form['formtype[filename]'][0]->upload($uploadedFile);
$this->client->submit($form);
...
That works fine.
But now I want to upload 2 files by 1 form submission (because the processing logic can behave differently when multiple files are uploaded at once). How can I do this? When I look at http://api.symfony.com/3.0/Symfony/Component/DomCrawler/Field/FileFormField.html I don't see any way to pass in, for example, an array of UploadedFile objects. Anyone experience with this?

If the multiple property is set, crawler creates a file form field array with single FileFormField field. One field can hold a single file so you need multiple fields for multiple files. I came to a solution by manually adding more FileFormField to the form.
$form = ...
// get file field node in DOM
$node = $crawler->filter("input[name='formtype[filename][]']")->getNode(0);
// add additional fields to form (you can create as many as you need)
$newField = new FileFormField($node);
$form->set($newField);
...
// set files with upload()
$form['formtype[filename]'][0]->upload($uploadedFile1);
$form['formtype[filename]'][1]->upload($uploadedFile2);
...
//or with submit values
$crawler->submit($form, [
...
'formtype[filename]' => [$uploadedFile1, $uploadedFile2]
]);

Related

Trying to add a logic hook to suiteCRM when creating or updating a task

This is my first try into coding for sugarCRM / suiteCRM.
I should say I've been coding for Wordpress for nearly 10 years now, but I'm completely lost now I'm starting to dig into suiteCRM.
I've read that you can add a logic hook to modify the data after saving it to the database, but I don't know where to start...
Imagine I create a task for today, july 7th, related to a client I use to visit every 2 months, so there's a field in Accounts named "Visiting frequency". I'd like to add a future date (july 7th + 60 days = september 7th aprox) into the task's "Future Visiting Date" field, so I can use it to create that particular future task via Workflow.
What I'm trying to do is to calculate a field in tasks (Future visiting date), that equals to the amount of days on the accounts module's field (Visiting frequency) added to the task's own Date field.
I've been able to make it work, using the following layout:
Inside \custom\modules\Tasks\logic_hooks.php
<?php
$hook_version = 1;
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(
1, //Processing index. For sorting the array.
'future_task_date_on_task_creation', //Label. A string value to identify the hook.
'custom/modules/Tasks/future_visit_date.php', //The PHP file where your class is located.
'before_save_class', //The class the method is in.
'future_visit_date' //The method to call.
);
?>
Inside \custom\modules\Tasks\future_visit_date.php
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class before_save_class {
function future_visit_date($bean, $event, $arguments) {
$bean->rhun_fecha_sig_c = date("Y-m-d H:i:s", $date);
}
}
?>
With this setup, the Future Visiting Date gets filled with the calculated date.
I've also read that this setup is not advised, and that I should use the Extension Framework and put the first file in this path:
/custom/Extension/modules/Tasks/Ext/LogicHooks/<file>.php
But I can't make it work.
Do I have to create the LogicHooks folder if it's not there?
Which filename should I assign to this file?
Do I have to change something else inside the code?
Yes, create the LogicHooks directory if it doesn't exist. The PHP file can be called anything you like.
/custom/Extension/modules/Tasks/Ext/LogicHooks/MyLogicHookFile.php
Define your logic hooks in this file as before.
<?php
$hook_version = 1;
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(
1, //Processing index. For sorting the array.
'future_task_date_on_task_creation', //Label. A string value to identify the hook.
'custom/modules/Tasks/future_visit_date.php', //The PHP file where your class is located.
'before_save_class', //The class the method is in.
'future_visit_date' //The method to call.
);
Then run a repair and rebuild from the Admin panel.
The main advantage to using the Extension framework is that it allows multiple developers to add components to a Sugar instance without worrying about overwriting existing code.
More info can be found about it in the Developer Guide

Check for Valid Image using getFilesAsync()

Using WinJS, while looping through a directory, how to retrieve only images in that particular directory and ignoring any other file extension, including the DoubleDots .. and the SingleDot . etc?
Something like:
var dir = Windows.Storage.KnownFolders.picturesLibrary;
dir.getFilesAsync().done(function (filesFound) {
for(var i=0; i < filesFound.length; i++){}
if(filesFound[i] IS_REALLY_AN_IMAGE_(jpeg,jpg,png,gif Only)){
//Retrieve it now!
}else{
//Escape it.
}
}})
Instead of trying to process pathnames, it will work much better to use a file query, which lets the file system do the search/filtering for you. A query also allows you to listen for the query's contentschanged event if you want to dynamically track the folder contents rather than explicitly enumerating again.
A query is created via StorageFolder.createFileQuery, createFolderQuery, or other variants. In your particular case, where you want to filter by file types, you can use createFileQueryWithOptions. This function takes a QueryOptions object which you can initialize with an array of file types. For example:
var picturesLibrary = Windows.Storage.KnownFolders.picturesLibrary;
var options = new Windows.Storage.Search.QueryOptions(
Windows.Storage.Search.CommonFileQuery.orderByName, [".jpg", ".jpeg", ".png", ".gif"]);
//Could also use orderByDate instead of orderByName
if (picturesLibrary.areQueryOptionsSupported(options)) {
var query = picturesLibrary.createFileQueryWithOptions(options);
showResults(query.getFilesAsync());
}
where showResults is some function that takes the promise from query.getFilesAsync and iterates as needed.
I go into this subject at length in Chapter 11 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, in the section "Folders and Folder Queries". Also refer to the Programmatic file search sample, as I do in the book.
When you want to display the image files, be sure to use thumbnails instead of loading the whole image (images are typically much larger than a display). That is, for each StorageFile, call its getThumbnailAsync or getScaledImageAsThumbnailAsync method. Pass the resulting thumbnail (blob) to URL.createObjectURL which returns a URL you can assign to an img.src attribute. Or you can use a WinJS.UI.ListView control, but that's another topic altogether (see Chapter 7 of my book).

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

How to use form validation with the file uploader to make sure a file is uploaded

Can anyone suggest how using the form validation rules I can say the following:-
If no file is uploaded - then create a rule to say 'no file uploaded' using the form validator library.
I am using CodeIgniter 2.
For instance - it is simple to validate on a text input field using the following, but I cannot understand how this is done with upload (that uses the $_FILES array rather than $_POST)
eg.
$this->form_validation->set_rules('title', 'Title', 'required'); // input field named 'title' is required
CodeIgniter's File Uploading class handles its own validation - no need to use the Form Validation class.
Per the documentation,
$this->upload->display_errors()
Retrieves any error messages if the do_upload() function returned
false. The function does not echo automatically, it returns the data
so you can assign it however you need.
In your example above, if the file input is left empty, $this->upload->display_errors() will return the following:
You did not select a file to upload.
So, set your preferences (see the "Setting Preferences" section of the documentation for exactly what is available):
// The following are just examples from the documentation...
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// ... other preferences as necessary
If any of the above fail during the attempted upload, $this->upload->display_errors() will retrieve the appropriate error message. Simply pass it to your view to display the error(s).
Hope that helps.

Zend Framework / Form Element is rendering as a text box rather than a dropdown box

I have the following in a config.ini file: (Zend_Form_Element)
site_status.name = "site_status"
site_status.type = "select"
site_status.label = "Status"
site_status.options.multiOptions.active.key = "Active"
site_status.options.multiOptions.active.value = "Active"
site_status.options.multiOptions.active.key = "Inactive"
site_status.options.multiOptions.active.value = "Inactive"
As you can see this is supposed to be a dropdown (select) box, however it is being rendered as a standard text box. What am I doing wrong?
--> Edit
Rather than tying the elements to a form, I am trying to tie them to a database: In my code it would look something like this:
[{tablename}] // the table name would represent a section in the ini
{column}.name = "{column_name/form_field_id}";
{column}.type = "{form_element_type}"
{column}.label = "{form_element_label}"
...
From there I would pull in the database table(s) that the form would represent data for (one or more tables as necessary). As far as the reasoning for this approach is that (down the road), I want to define (either by ini or some other storage method), a configuration file that would be a list of fields/elements that belong to a specific form (that a non-programmer type could easily edit), that the 'generic' form class would read, pull in the element info, and create the form on the fly.
I do realize however this poses another problem which I haven't yet figured out, and that is how to use table lookups for select elements (without coding the database retrieval of the lookup into the form, so that a non-user could easily just define it without any programming, purely configuration, but that is a whole other topic not part of my question here. (and I think I have viable ideas/solutions to that part of the problem anyhow) -- extra config entries and a generic routine pretty much.
I hope that clarifies my thought process and reason why I am doing it the way I am in the example above.
I have not yet played with using a Zend_Config to construct an instance of Zend_Form.
But a look at the code suggests that Zend_Form::addElement() doesn't directly take a Zend_Config instance as a param. Rather, it looks like you need pass your Zend_Config instance to the form constructor. It also seems that the config format needs to be a little deeper in order to map config keys to setXXX() calls.
In path/to/config/myForm.ini:
[myForm]
myForm.elements.site_status.name = "site_status"
myForm.elements.site_status.type = "select"
myForm.elements.site_status.label = "Status"
myForm.elements.site_status.options.multiOptions.active.key = "Active"
myForm.elements.site_status.options.multiOptions.active.value = "Active"
myForm.elements.site_status.options.multiOptions.inactive.key = "Inactive"
myForm.elements.site_status.options.multiOptions.inactive.value = "Inactive"
Then instantiating:
$formConfig = new Zend_Config_Ini('path/to/config/myForm.ini', 'myForm');
$form = new Zend_Form($formConfig);
Not tested, but looking at this example:
Using Zend_Form with Zend_Config - Andrew Vayanis
it feels like it should go something like the above.
Update
In view of the comments/feedback from #Aaron, two more approaches.
We could extend Zend_Form, implementing a method called something like addElementByConfig in which we would pass the shallow Zend_Config instance that describes the element itself. In fact, we could even just override addElement(), taking a recursive approach: if the first param is an instance of Zend_Config, then call addElement() using the component data.
If the atomicity and re-usability are the primary benefits we seek in using Zend_Config to describe an element, then perhaps we just make a custom element extending Zend_Form_Element. Then we could use these elements in any forms we wish.