How to get "media id" from media "image name/path" drupal 8 - drupal

I have created image field on media content type and then created media reference field in article node.
I want to retrieve the media id from image path.

This is how you can get the media id from filename
// Load file by filename
// array.
$file = $this->entityTypeManager
->getStorage('file')
->loadByProperties(['filename' => $file_name]);
// Get First file (make a loop if you get many files)
$fileId = array_shift($file)->fid->value;
// Array of Medias witch contains your file.
$this->entityTypeManager
->getStorage('media')
->loadByProperties(['field_media_image' => $fileId]);

Related

How can I set sys_file_metadata when creating a FAL Object in TYPO3 Extbase

I'am searching for solution for adding metadata to a sys_file fileObject in TYPO3 Extbase.
I'am adding a file to the storage in this way:
$resourceFactory = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class);
$storage = $resourceFactory->getDefaultStorage();
$fileObject = $storage->addFile(
$temporaryFile,
$storage->getFolder('some-folder/'),
$newfilename
);
And can manipulate a bunch of properties with updateProperties() like so:
$fileObject->updateProperties(array(
'name' => 'foo',
));
But how can I set further metadata properties in sys_file_metadata like title or alternative texts when I create the file? Is there a documentation out there, how to do this. I have only found this:
https://docs.typo3.org/m/typo3/reference-coreapi/10.4/en-us/ApiOverview/Fal/UsingFal/ExamplesFileFolder.html#
But this documentation contains no hints about metadata handling.
I solved it using the MetaDataAspect which is available on a File object.
$metaData = $fileObject->getMetaData();
$metaData->offsetSet('title', 'Image title');
$metaData->save();
Use with care, as the save method is marked as #internal. Also checkout this changelog document, which is the only document I could found.

Populate Image & Image List Fields with Bolt CMS Programatically

I am attempting to create entries programaticaly in Bolt 4. I have managed to create basic text entries fine which covers the majority of fields I need to fill in however unsure how to go about image and image list types.
$content->setFieldValue('name', 'Test Name');
Works fine for most fields as stated but images field types looks like below in database and am unsure what the "Bolt / Symfony / Doctrine" way of generating below is:
{"media":11,"filename":"entity\/year\/month\/image.jpg","alt":"","0":""}
Which looks like some JSON formatted to contain a media ID, file path and an alt attribute. I'm guessing image lists are similar but with multiple of above but hoping there is a function I can use to generate this output as unsure how I would grab media ID etc.
Am assuming I may need to upload a file temporarily from an external URL and provide this to some function however cannot find any examples. Any help would be much appreciated.
Not quite sure on this but will answer anyway as it works and may help someone else, but would be good to clear some of the bits up.
Example of an Image:
//not sure what goes in media here but blank seemed to not work here but a 7 did as looked at example in database however worried this is wrong and should be an Id
$image = array('media' => '7', 'filename' => $filename, 'alt' => $image['Alt'], '0' => '');
$imageJSON = json_encode($image);
$content->setFieldValue('image', $image);
Example of an Image List:
$images = array();
foreach ($images as $image) {
$ImageId = $image['id'];
//images may be already on system but I had to download them here
if ($fileName = $this->downloadImage($propertyFile->{'url'}->__toString(), $ImageId)) {
//not sure what goes in media here but seemed to work blank for imagelist type and unsure what the 0 is on the end either
$image[] = array('media' => '', 'filename' => $filename, 'alt' => $image['Alt'], '0' => ''); }
}
$imageJSON = json_encode($image);
$content->setFieldValue('gallery', $image);

SilverStripe edit gridfield success message on save

What's the easiest way to edit the default success message when saving an item in GridField edit view?
The message seems to be in a variable in class GridFieldDetailForm within method doSave.
$message = _t(
'GridFieldDetailForm.Saved',
'Saved {name} {link}',
array(
'name' => $this->record->i18n_singular_name(),
'link' => $link
)
);
Since the message uses the _t() function it will attempt to fetch the value defined in the lang file corresponding to the current user's locale. The default string defined in the function is just a fallback for when no translation could be found within the lang files.
To change the message you can update your site's yml lang file located in mysite/lang/{LANGUAGE_CODE}.yml
For english this would be:
# mysite/lang/en.yml
# remember to flush after editing me :-)
en:
GridFieldDetailForm:
Saved: 'My custom message using {name} and here is a link to the object: {link}'
https://docs.silverstripe.org/en/3.4/developer_guides/i18n/
Something like this should work for specific implementations
$form = $gridField->getConfig()->getComponentByType('GridFieldDetailForm');
$form->setItemEditFormCallback(function($form, $itemRequest)
{
// Replace save action with custom method in here
});
For more general implementations, you'll likely want to extend GridFieldDetailForm and override doSave, then replace the GridFieldDetailForm component with your custom class.

Module multi image upload

I'm using the following module for uploading multiple images:
https://github.com/bummzack/sortablefile
I use the has-many relationship.
class PortfolioPage extends Page
{
private static $has_many = array(
'Images' => 'PortfolioImage'
);
class PortfolioImage extends Image
{
private static $has_one = array(
'PortfolioPage' => 'PortfolioPage'
);
}
The problem is that when uploading multiple images with the same file name it gives me the following error: File with the same name already exists .
How can I avoid this such that it will be possible to upload multiple images when they have the same filename?
Thank you
SortableUploadField is extending the UploadField, try adding setOverwriteWarning to False in your getCMSFields section. Check the code below:
$uploadField = new SortableUploadField('Images', 'Upload Images');
$uploadField->setOverwriteWarning(FALSE);
$fields->addFieldToTab("Root.Main", $uploadField);
Take note, this only prevents the error and rename the duplicate file name. Example: if you upload same file name like file.jpg, the second file.jpg will be renamed to 2.jpg, 3.jpg, etc.
Actually this error is "natural" behavior, it's impossible to store multiple files with identical names in one directory.
Please read discussion on GitHub for more information.

Drupal7 copy filefield to another node at submit

I have a content type that has unlimited filefield fields in addition to other fields. At node save/submit I would like to create an additional node for each file in the field, and assign that filefield to it. I'm fine with the nodeapi hooks and progmatically creating the node, but I can't access the content of the filefield from the node. When I print the filefield contents from within hook_node_insert I get:
...
(
[fid] => 38
[display] => 1
[description] =>
[upload_button] => Upload
[remove_button] => Remove
[upload] =>
)
....
Not the formatted and proceed field I would normally see. My suspicion is that I can access this somehow from the form and do a form submit after modifying it, but I'm not sure how to do this and it may not the best way. Let me know if you have any tips on this, greatly appreciated.
since we have [fid] populated we can use file_load($fid) to load the file object. Then you can cast this file object to array and then attach it to the file field of newly created node.
Loop through the array and for each $fid you encounter..
$file = file_load($fid);
$new_node= new StdClass();
$new_node->type = 'image';
$new_node->language = LANGUAGE_NONE;
node_object_prepare($new_node);
// add additional data about new node.
$new_node->field_custom_files[LANGUAGE_NONE][] = array($file);
node_submit($new_node);
node_save($new_node);
I have not tested this, but do let me know if you face any issues.

Resources