Prestashop 1.7 file saving - php

How to upload a file and save it in Prestashop 1.7?
In ProductComments module I have a modal with a <form>:
post-comment-modal.tpl
<form id="post-product-comment-form" action="{$post_comment_url nofilter}" method="POST" enctype="multipart/form-data">
<div>
<div class="form-floating">
<input name="comment_title" type="text" class="form-control" placeholder="Title"/>
<label for="comment_title">Title</label>
</div>
<div class="form-floating">
<input name="customer_name" type="text" class="form-control" placeholder="Name"/>
<label for="customer_name">Name</label>
</div>
<div class="form-floating">
<textarea name="comment_content" class="form-control" placeholder="Review"></textarea>
<label for="comment_content">Review</label>
</div>
<input type="file" id="photo_input" name="photo_input" multiple> // I've added this field
<button type="submit">Send</button>
</div>
</form>
I've added there a <input type="file">.
This form is posted into ProductCommentsPostCommentModuleFrontController which extends ModuleFrontController
PostComment.php
class ProductCommentsPostCommentModuleFrontController extends ModuleFrontController
{
public function display()
{
$id_product = (int) Tools::getValue('id_product');
$comment_title = Tools::getValue('comment_title'); // Proper value
$comment_content = Tools::getValue('comment_content'); // Proper value
$customer_name = Tools::getValue('customer_name'); // Proper value
$criterions = (array) Tools::getValue('criterion');
$photo = Tools::getValue('photo_input'); // false
$file = $_FILES['photo_input']['name']; // null
// Validation
/** #var EntityManagerInterface $entityManager */
$entityManager = $this->container->get('doctrine.orm.entity_manager');
//Create product comment
$productComment = new ProductComment();
// Validation
$productComment
->setProductId($id_product)
->setTitle($comment_title)
->setContent($comment_content)
->setCustomerName($customer_name)
->setCustomerId($this->context->cookie->id_customer)
->setGuestId($this->context->cookie->id_guest)
->setDateAdd(new \DateTime('now', new \DateTimeZone('UTC')))
;
$entityManager->persist($productComment);
$this->addCommentGrades($productComment, $criterions);
$entityManager->flush();
$this->ajaxRender(
json_encode(
[
'success' => true,
'product_comment' => $productComment->toArray(),
]
)
);
}
Is there a way to extend this controller, and add a variable which holds a file upoaded by user by POST method?

Related

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

Is there a way to handle this error when updating a record in Laravel?

So this is my web.php
<?php
use App\Http\Controllers\BookingController;
use App\Http\Controllers\BookingRoomController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\GuestController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\RoomController;
use App\Models\Customer;
use App\Models\Room;
use App\Models\Guest;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome',[
'customerCount' => Customer::count(),
'guestCount' => Guest::count(),
'roomCount' => Room::count()
]);
});
// Customer Controller
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
// Guest Controller
Route::get('/guests',[GuestController::class,'index'])->name('guests.index');
Route::get('/guests/add',[GuestController::class,'create'])->name('guests.create');
Route::post('/guests',[GuestController::class,'store'])->name('guests.store');
Route::post('/guests/update',[GuestController::class,'update'])->name('guests.update');
Route::get('/guests/search',[GuestController::class,'search'])->name('guests.search');
Route::get('/guests/{id}',[GuestController::class,'show'])->name('guests.show');
Route::delete('/guests/{id}',[GuestController::class,'destroy'])->name('guests.destroy');
// Rooms
Route::get('/rooms',[RoomController::class,'index'])->name('rooms.index');
Route::post('/rooms/update',[RoomController::class,'update'])->name('rooms.update');
Route::get('/rooms/{id}',[RoomController::class,'show'])->name('rooms.show');
// Bookings
Route::get('/bookings',[BookingController::class,'index'])->name('bookings.index');
Route::get('/bookings/create',[BookingController::class,'create'])->name('bookings.create');
Route::post('/bookings',[BookingController::class,'store'])->name('bookings.store');
Route::get('/bookings/{id}',[BookingController::class,'show'])->name('bookings.show');
// Booking Rooms
Route::post('/bookingrooms',[BookingRoomController::class,'store'])->name('bookingrooms.store');
// Authentication
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
// Route::get('/email/verify', function () {
// return view('auth.verify-email');
// })->middleware('auth')->name('verification.notice');
// Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
// $request->fulfill();
// return redirect('/home');
// })->middleware(['auth', 'signed'])->name('verification.verify');
This is my customer controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
class CustomerController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['store','create']);
}
public function index(){
$customer = Customer::latest()->get();
return view('customers.index',['customer' => $customer]);
}
public function show($id){
$customer = Customer::findOrFail($id);
return view('customers.show',['customer' => $customer]);
}
public function create(){
return view('customers.create');
}
public function store(){
$customer = new Customer();
$customer->title = request('title');
$customer->first_name = request('firstname');
$customer->last_name = request('lastname');
$customer->date_of_birth = request('dateofbirth');
$customer->street = request('street');
$customer->town = request('town');
$customer->province = request('province');
$customer->postal_code = request('postalcode');
$customer->home_phone = request('homephone');
$customer->work_phone = request('workphone');
$customer->mobile_phone = request('mobilephone');
$customer->email = request('email');
$customer->save();
return redirect('/')->with('mssg','Added customer successfully!');
}
public function update(Request $req){
$customer = Customer::findorFail($req->id);
$customer->title = $req->title;
$customer->first_name = $req->firstname;
$customer->last_name = $req->lastname;
$customer->date_of_birth = $req->dateofbirth;
$customer->street = $req->street;
$customer->town = $req->town;
$customer->province = $req->province;
$customer->postal_code = $req->postalcode;
$customer->home_phone = $req->homephone;
$customer->work_phone = $req->workphone;
$customer->mobile_phone = $req->mobilephone;
$customer->email = $req->email;
$customer->save();
return redirect('/')->with('mssg','Updated customer successfully!');
}
public function search(Request $req){
$search = $req->get('search-customer');
$customer = Customer::where('first_name','like','%'.$search.'%')->paginate(5);
return view('customers.index',['customer' => $customer]);
// $records = ['first_name' => '%'.$search.'%',
// 'title' => '%'.$search.'%',
// 'last_name' => '%'.$search.'%'
// ];
}
public function destroy($id){
$customer = Customer::findOrFail($id);
$customer->delete();
return redirect('/')->with('mssg','Customer has been deleted!');
}
public function quantity(){
$customer = Customer::all();
return view('/',['customers' => $customer]);
}
}
This is my show.blade.php
#extends('layouts.app')
#section('content')
<div class="insert-customer-container-main">
<h1>Customer Information</h1>
<p>Please fill in the following</p>
<form class="insert-customer-container" action="{{ route('customers.update') }}" method="POST">
#csrf
{{-- get in controller to manipulate updating --}}
<input type="hidden" name="id" value="{{$customer->id}}">
<div class="customer-input-container row-one">
<div class="customer-input">
<label for="title">Title</label><br/>
<input style="width:945px" type="text" name="title" value="{{$customer->title}}" required>
</div>
</div>
<div class="customer-input-container row-two">
<div class="customer-input">
<label for="firstname">First Name</label><br/>
<input type="text" name="firstname" value="{{$customer->first_name}}">
</div>
<div class="customer-input">
<label for="lastname">Last Name</label><br/>
<input type="text" name="lastname" value="{{$customer->last_name}}">
</div>
<div class="customer-input">
<label for="dateofbirth">Date of Birth</label><br/>
<input type="date" name="dateofbirth" value="{{$customer->date_of_birth}}">
</div>
</div>
<div class="customer-input-container row-three">
<div class="customer-input">
<label for="street">Street</label><br/>
<input type="text" name="street" value="{{$customer->street}}">
</div>
<div class="customer-input">
<label for="town">Town</label><br/>
<input type="text" name="town" value="{{$customer->town}}">
</div>
<div class="customer-input">
<label for="province">Province</label><br/>
<input type="text" name="province" value="{{$customer->province}}">
</div>
</div>
<div class="customer-input-container row-four">
<div class="customer-input">
<label for="homephone">Home Phone</label><br/>
<input type="number" name="homephone" value="{{$customer->home_phone}}">
</div>
<div class="customer-input">
<label for="workphone">Work Phone</label><br/>
<input type="number" name="workphone" value="{{$customer->work_phone}}">
</div>
<div class="customer-input">
<label for="mobilephone">Mobile Phone</label><br/>
<input type="number" name="mobilephone" value="{{$customer->mobile_phone}}">
</div>
</div>
<div class="customer-input-container row-five">
<div class="customer-input">
<label for="postalcode">Postal Code</label><br/>
<input type="number" name="postalcode" value="{{$customer->postal_code}}">
</div>
<div class="customer-input">
<label for="email">Email Address</label><br/>
<input style="width:50vw;" type="email" name="email" value="{{$customer->email}}">
</div>
</div>
<input class="submit" type="submit" value="Update">
</form>
<form class="delete-form" action={{ route('customers.destroy', $customer->customer_id) }} method="POST">
#csrf
#method('DELETE')
<input type="submit" class="submit delete-btn" value="Delete">
</form>
</div>
#endsection
So my question is
When I'm editing a specific record and when I submit it, it redirects me to 404 page which is not what I'm expecting. Is there a way to fix this problem? I'm new in laravel and hoping someone could help. Thanks everyone!
May be your Route wrong
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
after
Route::resource('customers', 'CustomerController');
edit your all routes by resource after that try and also check your
route list
php artisan route:list
404: Not found
I think that is due to the wrong url you have passed as an action.
try to clean up your routes:
Route::group(['prefix' => 'customers', 'as' => 'customers.'], function() { Route::post('/update',[CustomerController::class,'update'])->name('customers.update'); });

