zf2 how to upload files, more than 1 file - php

I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.

I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.

I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}

Related

Invalid parameter Facebook video ad creative in Facebook Marketing API

I am getting the same error while creating Ad Creative via Facebook Marketing API. I followed their guide but doesn't work. Facebook video ad creative reference
$config = Config::get('facebook');
$data['account_id'] = 'act_'.$config['ad_account_id'];
$data['page_id'] = $config['page_id'];
// Init facebook
$api = Api::init($config['app_id'], $config['app_secret'], $config['access_token']);
// Create product catalog
$product_catalog = new ProductCatalog(null, $config['business_id']);
$product_catalog->setData(array(
ProductCatalogFields::NAME => "Catalog",
));
$product_catalog->create();
$product_catalog_id = $product_catalog->id;
// Setup Feed
$product_feed = new ProductFeed(null, $product_catalog_id);
$product_feed->setData(array(
ProductFeedFields::NAME => 'Campaign Feed',
ProductFeedFields::SCHEDULE => array(
ProductFeedScheduleFields::INTERVAL => 'DAILY',
ProductFeedScheduleFields::URL => 'http://example.com/facebook/dpa_product_catalog_sample_feed.csv',
ProductFeedScheduleFields::HOUR => 22,
),
));
$product_feed = $product_feed->create();
// Create Product Set
$product_set = new ProductSet(null, $product_catalog_id);
$product_set->setData(array(
ProductFeedFields::NAME => 'All Product',
));
$product_set->create();
$data['product_set_id'] = $product_set->id;
$video = new Advideo(null, $data['account_id']);
$video->{AdVideoFields::SOURCE} = public_path().'/facebook/video-demo.mp4';
$video->create();
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_URL => 'http://example.com/facebook/resize-image.jpg',
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $data['page_id'],
AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
));
Above these code working and return response but when I call ad creative, the API return "Invalid parameter"
$creative = new AdCreative(null, $data['account_id']);
$creative->setData(array(
AdCreativeFields::NAME => 'Video Ad Template Creative Sample',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
AdCreativeFields::PRODUCT_SET_ID => $data['product_set_id'],
));
$creative->create();
Might be your issue is in creating AdCreativeVideoData.
search for line
AdCreativeVideoDataFields::IMAGE_URL => public_path().'/facebook/resize-image.jpg',
Here IMAGE_URL requires url path like http://example.com/myimage.jpg. You are giving directory path that might cause problem.
If your image is not directly accessible from URL then you should create IMAGE_HASH. For this see below.
try {
$image = new AdImage(null, $data['account_id']);
$image->{AdImageFields::FILENAME} = public_path().'/facebook/resize-image.jpg';
$image->create();
// Image_hash = $image->hash
} catch (Exception $e) {
echo 'Error message: ' . $e->getMessage() . "\n" . "<br/>";
echo 'Error Code: ' . $e->getCode() . "<br/>";
}
And replace IMAGE_URL to IMAGE_HASH in your AdCreativeVideoData like this
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_HASH => $image->hash,
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));

php array page system, not working

