Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add media field to custom entity #172

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions Controller/MediaRestController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

namespace Pim\Bundle\CustomEntityBundle\Controller;

use Akeneo\Component\FileStorage\PathGeneratorInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
* Media REST controller
*
* @author Simon CARRE <[email protected]>
* @package Pim\Bundle\CustomEntityBundle\Controller
*/
class MediaRestController
{
/**
* Validator interface
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed comment line

*
* @var ValidatorInterface
*/
protected $validator;

/**
* Path generator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed comment line

*
* @var PathGeneratorInterface
*/
protected $pathGenerator;

/**
* Upload directory
*
* @var string
*/
protected $uploadDir;

/**
* @param ValidatorInterface $validator
* @param PathGeneratorInterface $pathGenerator
* @param string $uploadDir
*/
public function __construct(ValidatorInterface $validator, PathGeneratorInterface $pathGenerator, $uploadDir)
{
$this->validator = $validator;
$this->pathGenerator = $pathGenerator;
$this->uploadDir = $uploadDir;
}

/**
* Post a new media and return original filename and path
*
* @param Request $request
*
* @return JsonResponse
*/
public function postAction(Request $request)
{
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $request->files->get('file');
$violations = $this->validator->validate($file);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add an example of file validation in the AcmeCustomBundle ?


if (count($violations) > 0) {
$errors = [];
foreach ($violations as $violation) {
$errors[$violation->getPropertyPath()] = [
'message' => $violation->getMessage(),
'invalid_value' => $violation->getInvalidValue(),
];
}

return new JsonResponse($errors, 400);
}
$pathData = $this->pathGenerator->generate($file);

try {
$movedFile = $file->move(
$this->uploadDir . DIRECTORY_SEPARATOR . $pathData['path'] . DIRECTORY_SEPARATOR . $pathData['uuid'],
$file->getClientOriginalName()
);
} catch (FileException $e) {
return new JsonResponse("Unable to create target-directory, or moving file.", 400);
}
$filePath = $movedFile->getPathname();
$filePathWithoutDirectory = str_replace($this->uploadDir . '/', '', $filePath);

return new JsonResponse(
[
'originalFilename' => $file->getClientOriginalName(),
'filePath' => $filePath,
'shortFilePath' => $filePathWithoutDirectory
]
);
}
}
14 changes: 11 additions & 3 deletions Resources/config/controllers.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
parameters:
pim_ui.controller.ajax_option.class: Pim\Bundle\CustomEntityBundle\Controller\AjaxOptionController
pimee_ui.controller.ajax_option.class: Pim\Bundle\CustomEntityBundle\Controller\EnterpriseAjaxOptionController
pim_custom_entity.rest_controller.class: Pim\Bundle\CustomEntityBundle\Controller\RestController
pim_ui.controller.ajax_option.class: Pim\Bundle\CustomEntityBundle\Controller\AjaxOptionController
pimee_ui.controller.ajax_option.class: Pim\Bundle\CustomEntityBundle\Controller\EnterpriseAjaxOptionController
pim_custom_entity.rest_controller.class: Pim\Bundle\CustomEntityBundle\Controller\RestController
pim_custom_entity.media_rest_controller.class: Pim\Bundle\CustomEntityBundle\Controller\MediaRestController

services:
pim_custom_entity.controller:
Expand All @@ -16,3 +17,10 @@ services:
scope: request
arguments:
- '@pim_custom_entity.configuration.registry'

pim_custom_entity.media_rest_controller:
class: '%pim_custom_entity.media_rest_controller.class%'
arguments:
- '@validator'
- '@akeneo_file_storage.file_storage.path_generator'
- '%catalog_storage_dir%'
2 changes: 2 additions & 0 deletions Resources/config/requirejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ config:
custom_entity/form/common/save-form: pimcustomentity/js/form/common/save-form
custom_entity/form/common/delete: pimcustomentity/js/form/common/delete
custom_entity/form/common/label: pimcustomentity/js/form/common/label
custom_entity/form/common/fields/media: pimcustomentity/js/form/common/fields/media
custom_entity/controller/list: pimcustomentity/js/controller/custom_entity-list
custom_entity/controller/edit: pimcustomentity/js/controller/custom_entity-edit
custom_entity/fetcher: pimcustomentity/js/fetcher/custom_entity-fetcher
custom_entity/remover/reference-data: pimcustomentity/js/remover/reference-data-remover
custom_entity/template/form/common/fields/media: pimcustomentity/templates/form/common/fields/media.html

config:
pim/fetcher-registry:
Expand Down
5 changes: 5 additions & 0 deletions Resources/config/routing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,8 @@ pim_customentity_history:
actionType: history
requirements:
id: \d+

pim_customentity_media_rest_post:
path: '/rest/customentity_media'
defaults: { _controller: pim_custom_entity.media_rest_controller.class:postAction }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simoncarre here should be the name of the service pim_custom_entity.media_rest_controller , not the class. I got issue here

methods: [POST]
96 changes: 96 additions & 0 deletions Resources/public/js/form/common/fields/media.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
'use strict';

