Put/Get UploadField submitted image from custom Form -> Silverstripe 3.1 - image

I have a small problem programming with the use of UploadField . I have created pages to make a light CMS on the FrontEnd. But I don't know how retrieve this image to the page «Update».
There is the code from the page «Create» :
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
There is the code I tried to get working for the page «Update»
$evenID = Session::get('evenementID');
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
..
$SavedImage = File::get()->byID($evenement->ImageEvenementID)
$uploadField = new UploadField( 'ImageEvenement', 'Image', $SavedImage );
How can I retrieve the submitted image to $SavedImage ? My idea to get the ID from File don't work.
Another method :
$SavedImage = $evenement->ImageEvenement();
If I dump data from $SavedImage I'm viewing :
Image Object
(
[destroyed] =>
[model:protected] => DataModel Object
(
[customDataLists:protected] => Array
(
)
)
[record:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[changed:DataObject:private] => Array
(
)
[original:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[brokenOnDelete:protected] =>
[brokenOnWrite:protected] =>
[components:protected] =>
[unsavedRelations:protected] =>
[sourceQueryParams:protected] =>
[failover:protected] =>
[customisedObject:protected] =>
[objCache:ViewableData:private] => Array
(
)
[class] => Image
[extension_instances:protected] => Array
(
[BetterButtonDataObject] => BetterButtonDataObject Object
(
[owner:protected] =>
[ownerBaseClass:protected] => DataObject
[ownerRefs:Extension:private] => 0
[class] => BetterButtonDataObject
)
[SiteTreeFileExtension] => SiteTreeFileExtension Object
(
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => SiteTreeFileExtension
)
[Hierarchy] => Hierarchy Object
(
[markedNodes:protected] =>
[markingFilter:protected] =>
[_cache_numChildren:protected] =>
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => Hierarchy
)
)
[beforeExtendCallbacks:protected] => Array
(
)
[afterExtendCallbacks:protected] => Array
(
)
)
Any idea?
class PageCalendrierEvenement extends Page {
private static $db = array(
"Titre" => "Varchar(50)",
"DateDepart" => "Date",
"DateFin" => "Date",
);
private static $has_one = array(
'Creator' => 'Member',
'ImageEvenement' => 'Image',
);
..
}
Thank you!

has one relations need the "ID" suffix in the name of the relation (as it's saved to db...), e.g.
$uploadField = new UploadField( 'ImageEvenementID', 'Image', $SavedImage );
then it should save automatically.
OR, what i do for a single relation:
$imageField = UploadField::create('ImageEvenement', 'Image');
$imageField->setAllowedFileCategories('image');
$imageField->setAllowedMaxFileNumber(1);
hope that helps.

My code works fine but are not clean and not using SilverStripe function classes. The reason for non working saving images to dataobject, is because that I have not use :
$form->saveInto($evenement)
I would like to thank you Wmk for give me the get method to fill form with values on another post :
$form->loadDataForm($evenement)
Finaly, all works fine now!

Finaly after long time brain searching, I have found the trick! The command to use with UploadField is setValue($value) with fileIDs include with it. My final code is :
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
...
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
$data['ImageID'] = $evenement->ImageEvenement()->ID;
$fileIDs[]=$data['ImageID'];
$uploadField->setValue(array('Files' => $fileIDs));
Thats it!

Related

How can I check that file returned by laravel-medialibrary getUrl method really exists?

In laravel 8 app I use spatie/laravel-medialibrary 9
and how can I check that file returned by getUrl really exists under storage in code :
foreach (Auth::user()->getMedia('avatar') as $mediaImage) {
\Log::info( varDump($mediaImage, ' -1 $mediaImage::') );
return $mediaImage->getUrl();
}
?
$mediaImage var has data like:
Array
(
[id] => 11
[model_type] => App\Models\User
[model_id] => 1
[uuid] => 2fb4fa16-cbdc-4902-bdf5-d7e6d738d91f
[collection_name] => avatar
[name] => b22de6791bca17184093c285e1c4b4b5
[file_name] => avatar_111.jpg
[mime_type] => image/jpg
[disk] => public
[conversions_disk] => public
[size] => 14305
[manipulations] => Array
(
)
[custom_properties] => Array
(
)
[generated_conversions] => Array
(
)
[responsive_images] => Array
(
)
[order_column] => 1
[created_at] => 2021-12-30T14:08:11.000000Z
[updated_at] => 2021-12-30T14:08:11.000000Z
[original_url] => http://127.0.0.1:8000/storage/Photos/11/avatar_111.jpg
[preview_url] =>
)
Looks like nothing about file under storage...
Thanks!
Method :
File::exists($mediaImage->getPath());
helped me!

Reverse output from simplexml

Cannot reverse output, tried with array_reverse and usort.
I'm trying to import products from an XML to Magento with magmi datapump, works fine but I need the output in reverse order for Magento to link simple products with configurable products,
Any ideas?
$xml = simplexml_load_file("23.xml") or die("Error: Cannot create object");
foreach($xml->wapiitems->record as $book) {
$item = $book->fields->itemno;
if (strlen($item) <= 6) {
$type = "configurable";
$ca = "color,size";}
else {
$type = "simple";
$ca = "";}
$newProductData = array(
'sku' => (string)$book->fields->itemno, // name
'type' => (string)$type, // sku
'color' => (string)$book->subtables->descriptions->record->fields->variant1name, // special price
'size' => (string)$book->subtables->descriptions->record->fields->variant3name, // price
'attribute_set' => 'Default', // attribute_set
'store' => 'admin',
'name' => (string)$book->subtables->descriptions->record->fields->description, // full description
'configurable_attributes' => (string)$ca // short description
);
//$dp->ingest($newProductData);
echo "</br>";
print_r ($newProductData);
$newProductData=null; //clear memory
unset($newProductData); //clear memory
}
unset($xml);
$dp->endImportSession(); // end import
My output is:
Array ( [sku] => 90349 [type] => configurable [color] => [size] => [attribute_set] => Default [store] => admin [name] => [configurable_attributes] => color,size )
Array ( [sku] => 903490101004 [type] => simple [color] => Red [size] => 4 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101005 [type] => simple [color] => Black [size] => 5 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101006 [type] => simple [color] => Black [size] => 6 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
But I need this:
Array ( [sku] => 903490101006 [type] => simple [color] => Black [size] => 6 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101005 [type] => simple [color] => Black [size] => 5 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101004 [type] => simple [color] => Red [size] => 4 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 90349 [type] => configurable [color] => [size] => [attribute_set] => Default [store] => admin [name] => [configurable_attributes] => color,size )
Not sure how Magmi Datapump is linking the simple and configurable products based on your example, but assuming that all that is required for your problem is that configurable products get imported after the simple products, you could do something like this:
Create an intermediate array of product records after pulling them out of XML by changing $newProductData = array(...) to $newProductData[] = array(...)
Now use something like this to sort your intermediate array by product type:
usort($newProductData, function($a, $b)
{
if ($a['type'] == 'configurable' && $b['type'] == 'simple') {
return 1;
} else if ($a['type'] == 'simple' && $b['type'] == 'configurable') {
return -1;
} else {
return strnatcmp($a['sku'], $b['sku']);
}
});
Finally, iterate over the sorted array and complete the import:
foreach ($newProductData as $data) {
$dp->ingest($data);
}

CodeIgniter, variable declaration

I have a problem with undefined variable. In view/somefolder/somefile.php they echo some variabla (<?php echo $news;?> ) . I tried everything to find where this variable is defined (Find in Path at PHPStorm), but without result. When I put print_r($GLOBALS) to test, I got
[_ci_cached_vars:protected] => Array
(
[unread] => 0
[unans] => 0
[ques_unread] => 0
[is_loged] =>
[level] =>
[avatar] => media/img/avatar.png
[username] =>
[root_cat] => 0
[logErr] =>
[radio_list] => Array
(
)
[entitet] => 1
[current_modul] => infograda
[tree] => <ul></ul>
[category] => stdClass Object
(
[id] => 153
[title] => HRONIKA
[description] =>
[parent_id] => 0
[order] => 52
[module] => infograda
[expanded] => 0
[content_type_id] => 1
)
[module] => infograda
[active] =>
[additionHtml] =>
[news] => Array
(
[0] => stdClass Object
(
[id] => 1574
[content_id] => 1574
[module] => infograda
[order] =>
[title] => Title
[text] => <div class="uvod_holder">
in Codeigniter, a view is loaded from a controller. For example:
Controller:
// this file resides in application\controllers\mycontroller.php
class Mycontroller extends CI_Controller{
function mypage() {
$data = array('news' => 'some news');
$this->load->view('page', $data);// will load views\page.php and pass the $data array
}
}
View
<!--this file resides in application\views\page.php -->
<html>
<head></head>
<body><?= $news; ?></body>
</html>
To make this work, your URL will say http://localhost/index.php/mycontroller/mypage (if you're working locally)
Your variable is being set in the controller that loads that view.

Cakephp: How to validate array

I need to validate user thumbnail size and type when user upload their thumbnail. But I don't know how to validate array data. So please help me
p/s: I use Cakephp 2.x
my data:
Array
(
[User] => Array
(
[id] => 45
[username] => pa7264
[password] => admin
[new_password] =>
[thumbnail] => Array
(
[name] => demo.jpg
[type] => image/jpeg
[tmp_name] => D:\OpenServer\userdata\temp\phpD2FD.tmp
[error] => 0
[size] => 13582
)
)
)
You need a custom validation in a pair with getimagesize() function.
Here is a quick draft for you:
//in User.php model
public $validate = array(
'thumbnail' => array(
'imageSize' => array(
'rule' => array('check_image_size'),
'message' => 'Thumbnail size is too big!'
)
)
);
// this is custom validaion function
public function check_image_size($data)
{
$imagesize = getimagesize($data['thumbnail']['tmp_name']);
if (($imagesize[0] > 600) || ($imagesize[1] > 400)){
//here we taking request data to erase image to avoid problems in view
$request = Router::getRequest();
unset($request->data['User']['thumbnail']);
return false; //validaion failed
}
return true; //validaion passed
}

sorting and filtering not working in custom admin module

I am trying to implement an admin module in magento which has a grid in the first page and grids in the tabs while editing the grid entities.
The main grid works fine, but the grids in the tabs are not working fine.
The problem I found while I debugged the code is that, I am loading the collection in the grid with field filtering, ie I am filtering the collection with filter that is the user id. I did this because I need only data of a single user from the table. This made the entire problem, the data in the grid is coming correctly, but the filtering,sorting and searching feature inside grid is not working and returning a 404 not found error page. I tried removing the field filter I added while getting the collection, then it works fine but all the data in the table is coming which is the opposite to my requirement.
Is there any possible solution to this. Here is the way I am trying to do:
protected function _prepareCollection() {
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id', Mage::registry('merchant_data')->getId());
$this->setCollection($collection); //Set the collection
return parent::_prepareCollection();
}
Thanks in advance.
ok My problem is solved there is a mistake in my code. In the grid file the function below was wrong.
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id',Mage::registry('merchant_data')->getId(), '_current' => true));
}
The correct method was
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id'=> Mage::registry('merchant_data')->getId(), '_current' => true));
}
Filter action is dependent on your below method:
public function getGridUrl() {
return $this->getUrl('*/*/grid', array('user_id' => Mage::registry('merchant_data')->getId(),'_current'=>true));
}
now this is how you will prepare collection:
protected function _prepareCollection()
{
$regData = Mage::registry('merchant_data');
if(isset($regData))
$regData = $regData->getId();
else
$regData = $this->getRequest()->getParam('user_id');
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id',$regData);
...
When I dumped $regData I got this:
Cubet_Merchant_Model_Merchant Object
(
[_eventPrefix:protected] => core_abstract
[_eventObject:protected] => object
[_resourceName:protected] => merchant/merchant
[_resource:protected] =>
[_resourceCollectionName:protected] => merchant/merchant_collection
[_cacheTag:protected] =>
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_hasDataChanges:protected] =>
[_origData:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_idFieldName:protected] => user_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)

Resources