So I'm working on setting up my first "fancy" page system, and I have run into a problem. I use the code seen below, and it loads the "profile" page without any problems, and the default page works fine too. However the other two pages does not show at all, and I can't seem to request them in the URL eighter. All the files are there tho. Any help here will be much appreciated! :)
if(isset($_SESSION['user_id'])){
require('user.php');
$player = new user($_SESSION['user_id'], $database);
$default_page = 'profile';
$pages = array(
'profile' => array(
'name' => 'Profile',
'file' => 'profile.php',
'function' => 'profile',
),
'create_monster' => array(
'name' => 'Create Monster',
'file' => 'monsterPages.php',
'function' => 'createMonster',
),
'create_attack' => array(
'name' => 'Create Attack',
'file' => 'attackPages.php',
'function' => 'createAttack',
),
);
if(!empty($_GET['page'])){
$page = strtolower(trim($_GET['page']));
if(isset($pages[$page])){
require($pages[$page]['file']);
echo "<p class='pageTitle'>" . $pages[$page]['name'] . "</p>";
$pages[$page]['function']();
}
else{
require($pages[$default_page]['file']);
echo "<p class='pageTitle'>" . $pages[$default_page]['name'] . "</p>";
$pages[$default_page]['function']();
}
}
else{
require($pages[$default_page]['file']);
echo "<p class='pageTitle'>" . $pages[$default_page]['name'] . "</p>";
$pages[$default_page]['function']();
}
}
You've got some redundancy in your code. You could abbreviate it.
$page = isset($_GET['page']) ? $_GET['page'] : $default_page;
// You should check that the page exists here.
require($pages[$page]['file']);
echo "<p class='pageTitle'>" . $pages[$page]['name'] . "</p>";
$pages[$page]['function']();
I suggest you place the page loading code in a function. I've created a simple class here:
<?php
$pages = array(
'profile' => array(
'name' => 'Profile',
'file' => 'profile.php',
'function' => 'profile',
),
'create_monster' => array(
'name' => 'Create Monster',
'file' => 'monsterPages.php',
'function' => 'createMonster',
),
'create_attack' => array(
'name' => 'Create Attack',
'file' => 'attackPages.php',
'function' => 'createAttack',
),
);
class PageLoader
{
public $pages;
public $base_path;
public function __construct($pages, $base_path)
{
$this->pages = $pages;
$this->base_path = $base_path;
}
public function run($name) {
if(! isset($this->pages[$name])) {
throw new Exception('Page not found');
}
$path = $this->base_path . DIRECTORY_SEPARATOR . $this->pages[$name]['file'];
$func = $this->pages[$name]['function'];
require_once $path;
call_user_func($func);
}
}
$page = isset($_GET['page']) ? $_GET['page'] : 'profile'; // If no page given default to profile.
$loader = new PageLoader($pages, '/tmp');
$loader->run($page);
Before you can use $_SESSION, you need to start the session:
session_start(); # this should be the very 1st line in your php
if(isset($_SESSION['user_id'])){
// ...
}
else{
require($pages[$default_page]['file']);
echo "<p class='pageTitle'>" . $pages[$default_page]['name'] . "</p>";
$pages[$default_page]['function']();
}
}
and make sure that $pages[$default_page]['function'](); sets $_SESSION['user_id']

Why do I get an error when adding a category programmatically in Prestashop?

I am trying to write a script that imports my categories from a XML into prestashop. There is one problem, the script does not add the category and stops working when it reaches ->add();
I'm trying to find the problem, but I really don't know what to do anymore.
Here is my script:
if ($cat == "") {
$category = new Category;
$category->active = 1;
$category->id_parent = 3;
$category->name[1] = $product->category_name;;
$category->link_rewrite[1] = Tools::link_rewrite($product_xml->category_name);
echo "<br />name of new category = $product->category_name <br /> <br />";
$category->add();
$G_array[] = $category->id;
$G_cat = $G_cat . "\r\n" . 'Category: ' . $category->name[1].' with the id: '.$category->id.' Created'; //adding new category to var, to be displayed at the index page.
}else{
I am using prestashop 1.6, I hope that someone can explain to me what I am doing wrong..
It works for me
$Category = new Category();
$Category->name = [(int)Configuration::get('PS_LANG_DEFAULT') => 'nome'];
$Category->link_rewrite = [(int)Configuration::get('PS_LANG_DEFAULT') => 'link_rewrite'];
$Category->description = [(int)Configuration::get('PS_LANG_DEFAULT') => 'descrizione'];
$Category->active = 1;
$Category->id_parent = 3;
$Category->add();
for update
$Category = new Category($id_category);
$Category->name = [(int)Configuration::get('PS_LANG_DEFAULT') => 'nome'];
$Category->link_rewrite = [(int)Configuration::get('PS_LANG_DEFAULT') => 'link_rewrite'];
$Category->description = [(int)Configuration::get('PS_LANG_DEFAULT') => 'descrizione'];
$Category->active = 1;
$Category->id_parent = 3;
$Category->update();
you can check if the category is valid with this function
Validate::isLoadedObject($Category) //true or false
remember prestashop checks whether the values of the changes are valid
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => true, 'size' => 128),
'link_rewrite' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isLinkRewrite', 'required' => true, 'size' => 128),
'description' => array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'),
isCatalogName, isLinkRewrite, isCleanHtml these are controls insertion
You must delete character not valid in link_rewrite. Delete punctuation marks, vowels with accents, brackets, ...
In prestashop code there is a function to convert a string to link_rewrite.
Rarely does the array starts at 1... Change it:
$category->name[0]=...
$category->link_rewrite[0]=...
PD: The best way to manipulate data in prestashop is the Rest API

