Send image email cakephp without storing it - cakephp

I'm using Cakephp 3 with Cake\Network\Email\Email.
I have a form to send a message with two input fields. Those fields are stored in database.
I'd like to join an image to this form without storing it: only in attachment.
Here is my input file :
<?php echo $this->Form->file('photo', ['class' => 'form-control','value'=>'','accept'=>'image/*']); ?>
My Controller :
$Email = new Email('default');
$Email->theme('Front')
->template('my_template1')
->viewVars(['sender'=> $user, 'recipes'=> $recipes])
->attachments([$this->request->data['photo'] => $this->request->data['photo']['tmp_name']])
->emailFormat('html')
->to('xx#xx.com')
->from($user['email'])
->send();
Text inputs are well stored and sent. But no image attached in my email...
What's wrong?
Thanks!

I was stuck here to i got it, in your create form add
'enctype'=>'multipart/form-data'
So it should be
echo $this->Form->create($email, ['enctype'=>'multipart/form-data']);
This is added in the other controller by default but when you use a model less form it doesn't do this.

Related

How to give id to an image in CakePHP?

I'm inserting an image in my template file as
<?php echo $this->Html->image('profile_picture.png', array('alt'=>'frame partner avatar'), array('id'=>'framePartnerAvatar')); ?>
Now I'm trying to give style to this image by using the id mentioned, but on checking through Firebug only source and alternate name is visible. Image id is not coming there.
You have to use the correct syntax:
<?php echo $this->Html->image(
'profile_picture.png',
array(
'alt'=>'frame partner avatar',
'id'=>'framePartnerAvatar'
)); ?>
See HtmlHelper::image()
According to the documentation the method used to create images requires two parameters. The first one being the source link and the second one being the options parameter
$this->Html->image('cake_logo.png', ['alt' => 'CakePHP']);
Your code should be something along the lines of this
$this->Html->image('profile_picture.png', array(
'alt'=>'frame partner avatar',
'id'=>'framePartnerAvatar')
);
$thumb_img = $this->Html->image('yourimage.png',array('alt'=>'yoursite.com','id'=>'yourId'));
Please ensure that all HTML attributes such as alt, id, class etc needs to be written within a single array, and not multiple arrays.
<?php echo $this->Html->image('profile_picture.png', array(
'alt'=>'frame partner avatar',
'id'=>'framePartnerAvatar'
)
); ?>
This will certainly generate the following HTML:
<img src="/img/profile_picture.png" alt='frame partner avatar' id='framePartnerAvatar' />
Peace! xD

cakephp getLastInsertId not working

