CakePHP 3.x call function - cakephp

I have a view that is add a called help desk opening form (referring to add function, of course), and have this function is to upload that file to attach request, which is connected with a component, but I do not want to Let them in different view, because if I just send a file upload through the view, the image is "lost " and does not turn the call. I need within the add function I can call the upload function, to join views. If I call her by $ this-> upload (); Or simply make all the checking in of add, does not find the component, returning me an error (which I put down ), I believe the conflict is in the request-> data but do not know if there is a way to join the way I explained.
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is(['post', 'put'])) {
$this->Posts->patchEntity($post, $this->request->data);
$post->user_id = $this->Auth->user('id');
if ($this->Posts->save($post)) {
$this->Flash->success(__('send'));
return $this->redirect(['action' => 'listar']);
}
$this->Flash->error(__('not send'));
}
$this->set(compact('post'));
}
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data(['uploadfile']));
return $this->redirect(['action'=>'add']);
}
}
Component:
public function send( $data )
{
if ( !empty( $data) ) {
if ( count( $data) > $this->max_files ) {
throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
}
foreach ($data as $file) {
$filename = $file['name']; //line 32
$file_tmp_name = $file['tmp_name']; //33
$dir = WWW_ROOT.'img'.DS.'Anexos';
$allowed = array('png', 'jpg', 'jpeg');
if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
throw new InternalErrorException("Error Processing Request.", 1);
}elseif( is_uploaded_file( $file_tmp_name ) ){
$filename = Text::uuid().'-'.$filename;
$filedb = TableRegistry::get('Arquivos');
$entity = $filedb->newEntity();
$entity->filename = $filename;
$filedb->save($entity);
move_uploaded_file($file_tmp_name, $dir.DS.$filename);
}
}
}
}
Error when calling upload();
Warning (2): Illegal string offset 'name' [APP/Controller\Component\UploadComponent.php, line 32]
Warning (2): Illegal string offset 'tmp_name' [APP/Controller\Component\UploadComponent.php, line 33]
view:
<?php
//this is my view add ;
echo $this->Form->input('id' );
echo $this->Form->input('titulo');
echo $this->Form->input('ip');
echo $this->Form->input('mensagem');
?>
//and this is my view upload, I would like to join with add ;
<?php echo $this->Form->create(null, ['type' => 'file']); ?>
<label>Arquivos</label>
<?php
echo $this->Form->file('uploadfile.', ['multiple']);
echo $this->Form->button('Anexar', ['action' => 'submit']);
echo $this->Form->end();
?>

You aren't accessing uploadfile array. This line $this->Upload->send($this->request->data(['uploadfile'])); should be like $this->Upload->send($this->request->data('uploadfile'));.
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data('uploadfile'));
return $this->redirect(['action'=>'add']);
}
}

Related

Array to string Error while uploading an Image

i was trying to upload image using cakephp , i got the following error :
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
<?php echo $this->Form->create('User',array('type'=>'file'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
anything wrong with what i've did ?
You study cakephp manual properly HOW form type can be File ?????? :)
Use this
<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
You need to treat the file upload in the controller. If you debug the request you'll see that profile_pic field is an array:
# in controller:
if ($this->request->is('post')) {
debug($this->request->data); die();
}
# result:
array(
'User' => array(
'profile_pic' => array(
'name' => 'wappy500x500.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/tmp/phptk28hE',
'error' => (int) 0,
'size' => (int) 238264
)
)
)
Short answer:
public function upload() {
if ($this->request->is('post')) {
if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) {
$source = $this->request->data['User']['profile_pic']['tmp_name']; // Source
$dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS; // Destination
move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir)
$this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB
$this->User->create(); // We have a new entry
$this->User->save($this->request->data); // Save the request
$this->Session->setFlash(__('The user has been saved.')); // Send a success flash message
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Of course you need to make extra validations on the uploaded file.
Further reading: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file

Not able upload filename into db, in uploading concepts

In my UsersController.php
public function uploadFile()
{
$filename = '';
if ($this->request->is('post')) {
$uploadData = $this->data['uploadFile']['image'];
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) {
return false;
}
$filename = basename($uploadData['name']);
if ($this->User->save($filename)) {
$this->Session->setFlash(__('Your imagename has been saved.'));
}
$uploadFolder = WWW_ROOT. 'files';
$filename = time() .'_'. $filename;
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder);
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
//$this->set('pdf_path', $fileName);
return false;
}
}
}
}
And in my uploadfile.ctp
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
echo $this->Form->input('image', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
?>
In my db I have table name "image" along with some other fields. Now I'm not able to upload file name into db.
If you have a table name called 'image', then it should be related to the user model. $this->User->save($filename) needs at least a table field called 'filename' in the User table AND it needs to be assigned to a user via $this->User->id = $user_id;
If your image table has an image model which is related to the user model, read the book's chapter 'Saving related model data' http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto

cakephp post data field missing from SQL update statement

Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)

Get array from model, then pass to view

Simple, but for me as a beginner, a problem. I need to pass an array from my model (array is filled with info while reading a text file) to a controller and then finally to a view.
My model:
function show_notes(){
$file = "notes.txt";
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
$notes = array (
'user'=> '$user',
'content'=> '$content'
);
}
return $notes;
}
Controller:
function members_area()
{
$this->load->model('Note_model');
$notes[] = $this->Note_model->show_notes();
$this->load->view('includes/header');
$this->load->view('members_area', $notes);
$this->load->view('includes/footer');
}
And in view I use this:
foreach ($notes as $item)
{
echo "<h1>$user</h>";
echo "<p>$content</p>";
}
And I am getting error that notes variable is undefined in my view.
I think I just don't understand how arrays work. I have tried to read about that, I have tried some examples similar to this, but still can't get it.
In your controller:
$data['notes'] = $this->Note_model->show_notes();
...
$this->load->view('members_area', $data);
EDIT:
In your view:
<?php foreach ($notes as $item):?>
<h1><?php echo $item['user']; ?></h1>
<p><?php echo $item['content'] ?></p>
<?php endforeach; ?>
In your model:
$notes = array();
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
array_push($notes, array('user' => $user, 'content' => $content));
}
return $notes;
Replace this
$notes[] = $this->Note_model->show_notes();
with this
$notes['notes'] = $this->Note_model->show_notes();

how to put image variable between image helper quotes

app\views\images/view.ctp
this is the views code ..i need help to fetch image
<?php
// initialise a counter for striping the table
$count = 0;
// loop through and display format
foreach($images as $image){
// stripes the table by adding a class to every other row
$class = ( ($count % 2) ? " class='altrow'": '' );
// increment count
$count++;
$full3 = '/img/images/'.$image['Image'];
$thumb3 = $this->Html->image('images/image-1.jpg',array("width"=>"60", "height"=>"40"));
var_dump($full3) ;
$this->Html->link($thumb3,$full3,array('escape' => false, 'rel' => 'lightbox[plants]','title'=>'thanks allah for help me'));
}
?>
the controller code is images_controller code..
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid image', true));
$this->redirect(array('action' => 'index'));
}
$this->set('image', $this->Image->read(null, $id));
$images= $this->Image->find('all');
$this->set('images', $images);
}
replace this line
echo $thumb3 = $this->Html->image('images"/".$image['Image']['img_file']',array('width'=>"60", 'height'=>"40"));
with
echo $thumb3 = $this->Html->image("images/".$image['Image']['img_file'],array("width"=>"60", "height"=>"40"));

Resources