OctoberCMS Frontend file upload not adding file but adding database entry

I have edited the Rainlab User plugin to allow for the user to upload a file on the frontend attached to their user profile. Works in the backend but not working on the frontend.
Inside User.php Model
public $attachOne = [
'avatar' => 'System\Models\File',
'id_document' => 'System\Models\File'
];
/**
* #var array The attributes that are mass assignable.
*/
protected $fillable = [
'name',
'surname',
'login',
'username',
'email',
'password',
'password_confirmation',
'created_ip_address',
'last_ip_address',
'id_document'
];
Inside Account.php Component
public function onSubmit()
{
if (!$user = $this->user()) {
return;
}
$data = post();
if ($this->updateRequiresPassword()) {
if (!$user->checkHashValue('password', $data['password_current'])) {
throw new ValidationException(['password_current' => Lang::get('rainlab.user::lang.account.invalid_current_pass')]);
}
}
if (Input::hasFile('avatar')) {
$user->avatar = Input::file('avatar');
}
if (Input::hasFile('id_document')) {
$user->id_document = Input::file('id_document');
}
$user->fill($data);
$user->save();
/*
* Password has changed, reauthenticate the user
*/
if (array_key_exists('password', $data) && strlen($data['password'])) {
Auth::login($user->reload(), true);
}
Flash::success(post('flash', Lang::get(/*Settings successfully saved!*/'rainlab.user::lang.account.success_saved')));
/*
* Redirect
*/
if ($redirect = $this->makeRedirection()) {
return $redirect;
}
$this->prepareVars();
}
Inside update.htm component
<form data-request="onSubmit" data-request-files data-request-flash>
<input type="hidden" name="_handler" value="onSubmit">
{{ form_token() }}
{{ form_sessionKey() }}
<div class="form-group">
<label for="accountName">Full Name</label>
<input name="name" type="text" class="form-control" id="accountName" value="{{ user.name }}">
</div>
<div class="form-group">
<label for="accountEmail">Email</label>
<input name="email" type="email" class="form-control" id="accountEmail" value="{{ user.email }}">
</div>
<div class="form-group">
<label for="accountEmail">ID Document</label>
<input type="file" name="id_document">
</div>
<div class="form-group">
<label for="accountEmail">Avatar</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
Result in system_files table when I submit the form
Database return
How do I make sure it adds all needed details in order to upload the file. Even the storage does not reflect the file on upload.

