Use custom field checkbox in admin product page - PrestaShop 1.6 - prestashop

I have a custom field (checkbox) in the product admin page:
Informations.tpl:
<div class="form-group">
<div class="col-lg-1">
<span class="pull-right">{include file="controllers/products/multishop/checkbox.tpl" field="is_exclusive" type="checkbox" multilang="false"}</span></div>
<label class="control-label col-lg-2" for="is_exclusive">
<span class="label-tooltip" data-toggle="tooltip" title="{l s='Is Exclusive'}">
{l s='Is Exclusive ?'}
</span>
</label>
<div class="col-lg-9">
<input class="admin-form-check form-control" type="checkbox" id="is_exclusive" name="is_exclusive" value="1" {if $product->is_exclusive}checked{/if}/>
</div>
</div>
And have added it to override/classes/Product.php:
public $is_exclusive = false;
function __construct( $id_product = null, $full = false, $id_lang = null, $id_shop = null, Context $context = null ) {
Product::$definition['fields']['is_exclusive'] =
array('type' => self::TYPE_BOOL, 'lang' => false, 'validate' => 'isBool');
I need a way to catch when the checkbox is unchecked and assign the field with 0.
I have created override/controllers/admin/AdminProductsController.php:
class AdminProductsController extends AdminProductsControllerCore {
protected function copyFromPost(&$object, $table) {
if ( $this->isTabSubmitted( 'Informations' ) ) {
if ( $this->checkMultishopBox( 'is_exclusive', $this->context ) ) {
$object->is_exclusive = (int) Tools::getValue( 'is_exclusive' );
}
}
}
}
But this doesn't do the trick.

The solution is to delete cache file: cache/class_index.php.

Yes in Prestashopp 1.6 => The solution is to delete cache file: cache/class_index.php
In prestashop 1.7 => The solution is to delete cache file: var/cache/class_index.php
Regards

Related

how can i edit a room reservation in laravel 8.the update on the controller does not work

controller(update) :as you can see in the update i'm trying to edit the room reservation(time and date),but onlly one part work the if or the else!
public function update(Request $request, Roomreservation $roomreservation)
{
$request->validate([
'date' => 'required',
'time' => 'required',
]);
$roomreservation = Roomreservation::where('date', request('date'))->where('time', request('time'))->where('code_room', request('code_room'));
if ($roomreservation->exists()) {
return back()->with('erreur', 'The chosen room is already reserved');
}
else {
$roomreservation->update([
"date" => $request->date,
"time" => $request->time,
]);
return back()->with('message_sent', 'room reservation edited successfully!');
}
}
my form
<form method="post" action="{{ route('admin.roomreservations.update', $roomreservation->id) }}">
#csrf
#method('PUT') #method('PUT')
<div>
<div>
<label for="date">Date</label>
<input type="date" min="2022-01-01" max="2022-12-31" name="date" id="date"
value="{{ old('date', $roomreservation->date) }}" />
</div>
<div>
<label for="time">Time</label>
<select name="time" id="time"
value="{{ old('time',$roomreservation->time) }}" >
<option>8H30-10H00</option>
<option>10H00-11H30</option>
<option>11H30-13H00</option>
</select>
</div>
<div>
<button>
Edit
</button>
</div>
</div>
</form>
button update on the index form
<a href="{{ route('admin.roomreservations.edit', $roomreservation->id) }}" >Update</a>
i think something is wrong on the update condition
$roomreservation = Roomreservation::where('date', request('date'))->where('time', request('time'))->where('code_room', request('code_room'));
if ($roomreservation->exists())
It seems that you're passing a wrong parameter
Change your update function to the below
public function update(Request $request, $id)
{
$request->validate([
'date' => 'required',
'time' => 'required',
]);
$roomreservation = Roomreservation::find($id);
if ($roomreservation == null) {
return back()->with('erreur', 'The chosen room does not exist');
}
if ($roomreservation->date == $request->date && $roomreservation->time == $request->time && $roomreservation->code_room == $request->code_room) {
return back()->with('erreur', 'The chosen room is already reserved');
}
else {
$roomreservation->update([
"date" => $request->date,
"time" => $request->time,
]);
return back()->with('message_sent', 'room reservation edited successfully!');
}
}

405 Method Not Allowed response: { "message": "The GET method is not supported for this route. Supported methods: POST."}

I created an API with tymon/jwt-auth, I test it on POSTMAN and it works very well, but when I want to consume it with Guzzle I encountered this error :
GuzzleHttp\Exception\ClientException Client error: POST http://localhost/project/public/api/stands/1/images2/ resulted in a
405 Method Not Allowed response: { "message": "The GET method is not
supported for this route. Supported methods: POST.", "exception":
"Symfony\ (truncated...)
Route for API :
Route::post('stands/{id}/images2', 'ImageController#store');
Controller ImageController.php for API :
public function store(Request $request, $id) {
$validator = Validator::make($request->all(),
[
'nom' => 'required|mimes:jpeg,png'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
if ($files = $request->file('nom'))
{
$path = public_path() . '/images/';
$files->move($path, $files->getClientOriginalName() );
$image = new Image();
$image->nom = $files->getClientOriginalName();
// $image->stand_id= $request->stand_id;
$stand = $this->user->stands()->find($id);
if ($stand->images()->save($image)){
return response()->json([
'success' => true,
"message" => "File successfully uploaded"
]);
$image->save();
}
else{
return response()->json([
'success' => false,
'message' => 'Sorry, image could not be added'
], 500);
}
}
}
Form :
<form method="POST" enctype="multipart/form-data" action="{{ route('postImage',request()->route('id')) }}">
{{ csrf_field() }}
{{ method_field("post")}}
<!--begin::Card-->
<div class="card card-custom gutter-b example example-compact">
<div class="card-header">
<div class="card-title">
<h3 class="card-label">
Upload
</h3>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="box-browse" >
<div class="custom-file">
<input type="file" name="nom" class="custom-file-input" id="inputGroupFile01">
</div>
<div class="content-upload">
<i class="fa fa-download" aria-hidden="true"></i>
</div>
<span class="form-text text-muted">Allowed file types: png, jpg,
jpeg.</span>
<!-- <div class="custom-file">
<label class="custom-file-label" for="customFile">Choose
file</label>
</div> -->
</div>
</div>
</div>
</div>
</div>
<!--end::Card-->
<input type="submit" name="submit" value="ok" />
</form>
Controller Admin\ImageController.php that consumes API for upload file :
public function store(Request $request, $id){
$file = $request->file('nom');
$file_path = $file->getPathname();
$file_mime = $file->getMimeType('image');
$file_uploaded_name = $file->getClientOriginalName();
$url = "http://localhost/project/public/api/stands/".$id."/images2/";
$client = new \GuzzleHttp\Client();
try {
$response = $client->post($url,
[
'multipart' => [
[
'name' => 'nom',
'filename' => $file_uploaded_name,
'Content-Type' => 'multipart/form_data',
'contents' => fopen($file_path, 'r'),]
],
'headers' =>
[
'Authorization' => 'Bearer '.Session::get('token'),
'Accept' => 'application/json',
'Content-Type' => 'multipart/form_data',
]
]);
} catch (Exception $e) {
}
the route :
Route::post('/stands/{id}/images2/', 'Admin\ImageController#store')->name('postImage');

Prestashop after submit return page html

Hello I develop a module under Prestashop 1.6 and I am blocked on the submission of a form.
I add in my module a form with the hook "DisplayAdminOrderContentShip" which retrieves a tpl hook_button.tpl which displays my form (button)
relance
here is my tpl:
<div class="panel panel-default">
<div class="panel-heading">
<p>Export commande mecalux</p>
</div>
<div class="panel-body">
<p>Permet de relancer l'export vers Mecalux de la commande</p>
<form method="POST" action="#">
<button type="submit" value="1" id="exportordersubmit" name="exportordersubmit" class="btn btn-default pull-right">
<i class="process-icon-refresh"></i> {l s='Relancer l\'export' mod='exportorders'}
</button>
</form>
</div>
Here is my function:
public function hookDisplayAdminOrderContentShip($params)
{
$order = new Order(Tools::getValue('id_order'));
$status = (int)Configuration::get('EXPORTORDERS_STATUS_TRANSFERED_TO_WMS');
$statusError = (int)Configuration::get('EXPORTORDERS_STATUS_CMD_ERROR');
if (Tools::isSubmit('exportordersubmit')) {
if (isset($order) && (int)$order->valid == 1) {
if ($order->current_state != $status && $order->current_state != $statusError) {
return;
}
if (!$order->valid) {
return;
}
$customer = $order->getCustomer();
$deliveryAddress = new Address($order->id_address_delivery);
$id_country_delivery = $deliveryAddress->getCountryAndState($order->id_address_delivery);
$iso = new Country();
$userXml = [
'id_client' => $customer->id,
'email' => $customer->email,
'livraison' => $deliveryAddress,
'country_code_delivery' => $iso->getIsoById($id_country_delivery['id_country'])
];
$dateOrder = new DateTime($order->date_add);
$orderXml = [
'id' => $order->id,
'sorCode' => $order->reference,
'payment' => $order->payment,
'date' => $dateOrder->format('Y-m-d\TH:i:s') . 'Z',
];
$result = $this->fileXml($userXml, $orderXml, $order->getProducts());
if ((int)$result === 1) {
$order->setCurrentState($statusError, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$html = [
'message' => $this->displayError('Erreur de transmission au WMS'),
];
} else {
if ((int)$order->current_state !== (int)$status) {
$order->setCurrentState($status, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$order->wms_transfered = 1;
$order->save();
$html = [
'message' => $this->displayConfirmation('Transmise au WMS'),
];
}
}
}
}
$this->context->smarty->assign(
array(
'alert' => $html
)
);
return ($this->display(__FILE__, 'views/templates/hook/hook_button.tpl'));
}
and when I click here is the result of my page:
html
normally it should return an alert in the order detail page (admin) I do not see where my problem comes from have any idea?
Thank you for your help.
fetch

How fix not working ActionResult Update in NET Core?

I'm learning about .NET Core and I'm using code from this tutorial. But my update sql is not working.
Here is the index view code:
public ActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = db.Chars.ToList();
Chars Chars = db.Chars.Find(id);
return View(Chars);
}
As for now it work I see results from sql and here is the updated part:
public ActionResult Update(Chars Chars)
{
if (ModelState.IsValid)
{
db.Entry(Chars).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
Here is index.cshtml part:
#using (Html.BeginForm()
{
#foreach (var item in (IEnumerable<MVC__test_2.Chars>)ViewBag.Name)
{
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(modelItem => item.CharName, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(modelItem => item.CharID, new { id = item.CharID })
</div>
</div>
#Html.ActionLink("Index", "Index", new { id = item.CharID })
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
}
}
According to the tutorial you provided , I made a demo to test and it updated the data well. The following is the working example , you could refer to and make the modification as per your need .
Model
public class Description
{
public int Id { get; set; }
public string Display { get; set; }
}
Controller
public IActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = _context.Description.ToList();
Description description= _context.Description.Find(id);
return View(description);
}
public ActionResult Update(Description description)
{
if (ModelState.IsValid)
{
_context.Entry(description).State = EntityState.Modified;
_context.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
Index.cshtml , you should hide the id of the modified data in the modification section.
#model WebApplication1.Models.Description
#using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
#foreach (var item in (IEnumerable<WebApplication1.Models.Description >)ViewBag.Name)
{
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(modelItem => item.Display, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(modelItem => item.Id, new { id = item.Id })
</div>
</div>
#Html.ActionLink("Edit", "Index", new { id = item.Id })
}
// Create or Update data
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<fieldset>
<legend> <b>Entry Screen</b></legend>
<div class="form-group">
#Html.LabelFor(model => model.Display, new { #class = "control-label col-md-2" })
#Html.HiddenFor(model => model.Id)
<div class="col-md-10">
#Html.EditorFor(model => model.Display)
#Html.ValidationMessageFor(model => model.Display)
</div>
</div>
<div class="form-group">
<p>
<input type="submit" value="Create" name="Create"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
</p>
</div>
</fieldset>
</div>
}

Symfony 3 form + Aurelia

So i've playing around with building a web app in Symfony 3, using a form type and rendering the form on the page. I am starting to Aurelia, and am trying to render a Symfony form on the page via an Aurelia custom element, and then post the form back to symfony. I've gotten to the point of validating the form upon submit, but it never validates. Can someone please look over the below code and see if i'm missing something somewhere?
Form type:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Service\PayeeService;
class PayeeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('category', ChoiceType::class, [
'choices' => [
'Uncategorized' => PayeeService::CATEGORY_UNCATEGORIZED,
'Installment Loan' => PayeeService::CATEGORY_INSTALLMENT_LOAN,
'Credit Card' => PayeeService::CATEGORY_CREDIT_CARD,
'Utility' => PayeeService::CATEGORY_UTILITY,
'Mortgage' => PayeeService::CATEGORY_MORTGAGE,
'Entertainment' => PayeeService::CATEGORY_ENTERTAINMENT
],
'choices_as_values' => true
])
->add('amount', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('frequency', ChoiceType::class, [
'choices' => [
'Recurring' => PayeeService::FREQUENCY_RECURRING,
'One-time' => PayeeService::FREQUENCY_ONETIME
],
'choices_as_values' => true
])
->add('method', ChoiceType::class, [
'choices' => [
'ACH' => PayeeService::PAY_METHOD_ACH,
'Check' => PayeeService::PAY_METHOD_CHECK
],
'choices_as_values' => true
])
->add('dateLastPaid', DateType::class)
->add('dueDate', DateType::class)
->add('gracePeriod', IntegerType::class)
->add('balance', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('active', CheckboxType::class, ['label' => 'Active', 'data' => true])
->add('save', SubmitType::class, ['label' => 'Save Payee'])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Payee'
));
}
}
Controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
class FormController extends Controller
{
/**
* #Route("/_form/entity/{entity}", name="new_entity_form")
* #Method("GET")
*/
public function getFormForNewEntity(Request $request)
{
$rawName = $request->get('entity');
$content = $request->getContent();
$data = json_decode($content, true);
$formName = strtolower($rawName) . "_form";
$submitFunction = $data['submitFunction'];
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
return $this->render('form/form.html.twig', [
'name' => $formName,
'form' => $form->createView(),
'submitFunction' => $submitFunction]);
}
/**
* #Route("/_form/entity/{entity}", name="new_entity_create")
* #Method("POST")
*/
public function saveFormForNewEntity(Request $request)
{
$em = $this->getDoctrine()->getManager();
$rawName = $request->get('entity');
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return new JsonResponse(['result' => true]);
} elseif ($form->isEmpty()) {
return new JsonResponse(['result' => false, 'errors' => 'form empty']);
} else {
return new JsonResponse(['result' => false, 'errors' => iterator_to_array($form->getErrors(true))]);
}
}
}
Form twig:
{{ form_start(form, {'attr': {'id':name, 'role':'form', 'submit.delegate':submitFunction}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Aurelia component js:
import {InlineViewStrategy} from 'aurelia-framework';
import {customElement, bindable, inject} from 'aurelia-framework';
import $ from 'jquery';
import {HttpClient} from 'aurelia-http-client';
import 'fetch';
#customElement('symfony-form')
#inject(Element)
export class SymfonyForm {
#bindable entity;
constructor(element) {
this.content = '';
this.http = new HttpClient();
this.http.configure(config => {
config
.withBaseUrl('http://localhost:8000/');
});
this.element = element;
}
bind(binding, override) {
return this.http.get('_form/entity/' + this.entity, {'submitFunction': 'submit()'})
//.then(response => response.html())
.then(response => {
this.content = response.response;
});
}
submit() {
// application/x-www-form-urlencoded
this.http.createRequest('_form/entity/' + this.entity)
.withHeader('Content-Type', 'application/x-www-form-urlencoded')
.asPost()
.withContent($(this.element).find('form').serialize())
.send()
.then(response => {
alert(response.response);
});
//alert('submitted ' + this.entity);
// return this.http.post('_form/entity/' + this.entity, $(this.element).find('form').serialize())
// .then(response => {
// alert(response.response);
// });
}
}
aurelia component view:
<template>
<form role="form" submit.delegate="submit()">
<div innerHTML.bind="content"></div>
</form>
</template>
aurelia page:
<template>
<require from="form"></require>
<section class="au-animate">
<h2>${heading}</h2>
<form role="form" submit.delegate="submit()">
<div class="form-group">
<label for="fn">First Name</label>
<input type="text" value.bind="firstName" class="form-control" id="fn" placeholder="first name">
</div>
<div class="form-group">
<label for="ln">Last Name</label>
<input type="text" value.bind="lastName" class="form-control" id="ln" placeholder="last name">
</div>
<div class="form-group">
<label>Full Name</label>
<p class="help-block">${fullName | upper}</p>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<symfony-form entity="Payee"></symfony-form>
</section>
</template>
I'm not an expert on SPAs, or JS frameworks, but from what I can see the problem is the lack of a CSFR field with the correct token and also that I don't believe your inputs are named correctly for symphony to read them correctly (I may have missed where this is handled so apologies if so). You need to have the input name formatted as below:
<input type="text" name="formname[formfield]" />
So for example I believe you need your name field to be:
<input type="text" name="payeetype[name]" />