Here I have used cakephp js helper to send data,After insert One data I need this last id for farther work.Here I have tried bellow code in Addcontroller
if ($this->Patient->save($this->request->data)) {
$lastid=$this->Patient->getLastInsertId();
$patient=$this->Patient->find('all',array(
'conditions'=>array('Patient.id'=>$lastid ),
'recursive' => -1
));
$this->set('patient', $patient);
}
In add.ctp I have tried bellow code but I haven't get last id here.
<?php foreach ($patient as $patient): ?>
<?php echo h($patient['Patient']['id']); ?>
<?php endforeach; ?>
Method getLastInsertId() return id of just saved records.
If you need this id in your view just after save, you must first set that variable in your controller like $this->set(compact('lastid','patient'); and then use in view <?php echo $lastid; ?>
use
if ($this->Patient->save($this->request->data)) {
$id = $this->Patient->id;
$patient=$this->Patient->find('all',array('conditions'=>array('Patient.id'=>$id),'recursive' => -1));
$this->set->('patient', $patient);
//If you are saving the record with ajax which it looks like you
//might be from your question you will need the following instead
//of $this->set->('patient', $patient); try:
return json_encode($patient);
You will then also need to update your js ajax call, you will have a json array to decode so parse it with jquery and append it back into your view.
Cake will always give you the id of record you have just saved, by simply adding $id = $this->MyModel->id; You can use the id to query for the record.
Try below code:
In controller:
$lastid=$this->Patient->getLastInsertId();
$this->set(compact('lastid','patient');
Then use $lastid in View file.
In controller:
$lastid=$this->Patient->getLastInsertId();
$patient['Patient']['last_id'] = $lastid;
then use $patient['Patient']['last_id'] in your view file.

Save associated Model data before Form submission

I have a polymorphic attachment model between Article and Image (alias for Attachment model) ala https://github.com/josegonzalez/upload. Article hasMany Image. Image is an Attachment.
When the form is submitted via the Article form's save button, everything saves properly, including associated models.
However, I have set up a dynamic display of attached images so that the user can choose which one to use for the article's preview before saving the article. The dynamic image display works (proved by deleting row in phpMyAdmin), but I cannot figure out how to upload and save the associated Image that has been selected without pressing the submit button. I'd like to upload the image immediately upon selection (or upon a button press that does not submit the article, too!
Here is the relevant form section, and the script that eventually results in the display of all associated Images.
<div id='imagesControl'>
<?php
//TODO gotta make this happen live
echo $this->Form->input('Image.0.attachment', array('type' => 'file', 'label' => 'Image'));
echo $this->Form->input('Image.0.model', array('type' => 'hidden', 'value' => 'Content'));
echo $this->Form->input('Image.0.foreign_key', array('type' => 'hidden', 'value' => $id));
echo $this->Form->input('Image.0.id', array('type' => 'hidden')); //Thought this would help
?>
<div id='attachedImages'>
</div> </div>
<script>
$(document).ready(function() {
$('#imagesControl').change(function() {window.alert("sometext");
$("#attachedImages").load('../imageDisplay/<?php echo $id ?> #attachedImages',
{id: $(this).attr('id')});
})
.change();
});
</script>
Notably, in the view file '../imageDisplay' that gets rendered, $this->data only contains the div id sent via $(this).attr('id'). I cannot find a variable, anywhere, that contains the file I chose in the input section before the form saves (the file I'm trying to upload and save). It's apparently there, because it does save using $this->Article->saveAll() automagic.
However, I cannot even begin to guess where / when / how I can upload the image and add a row to the attachments table containing the new image's data without submitting the article. I've been stuck for days.

blackhole cakephp 2 associated entities

My Goal:
Reuse of a contact form to be related to several different entities I call "Parents" ie Group has contact information, Member has contact info etc....
The way I tried doing it was:
1. Creating a view file for contact, named "form.ctp" which doesn`t create a new form, nor submits, just echo's the contact's fields.
2. Calling this file using requestAction
My Problem:
The form's _Token get crumbled.
Parent add.ctp example
<?php echo $this->Form->create('Group');?>
<fieldset>
echo $this->Form->input($field_prefix.'contact_id',array('type'=>'hidden'));
<?php echo $this->requestAction(array('controller' => 'contacts', 'action' => 'form'), array('named' => array('index'=>'0','parent'=>'Group',
'fields'=>array(
'email'=>array('value'=>'xx#yy.com','hidden'=>1)
))));
inside the form.ctp I have:
//Associated Model
echo $this->Form->input('Contact.0.city',array('type'=>'hidden'));
echo $this->Form->input('Contact.0.postcode');
echo $this->Form->input('Contact.0.phone');
echo $this->Form->input('Contact.0.cellphone');
echo $this->Form->input('Contact.0.email',array('value'=>""));
echo $this->Form->input('Contact.0.id',array('type'=>'hidden'));
?>
Looking at the HTML source code that is generated, I see that whether I use the request action or just copy the contect of the form.ctp into the "Parent's" add file, I get the same HTML result.
HOWEVER!!! when I use the form.ctp Action Request, I get the blackhole, the tokens are being messed up!!!
Any Ideas?
Thanks in advance
Orly
If your problem is solely reusing a form, you can use the form as a Element, and then you could call it multiple times, substituting in the exact values you need.
As for SecurityComponent, I would recommend (at least as a temporary fix) disabling SecurityComponent for that specific action by using $this->Security->unlockedActions(); in your controller's beforeFilter()

Cakephp Validation

I am using an Account Controller which doesnt have its own table but uses User Model.
All works fine except - when I validate any form. It says validation fails (when I try to fail the validation to check) but doesnt throw the error below the field
View
<?php echo $this->Form->input('id'); ?>
<label for="UserPassword">New Password:</label>
<?php echo $this->Form->text('password', array('type' => 'password', 'value' => 'harsha')); ?><em>Password must be min 6 characters.</em> <?php echo $form->error('password'); ?>
Controller Action
if($this->User->saveField('password', $this->data['User']['password'], array('validate' => 'first'))) {
$this->Session->setFlash('Password has been changed.', 'flash-success');
} else {
$this->Session->setFlash('There was some problem with our system. Please try after some time.', 'flash-warning');
}
Try debug()ing the contents of $this->validationErrors in your view, as well as $this->data in your controller just after a form submission. This should give you a lot more information to work from.
I suspect that your problem is Cake is building form inputs based on the wrong model -- building form fields for Account.id and Account.password instead of User.id and User.password. This is because FormHelper takes its default model from the controller/view it's invoked from, which in your case appears AccountsController.
In order to generate the User.id and User.password fields your controller's submission handling expects, you'll need to prepend User. in your FormHelper calls. Thus:
$this->Form->input('User.id');
$this->Form->text('User.password');
Have you tried:
echo $session->flash();
Note that whatever the manual says, it returns, not echoes. I logged this a while back and it has been changed in the 1.3 manual, but not the 1.2.
Hi you who's asking If you want to show error-message that return from UserModel's validate So you can add line code bellow after input form password
<?php
if ($this->Form->isFieldError('password')) {
echo $this->Form->error('password', array('class' => 'error'));
?>
and if you want to show error-message that set by method setFlash
you must redirect page and then use $this->Session->flash('flash-name') in page you want to show it
<?php
//in UsersController
$this->Session->setFlash('message here', 'flash-name');
//in view
echo $this->Session->flash('flash-name');
?>
Good luck!

Resources