Unable to preserve input values after form validation Codeigniter 4

This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}

OCTOBERCMS Form and Model

I'm a newbie in OctoberCms and i don't have much knowledge in Laravel also. While self studying I face a request like this it's a Select if record exist query I need to read the database and look for the match and I'm really confuse.
This is my form in form.htm where I design my Form.
use Drufal\DynamicContentManager\Models\MembersVerification;
==
<form data-request="onSend" accept-charset="UTF8" enctype="multipart/form-data">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" name="first_name" required>
</div>
<div class="form-group">
<label>Middle Name:</label>
<input type="text" class="form-control" name="middle_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" name="last_name" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
and this my model
<?php namespace Drufal\DynamicContentManager\Models;
use Model;
use Input;
/**
* Model
*/
class MembersVerification extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Disable timestamps by default.
* Remove this line if timestamps are defined in the database table.
*/
public $timestamps = false;
/**
* #var array Validation rules
*/
public $rules = [
];
/**
* #var string The database table used by the model.
*/
public $table = 'drufal_dynamiccontentmanager_members';
public function onSend(){
$fn = Input::get('first_name');
$mn = Input::get('middle_name');
$ln = Input::get('last_name');
$membertbl=$table::where('first_name', '=', $fn)->first();
if ($membertbl === null) {
echo"
<script>
alert('Successfully');
</script>
";
}else{
echo"NO RESULT";
}
}
}
Help the newbie please.
I think you missed the DB:: in your database request:
$users = Db::table('users')->where('votes', 100)->first();
Maybe this documentation will help you:
https://octobercms.com/docs/database/query#where-clauses

Categories