How to add image on push notification using brozot / Laravel-FCM ?
I'm sending notifications correctly, but I would like to know how can I send an image with the notification?
I tried this code but not working
$pushData = ['body' => $message, 'title'=>$title,'image'=>'image-url'];
$pushJsonData = json_encode($pushData);
if(count($tokens)>0)
{
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);
$notificationBuilder = new PayloadNotificationBuilder($title);
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => $pushJsonData]);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();
//return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();
//return Array (key : oldToken, value : new token - you must change the token in your database )
$downstreamResponse->tokensToModify();
//return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();
// return Array (key:token, value:errror) - in production you should remove from your database the tokens present in this array
$downstreamResponse->tokensWithError();
You need to create a custom script that herance the vendor script and add some properties on it.
Create a new path in app: app/Notifications/Message
Add a new script called CustomPayloadNotification.php
Here you need to:
Extends PayloadNotification (vendor);
Add a new variable $image;
Override __construct method, changing the parameter type to CustomPayloadNotificationBuilder. Set all the variables like is in PayloadNotification and also set the new variable $image.
Override toArray method, setting all the properties like is in PayloadNotification and also set a new property image with $image value.
Something like this:
<?php
namespace App\Notifications\Messages;
use LaravelFCM\Message\PayloadNotification;
use App\Notifications\Messages\CustomPayloadNotificationBuilder;
class CustomPayloadNotification extends PayloadNotification // Extends vendor script
{
protected $image; // New variable
/**
* CustomPayloadNotificationBuilder constructor.
*
* #param CustomPayloadNotificationBuilder $builder
*/
public function __construct(CustomPayloadNotificationBuilder $builder) // Change the type of parameter
{
$this->title = $builder->getTitle();
$this->body = $builder->getBody();
$this->icon = $builder->getIcon();
$this->sound = $builder->getSound();
$this->badge = $builder->getBadge();
$this->tag = $builder->getTag();
$this->color = $builder->getColor();
$this->clickAction = $builder->getClickAction();
$this->bodyLocationKey = $builder->getBodyLocationKey();
$this->bodyLocationArgs = $builder->getBodyLocationArgs();
$this->titleLocationKey = $builder->getTitleLocationKey();
$this->titleLocationArgs = $builder->getTitleLocationArgs();
$this->image = $builder->getImage(); // Set image
}
/**
* convert CustomPayloadNotification to array
*
* #return array
*/
function toArray()
{
$notification = [
'title' => $this->title,
'body' => $this->body,
'icon' => $this->icon,
'sound' => $this->sound,
'badge' => $this->badge,
'tag' => $this->tag,
'color' => $this->color,
'click_action' => $this->clickAction,
'body_loc_key' => $this->bodyLocationKey,
'body_loc_args' => $this->bodyLocationArgs,
'title_loc_key' => $this->titleLocationKey,
'title_loc_args' => $this->titleLocationArgs,
'image' => $this->image, // Set property image with $image value
];
// remove null values
$notification = array_filter($notification, function($value) {
return $value !== null;
});
return $notification;
}
}
Add a new script called CustomPayloadNotificationBuilder.php
Here you need to:
Extends PayloadNotificationBuild (vendor);
Add a new variable protected $image;
Create the set/get methods to $image;
Override build method, returning a new CustomPayloadNotification instead PayloadNotification.
Something like this:
<?php
namespace App\Notifications\Messages;
use LaravelFCM\Message\PayloadNotificationBuilder;
use App\Notifications\Messages\CustomPayloadNotification;
class CustomPayloadNotificationBuilder extends PayloadNotificationBuilder // Extends vendor script
{
protected $image; // New variable
/**
* Set image
*
* #param string $image
*
* #return CustomPayloadNotificationBuilder
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image.
*
* #return null|string
*/
public function getImage()
{
return $this->image;
}
/**
* Build an CustomPayloadNotification
*
* #return CustomPayloadNotification
*/
public function build()
{
return new CustomPayloadNotification($this); // Change the object returned
}
}
Reference CustomPayloadNotificationBuilder instead PayloadNotificationBuilder scripts in your code.
Use the method setImage
Your code should be something like this:
use App\Notifications\Messages\CustomPayloadNotificationBuilder; // Add the reference on the top of your code
// No changes before here [...]
$notificationBuilder = new CustomPayloadNotificationBuilder($title); // Replace here
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
$notificationBuilder->setImage("Image URL here"); // Add an image
// No changes after here [...]
you need to do some change in vendor for this
Step-1 : Go to the following url I am sharing here-
Laravel-FCM-master\Laravel-FCM-master\src\Message\PayloadNotification.php
Step-2 : here you have to add a instance variable as
protected $image;
Step - 3 find the public function __construct(PayloadNotificationBuilder $builder)
step -4 add $this->image = $builder->getImage(); in this function.
step -5 find the public function toArray()
step -6 add here 'image' => $this->image,
step -7 save and exit.
step -8 then follow this url in vendor again Laravel-FCM-master\Laravel-FCM-master\src\Message\PayloadNotificationBuilder.php:
step -9 add in above page
/**
* Indicates the image that can be displayed in the notification
* Supports an url or internal image.
*
* #param string $image
*
* #return PayloadNotificationBuilder current instance of the builder
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
step - 10 then add
/**
* Get image.
*
* #return null|string
*/
public function getImage()
{
return $this->image;
}
step - 11 that's it, now you can easily able to add a new field in your controller where your code was written asked in question.
simply modify as
$notificationBuilder = new PayloadNotificationBuilder($title);
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setImage("https://yourdoamin.com/yourdesiredimage.jpeg")->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
and send you will get exact what you are looking for.
Related
Hello (excuse my English, not too confident with it)
I'm actually working on a Symfony website that display some spectacles' information.
For now, I need to add an image when I create one of them. I managed to do so with the help of this tutorial.
It basically works like this: I upload an image into site's directory and then send file's name to the entity (Store in a MySQL database). I can then display the image in spectacle's details.
The issue appeared when I want to edit a spectacle. I can't update the image's name. I have two only possibilities are to 1/not edit the entity, or to 2/change the image name and then get a random one that I can't display anymore (these names are usually like /tmp/phpWb8kwV)
My image is instantiate like this in the entity (in Spectacle.php):
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255)
* #Assert\NotBlank(message="Veuillez ajouter une image à votre spectacle.")
* #Assert\File(mimeTypes={ "image/png" })
*/
private $image;
And the FormType for the spectacle's form is made like this (in SpectacleType.php):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image',FileType::class, array(
'label' => 'Image du spectacle',
'required' => false, //(Still need to provide a file to finalize the creation/edit)
));
}
And the controller to acces this page is made like this (in SpectacleController.php):
/**
* Creates a new spectacle entity.
*
* #Route("/new", name="admin_spectacle_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$spectacle = new Spectacle();
$form = $this->createForm('FabopBundle\Form\SpectacleType', $spectacle);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
$em->persist($spectacle);
$em->flush();
return $this->redirectToRoute('admin_spectacle_show', array('id' => $spectacle->getId()));
}
return $this->render('spectacle/new.html.twig', array(
'spectacle' => $spectacle,
'form' => $form->createView(),
));
}
The function that is routed to the edit view is approximatively the same, but i can't use
$spectacle->setImage($fileName);
There is two possibilities to solve this: I would like being able to update the new filename in the entity (with the other information) or being able to update the entity without changing filename.
I hope I was clear enough to explain my problem...
Thanks in advance for your responses.
I had this problem when trying to upload a PDF/TEXT.. file.
But for managing images, I advice you to use ComurImageBundle, it helps you a lot and your problem will be resolved.
It's very simple, you download the bundle like it's explained in this link.
Then you modify your code like this :
1/ Instantiation of your image in Spectacle.php (your image is stored in the DB like string)
/**
* #ORM\Column(type="string", nullable=true)
*/
private $image;
2/ Update your base ( php bin/console doctrine:schema:update --force)
3/ Add these functions to your Spectacle.php after updating your DB schema, these functions let you upload and stock your images under specific directory (web/uploads/spectacles) and don't forget to add this two libraries
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #Assert\File()
*/
private $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* #ORM\PrePersist
*/
public function preUpload()
{
if (null !== $this->file) {
$this->image = uniqid() . '.' . $this->file->guessExtension();
}
}
/**
* #ORM\PostPersist
*/
public function upload()
{
if (null === $this->file) {
return;
}
// If there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->file->move($this->getUploadRootDir(), $this->image);
}
public function getUploadDir()
{
return 'uploads/spectacles';
}
public function getBaseUrl()
{
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
return substr($pathInfo['dirname']."/", 1);
}
public function getUploadRootDir()
{
return $this->getBaseUrl() . $this->getUploadDir();
}
public function getWebPath()
{
return null === $this->image ? null : $this->getUploadDir() . '/' . $this->image;
}
public function getAbsolutePath()
{
return null === $this->image ? null : $this->getUploadRootDir() . '/' . $this->image;
}
4/ Modify the FormType (SpectacleType.php)like this
use Comur\ImageBundle\Form\Type\CroppableImageType;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image', CroppableImageType::class, array('label' => 'Image', 'required' => true,
'uploadConfig' => array(
'uploadUrl' => $myEntity->getUploadDir(), // required - see explanation below (you can also put just a dir path)
'webDir' => $myEntity->getUploadRootDir(), // required - see explanation below (you can also put just a dir path)
'fileExt' => '*.png', // required - see explanation below (you can also put just a dir path)
'showLibrary' => false,
),
'cropConfig' => array(
'minWidth' => 128,
'minHeight' => 128,
'aspectRatio' => true,
)
));
}
5/ Remove all these lines from your controller you won't need them
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
6/ That's it you can call the form of your image in new.html.twig and edit.html.twig, all will get well, try it please and notify me if there is any problem.
The solution was stupid ...
In fact, the controller to access the edit route didn't have those lines:
$em = $this->getDoctrine()->getManager();
...
$em->persist($spectacle);
$em->flush();
I need to finish this quickly. If i have more time later, i'll try to make it work with the ComurImageBundle.
Thank you for your help, i'll be more carefull next time ...
I am attempting to return a list of comments related to a an entity. The query results on when it runs and returns, the related field does not provide a meaningful result.
Here is the comment entity declarations
/**
* #var Books
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Books")
*/
private $imagefk;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Users")
*/
private $userfk;
This is my controller snippets of codes that fetches all the comment a user commented to a particular book
private function serializeComments(Comments $cmt) {
return array(
'message' => $cmt->getMessage(),
'userid' => $cmt->getUserfk(),
'bookid' => $cmt->getBookfk(),
);
}
the below function calls the function above
public function getAllCommentsAction($books)
{
$messages = $em->getRepository("AppBundle")->findBy(
array(
"imagefk" => $books
)
);
$data = array();
foreach ($messages as $message)
{
array_push($data, $this->serializeComments($message));
}
$response = new Response(json_encode($data), 200);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Here is the result of attempt
[{"message":"This is comment for a user one","userid":{"__initializer__":{},"__cloner__":{},"__isInitialized__":false},"bookid":{"path":"http:\/\/10.0.2.2:88\/xxx\/web\/uploads\/pdf\/5ub3uy8zv09cee2avi11.pdf"}}
Please how can I return the objects properties from this result instead of this
"userid":{"__initializer__":{},"__cloner__":{},"__isInitialized__":false},"bookid":{"path":"http:\/\/10.0.2.2:88\/xxx\/web\/uploads\/pdf\/5ub3uy8zv09cee2avi11.pdf"
Try accessing the object properties:
'userid' => $cmt->getUserfk()->getId(),
instead of
'userid' => $cmt->getUserfk(),
Hope this help
I try to modify the extension importr to insert a custom action to the controller "Importr" at importr\Classes\Controller\ImportrController.php.
I called the action "customAction" and reference to it from a button which I render with fluid in importr\Resources\Private\Templates\Importr\Index.html by using <f:link.action>
<div id="myButton">
<f:link.action
extensionName="Importr"
pluginName="Importr"
controller="Importr"
action="custom"
arguments="{taskid:5}"
>
Click here
</f:link.action>
</div>
controller action:
/**
* #param int $taskid
* #return void
*/
public function customAction($taskid)
{
...
}
However, every attempt to pass a parameter to the action fails.
At my first attempt I even get an error page without even clicking on the button as you can see in the screenshot below.
Attempt #1
/**
* #param int $taskid
* #return void
*/
public function customAction($taskid)
{
print_r($taskid);
die;
}
Uncaught TYPO3 Exception
1298012500: Required argument "taskid" is not set for HDNET\Importr\Controller\ImportrController->custom.
TYPO3\CMS\Extbase\Mvc\Controller\Exception\RequiredArgumentMissingException
thrown in file
/var/www/typo3/typo3_src-6.2.25/typo3/sysext/extbase/Classes/Mvc/Controller/AbstractController.php
in line 425.'
Attempt #2
/**
* #return void
*/
public function customAction()
{
$taskid = "default";
if ($this->request->hasArgument('taskid')) {
$taskid = $this->request->getArgument('taskid');
}
echo "TASKID = '$taskid'";
die;
...
OUTPUT: TASKID = 'default'
Attempt #3:
/**
* #return void
*/
public function customAction()
{
$args = $this->request->getArguments();
$taskid = $args['taskid'];
echo "TASKID = '$taskid'";
die;
OUTPUT: TASKID = ''
I don't know what else I can try. Is it possible that I made a mistake in the Fluid Code? Do I use a wrong pluginName or extensionName or is it even a typo3 bug? Where is the pluginName stored so I can check it?
More Infos
I allowed my custom action by adding it to the other actions inside ext_tables.php
<?php
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
/** #var string $_EXTKEY */
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
'HDNET.' . $_EXTKEY,
'file',
'tx_importr_mod',
'',
[
'Importr' => 'custom,index,import,preview,create',
],
[
'access' => 'user,group',
'icon' => 'EXT:' . $_EXTKEY . '/ext_icon.gif',
'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_mod.xlf'
]);
There were two problems:
1. ext_tables.php
The order of the actions was not correct.
The first action is always the default action, so it took my custom action as default action and therefor no page was loaded after clicking on the Importr Modul in the menu at the left. It worked after I corrected it.
'Importr' => 'index,import,preview,create,custom',
2. Fluid
The pluginName was incorrect, the correct pluginName is file_importrtximportrmod, which we can see in ext_tables.php
It is not even needed, it also works if you omit pluginName and extensionName.
Make sure to clear the cache in the install tool afterwards.
As the title states, I'm getting an odd error in Laravel 5. I'm new to Laravel, and this week I dived into Jobs/Queues. I've gotten an "Undefined Variable: $errors" error in the past, and that one I was able to understand and fix. But now, I can't seem to get past this one. To my knowledge, everything looks fine. The following breakdown will (hopefully) give you an idea of what I'm doing/where the error happens:
class PostFormFields extends Job implements SelfHandling
{
use InteractsWithQueue, SerializesModels;
/**
* The id (if any) of the Post row
*/
protected $id;
/**
* List of fields and default value for each field
*/
protected $fieldList = [
'title' => '',
'subtitle' => '',
'page_image' => '',
'content' => '',
'meta_description' => '',
'is_draft' => '8',
'publish_date' => '',
'publish_time' => '',
'layout' => 'blog.layouts.post',
'tags' => [],
];
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($id = null)
{
$this->id = $id;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$fields = $this->fieldList;
if($this->id)
{
$fields = $this->fieldsFromModel($this->id, $fields);
} else {
$when = Carbon::now()->addHour();
$fields['publish_date'] = $when->format('M-j-Y');
$fields['publish_time'] = $when->format('g:i A');
}
/**
* Populate with old values, if they exist
* #var [type]
*/
foreach ($fields as $fieldName => $fieldValue)
{
$fields[$fieldName] = old($fieldName, $fieldValue);
}
$fields = array_merge($fields, ['allTags' => Tag::lists('tag')->all()]);
return $fields;
}
Above is the code inside the handler function of my Job class, the file it sits in is called PostFormFields.php. It's job, essentially, is just to return an array filled with all the values pertaining to a post, based on the Post Model and what's in the database that pertains to that specific Post ('title','content',etc) if a user's entered them in the past
public function create()
{
$data = $this->dispatch(new PostFormFields());
$data['title'] = 'testing';
var_dump($data);
return view('admin.post.create', $data);
}
Above is the code inside my PostController class, in the create() method. As you can tell, I'm using a resource controller for my Post Controller. It dispatches the PostFormFields Job and stores all the returned data in an array $data. However, since the create() method will be used to create a new post, only the keys should be returned, with values set to their default value ''.
This works. As you can see, i run a 'var_dump()' on the variable $data to see what, if anything, is returned. I then pass the $data array to the create View. This is where the error comes up.
Laravel "Undefined Varieble" Error
Above is a picture of the error I get when I try to access the /create route. It's clear that the $data does have the $title variable defined, as well as all the other keys in the array. Why am I getting an "Undefined Variable" array when I clearly have it defined by the time it's sent to the create View?
The line of code is says the error is in is the following:
<input type="text" class="radius" name="title" id="title" value="{{ $title }}">
You have to pass that array to view via compact function of laravel. So that you can use it in view as you want.
Please check about compact here - https://laracasts.com/discuss/channels/general-discussion/phps-compact-pros-and-cons?page=1
public function create()
{
$data = $this->dispatch(new PostFormFields());
$data['title'] = 'testing';
var_dump($data);
return view('admin.post.create', compact('data'));
}
I'm using league/fractal with JsonApiSerializer,
I've got users collection for json output.
Now I want to add some filters data to this json response (like users count for current filters).
I got this:
$resource = new Collection($dataProvider->getData(), new UserTransformer());
//the only way to include some not directly linked data i found is using setMeta():
$resource->setMetaValue('projects', $dataProvider->getProjects());
$resource->setMetaValue('somes', $dataProvider->getTasks());
But! 'projects' & 'somes' collections (yes, they are collection too) also included with 'data' key in it.
So, I've got this structure:
{
'data' => [
{//user1},{//user2},...
],
'meta' => {
'projects' => {
'data' => {...}
},
'somes' => {
'data' => {...}
}
}
}
but I want something like:
{
'data' => [
{//user1},{//user2},...
],
'meta' => {
'projects' => {...}, //there is no 'data' key
'somes' => {...} //there is no 'data' key
}
}
What should I do?
This is kinda hack but works fine without refactor Scope class which hardcoded in fractal's League\Fractal\Manager::createData() and is only way to use your own Scope class realization is to overload this method in Manager's extension.
<?php
use League\Fractal\Serializer\JsonApiSerializer;
/**
* Class EmbedSerializer
*/
class EmbedSerializer extends JsonApiSerializer
{
const RESOURCE_EMBEDDED_KEY = 'embedded';
/**
* Serialize a collection.
*
* #param string $resourceKey
* #param array $data
* #return array
*/
public function collection($resourceKey, array $data)
{
return $resourceKey === self::RESOURCE_EMBEDDED_KEY ? $data : [$resourceKey ?: 'data' => $data];
}
/**
* Serialize an item.
*
* #param string $resourceKey
* #param array $data
* #return array
*/
public function item($resourceKey, array $data)
{
return $resourceKey === self::RESOURCE_EMBEDDED_KEY ? $data : [$resourceKey ?: 'data' => [$data]];
}
}
So, now i could use it like:
/** #var $this->fractal League\Fractal\Manager */
$this->fractal->setSerializer(new EmbedSerializer());
$projectsCollection = $this->fractal->createData(
new Collection($projects, new UserProjectTransformer(), 'embedded')
)->toArray();
$resource = new Collection($users, new UserTransformer());
$resource->setMetaValue('projects', $projectsCollection);
That's all u need. Hope this will be helpful.