Mutator doesn't fire for image upload - amazon-s3

Working on a project in Backpack for Laravel that involves uploading images, videos, etc. Starting with a simple image upload, I have a mutator in my model as follows:
public function setThumbnailAttribute($value)
{
$attribute_name = "Thumbnail_URL";
$disk = "s3";
$destination_path = "images";
$this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}
But it doesn't seem to fire, and whenever the file is 'uploaded' it shows a 'C:\Windows\Temp\php6803.tmp' as the location.
My field:
$this->crud->addField([
'name' => 'Thumbnail',
'label' => 'Thumbnail',
'type' => 'image',
'upload' => true,
'disk' => 's3'
]);
And my 's3' disk in filesystems.php:
's3' => [
'driver' => 's3',
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET'),
],
I've double checked that the Thumbnail_URL is fillable. I'm really not sure what I'm missing.

public function setThumbnailAttribute($value)
{
$attribute_name = "Thumbnail_URL";
$disk = "s3";
$destination_path = "images";
**MISSING** $this->attributes[$attribute_name] = '....' (image path/filename)
$this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}

Related

Cakephp 4 save delete auto_increment

I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => 'prueba#gmail.com',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
It was that the sql file used in the bootstrap didn't have the autoincrement value.

How to remove validation lastname from prestashop 1.7.8.3 backoffice

I have a question how to remove validation from LastName inside client address edit. I need to allow numbers inside this field.
I found here thread Prestashop : Remove Lastname Field Rules Validation From B.O, but this solution is not working.
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
Change this to isAnything
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
Now, you are ready to go and check.
Go to the file classes/Address.php file:
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
to :
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
validate to isAnything.
I think you were modifying in customer class. Please try with Address.php.
Thanks for sharing the files.
I have resolved the case. You need to modify the classes/form/CustomerAddressForm.php
line 229
$isValid &= $this->validateField('lastname', 'isName', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
Change to:
$isValid &= $this->validateField('lastname', 'isAnything', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
I want to do this good with override. I have an issue with override this class. I have created module to override but it is not working. There is a way to override this without editing core files?
services:
_defaults:
public: true
form.type.customer_address:
class: 'Playdev\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType'
public: true
arguments:
- '#prestashop.adapter.form.choice_provider.country_state_by_id'
- '#=service("prestashop.adapter.legacy.context").getContext().country.id'
- '#router'
tags:
- { name: form.type }
https://ibb.co/VVjnJYr
There is a file class override:
\modules\pd_overridemodule\src\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType.php
https://ibb.co/7QPHrqx
And I have an error when I am inside Edit Address Form Backoffice
Type error: Too few arguments to function PrestaShopBundle\Form\Admin\Sell\Address\CustomerAddressType::__construct(), 0 passed in C:\laragon\www\prestabiolab\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 5 expected
[Symfony\Component\Debug\Exception\FatalThrowableError 0]
https://ibb.co/YfwhtKq
I have found a solution
Need to create module and call hookactionCustomerAddressFormBuilderModifier.
public function hookactionCustomerAddressFormBuilderModifier(array $params)
{
/** #var $formBuilder \Symfony\Component\Form */
$formBuilder = $params['form_builder'];
// remove lastname field
$formBuilder->remove('last_name');
// get all fields without removed
$allFields = $formBuilder->all();
// remove all fields
foreach ($allFields as $inputField => $input) {
$formBuilder->remove($inputField);
}
foreach ($allFields as $inputField => $input) {
// normally add fields
$formBuilder->add($input);
// add fields after firstname
if ($inputField == 'first_name') {
$formBuilder->add('last_name', TextType::class, [
'label' => $this->trans('Last name', [], 'Admin.Global'),
'help' => $this->trans(
'Invalid characters:',
[],
'Admin.Notifications.Info'
) . ' ' . TypedRegexValidator::GENERIC_NAME_CHARS,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', [], 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH],
'Admin.Notifications.Error',
),
]),
],
]);
}
}
}
Now I think it works okey with override :)

SplFileInfo::getSize(): stat failed for D:\xampp\tmp\php83FA.tmp