How to migrate entity from XML to Drupal 7 using migrate module

I have created a class using migrate module but I am unable to migrate entities. my class codes are below please check it and tell me whats the problem with it??
<?php
class ItemOrderXMLMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('OrderFeed'));
$this->description = t('Migrate entity from XML file');
//$this->softDependencies = array('WineFileCopy');
$fields = array(
'Number' => t('Number'),
'Date' => t('Date'),
'SubTotal' => t('Sub Total'),
'Discount' => t('Discount'),
'ShippingCharges' => t('Shipping Charges'),
'ShippingChargesDiscount' => t('Shipping Charges Discount'),
'NumItems' => t('NumItems'),
'VATPercentage' => t('VAT Percentage'),
'CurrencyCode' => t('Currency Code'),
'PaymentTypeDesc' => t('Payment Type Desc'),
'OrderState' => t('Order State'),
);
$this->map = new MigrateSQLMap($this->machineName,
array(
'Number' => array(
'type' => 'varchar',
'length' => 225,
'not null' => TRUE,
)
),
MigrateDestinationEntityAPI::getKeySchema('entity_example_basic','first_example_bundle')
);
$xml_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'products_import') . '/xml/';
$items_url = $xml_folder . 'OrderFeed.xml';
$item_xpath = '/Orders/Item'; // relative to document
$item_ID_xpath = 'Number'; // relative to item_xpath and gets assembled
// into full path /producers/producer/sourceid
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_ID_xpath);
$this->source = new MigrateSourceMultiItems($items_class, $fields);
$this->destination = new MigrateDestinationEntityAPI('entity_example_basic','first_example_bundle');
$this->addFieldMapping('field_number', 'Number')
->xpath('Number');
$this->addFieldMapping('field_subtotal', 'SubTotal')
->xpath('SubTotal');
$this->addFieldMapping('field_discount', 'Discount')
->xpath('Discount');
//$this->addUnmigratedDestinations(array('weight'));
}
}
?>
When I import it I got the save error message for all entities: Creating default object from empty value File /var/www/mig/migration/sites/all/modules/migrate_extras/entity_api.inc, line 227
Try the latest or updated migrate module https://www.drupal.org/project/migrate. I think you were using old one which were having some issues to migrate entities.
Why don't you try with a feed importer (Feeds module) using XPath parser module?. It's really easy, and you can use both an uploaded file or a source URL.

symfony 1.4 file uploads and templates

I successfully saved the path of photo into mysql database.My question is,how to render correctly in templates?I tried
<td width="129" rowspan="5"><img src= "/uploads/photos<?php echo $applicant->photo?>"width="129" height="129"/></td>
Not working.
In my action, i tried
$photo = $this->form->getValue('photo');
$filename = 'photo'.sha1($photo->getOriginalName());
$extension = $photo->getExtension($photo->getOriginalExtension());
//$photo->save(sfConfig::get('sf_upload_dir').'/' . $filename . $extension);
$photo->save(sfConfig::get('sf_upload_dir') . '/'.$photo) . date('Ym') . '/' . $filename . $extension);
and in my form i tried
$this->widgetSchema['photo'] = new sfWidgetFormInputFileEditable(array(
'label' => 'Photo',
'file_src' => '/uploads/photos/'.$this->getObject()->getPhoto(),
'is_image' => true,
'edit_mode' => !$this->isNew(),
'template' => '<div class="sublabel">%file%<br />%input%<br />%delete% %delete_label%</div>',
));
$this->validatorSchema['photo'] = new sfValidatorFile(array(
'required' => false,
'path' => sfConfig::get('sf_upload_dir').'/photos',
'mime_types' => 'web_images',
));

Categories