define([
'jquery',
'underscore',
'pim/form/common/fields/field',
'pim/media-url-generator',
'routing',
'custom_entity/template/form/common/fields/media'
],
function ($,
_,
BaseField,
MediaUrlGenerator,
Routing,
template) {
return BaseField.extend({
template: _.template(template),

events: {
'change input[type="file"]': function (event) {
this.errors = [];
this.updateModel(this.getFieldValue(event.target));
this.render();
},
'click .clear-field': 'clearField'
},

/**
* {@inheritdoc}
*/
renderInput: function (templateContext) {
var modelValue = this.getModelValue();
var originalFilename = null;
var filePath = null;
var shortFilePath = null;
if (modelValue != null) {
var modelValueAsJson = JSON.parse(modelValue);
originalFilename = modelValueAsJson.originalFilename;
filePath = modelValueAsJson.filePath;
shortFilePath = modelValueAsJson.shortFilePath;
}

return this.template(_.extend(templateContext, {
value: modelValue,
originalFilename: originalFilename,
filePath: filePath,
shortFilePath: shortFilePath,
mediaUrlGenerator: MediaUrlGenerator
}));
},

/**
* {@inheritdoc}
*/
getFieldValue: function (field) {
var self = this;
var fieldValue = null;

var input = this.$(field).get(0);
if (!input || 0 === input.files.length) {
return null;
}
var formData = new FormData();
formData.append('file', input.files[0]);

$.ajax({
url: Routing.generate('pim_customentity_media_rest_post'),
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
async: false
}).done(function (data) {
fieldValue = JSON.stringify(data);
}).fail(function () {
self.errors.push({
code: self.fieldName,
message: _.__('pim_enrich.entity.product.error.upload'),
global: false
});
});

return fieldValue;
},

/**
* Clear media field
*/
clearField: function () {
this.updateModel(null);
this.render();
}
});
});
22 changes: 22 additions & 0 deletions Resources/public/templates/form/common/fields/media.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<div class="AknMediaField <%- filePath ? 'has-file' : '' %>" >
<% if (!filePath) { %>
<input class="AknMediaField-fileUploaderInput" id="upload_field_<%- fieldId %>" type="file"/>
<div class="AknMediaField-emptyContainer">
<span title="upload icon" class="AknMediaField-uploadIcon"/>
<span><%- _.__('pim_enrich.entity.product.media.upload')%></span>
</div>
<% } else { %>
<div class="AknMediaField-preview preview">
<% mediaThumbnailUrl = mediaUrlGenerator.getMediaShowUrl(filePath, 'thumbnail_small') %>
<% mediaDownloadUrl = mediaUrlGenerator.getMediaDownloadUrl(shortFilePath) %>
<div class="AknMediaField-thumb file"><img src="<%- mediaThumbnailUrl %>" class="AknMediaField-image"/></div>
<div class="AknMediaField-info info">
<div class="filename" title="<%- originalFilename %>"><%- originalFilename %></div>
<div class="AknButtonList AknButtonList--centered actions">
<a href="<%- mediaDownloadUrl %>" class="AknButtonList-item AknIconButton AknIconButton--grey download-file" download><i class="icon icon-cloud-download"></i></a>
<span class="AknButtonList-item AknIconButton AknIconButton--grey clear-field"><i class="icon icon-trash"></i></span>
</div>
</div>
</div>
<% } %>
</div>
25 changes: 25 additions & 0 deletions docs/examples/CustomBundle/Entity/Brand.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,36 @@
*/
class Brand extends AbstractCustomEntity
{
/**
* @var string
*/
protected $visual;

/**
* @var Fabric
*/
protected $fabric;

/**
* @return string
*/
public function getVisual()
{
return $this->visual;
}

/**
* @param string $visual
*
* @return Brand
*/
public function setVisual($visual)
{
$this->visual = $visual;

return $this;
}

/**
* @param Fabric|null $fabric
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ public function __construct(FabricNormalizer $fabricNormalizer)
public function normalize($entity, $format = null, array $context = [])
{
$normalizedBrand = [
'id' => $entity->getId(),
'code' => $entity->getCode(),
'id' => $entity->getId(),
'code' => $entity->getCode(),
'visual' => $entity->getVisual(),
];

$fabric = $entity->getFabric();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Acme\Bundle\CustomBundle\Entity\Brand:
type: string
length: 255
unique: true
visual:
type: text
nullable: true
sortOrder:
type: integer
manyToOne:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,20 @@ extensions:
required: true
readOnly: true

pim-brand-edit-form-properties-visual:
module: custom_entity/form/common/fields/media
parent: pim-brand-edit-form-properties-common
targetZone: content
position: 100
config:
fieldName: visual
label: acme_custom.brand.field.label.visual

pim-brand-edit-form-properties-fabric:
module: custom_entity/field/custom-entity-select
parent: pim-brand-edit-form-properties-common
targetZone: content
position: 100
position: 110
config:
fieldName: fabric
choiceNameField: code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ acme_custom:
selected: brands selected
field.label:
code: Code
visual: Visual
form:
tab.properties.section.common: Common
tab.properties.section.label_translations: Labels
Expand Down