When sumbit thoes field, it store my public path but face this
error:SplFileInfo::getSize(): stat failed for D:\xampp\tmp\php83FA.tmp
in laravel
Laravel 6 use this code for file upload
if ($files = $request->file('image')) {
$path = $files->store('uploads/feedback');
}
$feedbackData = Feedback::create([
'name' => $request->name,
'image' => $path,
'state_country' => $request->state_country,
'feedback' => $request->feedback,
'status' => $request->status,
]);

How to add an entity content programmatically in drupal

Good night: I used to create node programmatically with a code similar to:
use Drupal\node\Entity\Node;
$nodeObj = Node::create([
'type' => 'article',
'title' => 'Programatically created Article',
'body' => "CodeExpertz is contains best Blogs.",
'field_date' => '2017-10-24',
'field_category' => 'Study',
'uid' => 1,
]);
$nodeObj->save(); // Saving the Node object.
$nid = $nodeObj->id(); // Get Nid from the node object.
Print "Node Id is " . $nid;
Now I want to create entities content (no nodes) but I can't find something about this. I tried to adapt the next snippet:
$term = \Drupal\taxonomy\Entity\Term::create([
'vid' => 'test_vocabulary',
'name' => 'My tag',
]);
$term->save();
to this (vehicle is my entity):
$newvehicle = \Drupal\vehicle\Entity\Vehicle::create([
'title' => 'Ferrari'
]);
$newvehicle->save();
The result is the white page of death.
Thanks for your help.
I was able to do it with this code
use Drupal\customModule\Entity\entityCustom;
$entityCustom = entityCustom::create([
'type' => 'custom_entity',
'uid' => 1,
'status' => TRUE,
'promote' => 0,
'created' => time(),
'langcode' => 'en',
'name' => 'NAME',
]);
$entityCustom->save();

install.php is not being run during installation

My install.php is not being run during installation.I checked everywhere.To be sure,I ran the code in install.php elsewhere and it worked well. But during installation only the install.php is being skipped somehow.My module name is Hotelreservation, hence the code in install.php is as below. Why is there no error display during installation ?
<?php
class Hotelreservation_Installer extends Engine_Package_Installer_Module
{
public function onInstall()
{
$this->_hotelroomsBrowsePage();
parent::onInstall();
}
protected function _hotelroomsBrowsePage()
{
$db = $this->getDb();
// profile page
$page_id = $db->select()
->from('engine4_core_pages', 'page_id')
->where('name = ?', 'hotelreservation_index_browse')
->limit(1)
->query()
->fetchColumn();
if (!$page_id) {
// Insert page
$db->insert('engine4_core_pages', array(
'name' => 'hotelreservation_index_browse',
'displayname' => 'HotelRooms Browse Page',
'title' => 'Browse Rooms',
'description' => 'this page displays rooms',
'custom' => 0,
));
$page_id = $db->lastInsertId();
// Insert main
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'main',
'page_id' => $page_id,
));
$main_id = $db->lastInsertId();
// Insert middle
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'middle',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 2,
));
$middle_id = $db->lastInsertId();
// Insert hotelreservation.browse-menu
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'hotelreservation.browse-menu',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 1,
));
// Insert core content
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'core.content',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 2,
));
// Insert left
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'left',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 3,
));
$left_id = $db->lastInsertId();
}
return $this;
}
}// end class
Did you add info to mainfest file like this in packages array
'callback' => array(
'path' => 'Your path to php file',
'class' => 'Hotelreservation_Installer',
),
I agree with Arif. Check the file manifest.php inside of //settings:
(info of module Album)
'callback' => array(
'path' => 'application/modules/Album/settings/install.php',
'class' => 'Album_Installer',
),
I had this same issue and got it to work.
It turns out that the installer looks in application/packages/module-yourmodule-x.x.x.json first. around line 35 you'll find:
"callback": {
"path": null,
"class": "Engine_Package_Installer_Module",
"priority": 100
},
change that to:
"callback": {
"path": "application/modules/Yourmodule/settings/install.php",
"class": "Yourmodule_Installer",
"priority": 100
},
now, when you run the installer, your install.php will be called.