Error uploading an image in symfony 3.4 - image

I'm trying to upload an image in symfony 3, but when i execute my controller display me this error message "Call to a member function guessExtension() on string ". Before the image was stored in my directory web/uploads/images only and not in my database. And when i try to fix this problem, i have this error.
This is my entity:
namespace Doctix\MedecinBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
/**
* Media
*
* #ORM\Table(name="media")
* #ORM\Entity(repositoryClass="Doctix\MedecinBundle\Repository\MediaRepository")
* #ORM\HasLifecycleCallbacks
*/
class Media
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Ajouter une image valide")
* #Assert\File(mimeTypes={ "image/jpeg", "image/png", "image/gif" })
*/
private $image;
// On ajoute cet attribut pour y stocker le nom du fichier temporairement
private $tempFilename;
// On modifie le setter de File, pour prendre en compte l'upload d'un
fichier
lorsqu'il en existe déjà un autre
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
return $this;
// On vérifie si on avait déjà un fichier pour cette entité
if (null !== $this->url) {
// On sauvegarde l'extension du fichier pour le supprimer plus tard
$this->tempFilename = $this->url;
// On réinitialise les valeurs des attributs url et alt
$this->url = null;
$this->alt = null;
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Le nom du fichier est son id, on doit juste stocker également son
extension
// Pour faire propre, on devrait renommer cet attribut en « extension »,
plutôt que « url »
$this->url = $this->image->guessExtension(); **Error location**
// Et on génère l'attribut alt de la balise <img>, à la valeur du nom du
fichier sur le PC de l'internaute
$this->alt = $this->image->getClientOriginalName();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Si on avait un ancien fichier, on le supprime
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this-
>tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
// On déplace le fichier envoyé dans le répertoire de notre choix
$this->image->move(
$this->getUploadRootDir(), // Le répertoire de destination
$this->id.'.'.$this->url // Le nom du fichier à créer, ici « id.extension
»
);
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload(){
// On sauvegarde temporairement le nom du fichier, car il dépend de l'id
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload(){
// En PostRemove, on n'a pas accès à l'id, on utilise notre nom sauvegardé
if (file_exists($this->tempFilename)) {
// On supprime le fichier
unlink($this->tempFilename);
}
}
public function getUploadDir(){
// On retourne le chemin relatif vers l'image pour un navigateur
return 'uploads/images';
}
protected function getUploadRootDir(){
// On retourne le chemin relatif vers l'image pour notre code PHP
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath(){
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
*
* #return Media
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set alt
*
* #param string $alt
*
* #return Media
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
}
Then my controller:
public function mediaEditAction(Request $request){
$media = new Media();
$form = $this->createForm(MediaType::class, $media);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $media->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('images_directory'),
$fileName
);
$media->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
$request->getSession()->getFlashBag()->add('Notice', 'Photo ajoutée
avec succès');
// redirection
$url = $this->generateUrl('medecin_parametre');
// redirection permanente avec le status http 301 ::)))))
return $this->redirect($url,301);
}else{
return $this-
>render('DoctixMedecinBundle:Medecin:mediaedit.html.twig', array(
'form' => $form->createView()
));
}
}
Thanks.

Тhe image property of your entity is a string, so it is normal to get the error.
If you want to use guess extension you can use like following:
use Symfony\Component\HttpFoundation\File\File;
$file = new File($this->getUploadRootDir() . '/' . $this->image);
$this->url = $file->guessExtension();

Related

Multiple conditional in Laravel Middleware

I have a middleware like this:
class HasBilling {
public function handle($request, Closure $next) {
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (!is_object($user_profile) && !\Auth::user()->hasPermissionTo('soy-agente') && !\Auth::user()->hasPermissionTo('soy-agente_inversor')) {
return redirect()->route('myaccount.facturacion.ver')->with('error', 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.');
}
if(is_object($user_profile) && is_null($user_profile->validate)){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación están pendiente de validar');
}
if(is_object($user_profile) && $user_profile->validate == 2){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación han sido rechazados.');
}
if(!is_null(\Auth::user()->activity) && \Auth::user()->activity == "empresa"){
$autorizado = UsersProfileAutorizado::find($user_profile->id);
if(!is_object($autorizado)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'No posees ningún autorizado. Al ser una empresa, antes de usar algunas funciones como la facturación o la publicidad debes rellenar los datos de autorizado.');
}
if(is_object($autorizado) && is_null($autorizado->validate)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado está pendiente de validar.');
}
if(is_object($autorizado) && $autorizado->validate == 2){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado ha sido rechazado.');
}
}
return $next($request);
}
}
The problem with this is that it checks the first IF, but the others are omitted.
The middleware works because the first if always checks for it, but the rest "ignore" them.
How can i fix that?
You could store the errors in an array, and redirect at the end of the method.
class HasBilling {
public function handle($request, Closure $next) {
$errors = [];
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (
!is_object($user_profile)
&& !\Auth::user()->hasPermissionTo('soy-agente')
&& !\Auth::user()->hasPermissionTo('soy-agente_inversor')
) {
$errors[] = 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.';
}
if (
is_object($user_profile)
&& is_null($user_profile->validate)
){
$errors[] = 'Tus datos de facturación están pendiente de validar');
}
// Add other checks where you can append $errors array
if (count($errors) > 0) {
return redirect()
->route('myaccount.facturacion.ver')
->with('errors', $errors);
}
return $next($request);
}
}
When reading the errors in the 'myaccount.autorizado.ver route, you have to make sure to read, parse and show the $errors array instead of the single error. For example in a foreach that shows a list of errors.

PayPal - Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAYID-L6ZZRNY2CA2198940171953X/execute

I am using the SAME code that I use on another platform, but the difference is that here I use euros.
I have created a different PayPal account, which is also in euros.
private $_api_context;
public function __construct()
{
//setup PayPal api context
$paypal_conf = \Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_api_context->setConfig($paypal_conf['settings']);
}
public function postPayment()
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$items = array();
$subtotal = 0;
$cart = \Session::get('cart');
$currency = 'EUR';
//PEDIDO ACTUAL
$pedidoActual = DB::table('pedido as pe')
->select('pe.subtotal')
->where('pe.idpedido','=',$cart['idpedido'])
->first();
$monto = number_format($pedidoActual->subtotal,2);
$item = new Item();
$item->setName("Pedido de Momento Mágico")
->setCurrency($currency)
->setDescription("Entrega a domicilio incluido")
->setQuantity(1)
->setPrice($monto);
$items[] = $item;
$subtotal = $monto;
///////////////
$item_list = new ItemList();
$item_list->setItems($items);
//Nos sirve si queremos agregar un costo por el envío
$details = new Details();
$subtotal = $subtotal;
$details->setSubtotal($subtotal)
->setShipping(0);
//Es el objeto que tiene la moneda, el detalle a pagar y envio
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($subtotal)
->setDetails($details);
//Los datos de la transacción
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Pedido de Prueba en App Store');
//Recibe la ruta si se realiza o se cancela el pago
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(\URL::route('payment.status'))
->setCancelUrl(\URL::route('payment.status'));
//A traves del objeto Payment creamos el pago
$payment = new Payment();
$payment->setIntent('Sale') //De tipo Venta directa, puede ser de otros tipos
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
//Enviamos el pago y si hay errores lo mostramos en el Debug
try
{
$payment->create($this->_api_context);
}
catch (\PayPal\Exception\PPConnectionException $ex) {
if (\Config::get('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
exit;
} else {
die('Ups! Algo salió mal');
}
}
// Si todo salió bien, Paypal nos devuelve información
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// add payment ID to session // para darle seguimiento al usuario que lo hizo
\Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return \Redirect::away($redirect_url);
}
return \Redirect::route('home')
->with('error', 'Ups! Error desconocido.');
}
public function getPaymentStatus(Request $request)
{
// Get the payment ID before session clear
$payment_id = \Session::get('paypal_payment_id');
$cart = \Session::get('cart');
// clear the session payment ID
\Session::forget('paypal_payment_id');
$input = $request->all();
$payerId = Arr::except($input,array('PayerID'));
$token = Arr::except($input,array('token'));
//$payerId = \Input::get('PayerID');
//$token = \Input::get('token');
//if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
if (empty($payerId) || empty($token) || empty($payment_id)) {
$notificarError = (new MailController)->errorPagoPaypal();
return \Redirect::route('home')
->with('message', 'Hubo un problema al intentar pagar con Paypal');
}
//Si se pudo realizar el pago
$payment = Payment::get($payment_id, $this->_api_context);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($payerId);
//Execute the payment
$result = $payment->execute($execution, $this->_api_context);
//echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later
if ($result->getState() == 'approved') { // payment made
// Eliminar carrito
// Enviar correo a user
$fecha_prog_envio = (new CartController)->obtenerFechaEnvio($cart['tipo_producto']);
// Enviar correo a user
$notificarPagoPayPal = (new MailController)->notificarPagoIngresado($fecha_prog_envio,'PayPal');
$this->saveOrder(\Session::get('cart'),$fecha_prog_envio);
\Session::forget('cart');
return \Redirect::route('home')
->with('message', 'Pago realizado correctamente.');
}
return \Redirect::route('home')
->with('message', 'La compra fue cancelada');
}
I have already read all the forums, checked the amounts are correct and it doesn't work.
It is not an authentication issue as I have tried to connect to the other platform and the error is the same.
I imagine that the error may come from the currency exchange, the total amount. But I have not found the error.
$execution->setPayerId($payerId);
What is the value of $payerId at this stage of using it? Log it.
It's supposed to be a plain string value, but your code before this where you set and check payerId looks funny, I don't trust the value.

Laravel: The cart does not contain rowId ce5452f389f041ab17e46324cc050c0d

My code works perfect on the local machine, i deployed but the delete, add and update function do not work well that is why i get the following errow "The cart does not contain rowId ce5452f389f041ab17e46324cc050c0d."
Here is my controller
public function index()
{
$cartItems=Cart::content();
return view('cart.index',compact('cartItems'));
}
public function addItem($id)
{
$product=Product::find($id);
Cart::add($id,$product->name,1,$product->price,['size'=>'medium']);
return back();
}
public function update(Request $request, $id)
{
// dd(Cart::content());
// dd($request->all());
Cart::update($id,['qty'=>$request->qty,"options"=>['size'=>$request->size]]);
return back();
}
public function destroy($id)
{
Cart::remove($id);
return back();
}
MY "MODEL" please be patient with me, i only seek understanding if i appear to be some sort of slow
namespace Gloudemans\Shoppingcart;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Session\SessionManager;
use Illuminate\Database\DatabaseManager;
use Illuminate\Contracts\Events\Dispatcher;
use Gloudemans\Shoppingcart\Contracts\Buyable;
use Gloudemans\Shoppingcart\Exceptions\UnknownModelException;
use Gloudemans\Shoppingcart\Exceptions\InvalidRowIDException;
use Gloudemans\Shoppingcart\Exceptions\CartAlreadyStoredException;
class Cart
{
const DEFAULT_INSTANCE = 'default';
/**
* Instance of the session manager.
*
* #var \Illuminate\Session\SessionManager
*/
private $session;
/**
* Instance of the event dispatcher.
*
* #var \Illuminate\Contracts\Events\Dispatcher
*/
private $events;
/**
* Holds the current cart instance.
*
* #var string
*/
private $instance;
/**
* Cart constructor.
*
* #param \Illuminate\Session\SessionManager $session
* #param \Illuminate\Contracts\Events\Dispatcher $events
*/
public function __construct(SessionManager $session, Dispatcher $events)
{
$this->session = $session;
$this->events = $events;
$this->instance(self::DEFAULT_INSTANCE);
}
/**
* Set the current cart instance.
*
* #param string|null $instance
* #return \Gloudemans\Shoppingcart\Cart
*/
public function instance($instance = null)
{
$instance = $instance ?: self::DEFAULT_INSTANCE;
$this->instance = sprintf('%s.%s', 'cart', $instance);
return $this;
}
/**
* Get the current cart instance.
*
* #return string
*/
public function currentInstance()
{
return str_replace('cart.', '', $this->instance);
}
/**
* Add an item to the cart.
*
* #param mixed $id
* #param mixed $name
* #param int|float $qty
* #param float $price
* #param array $options
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function add($id, $name = null, $qty = null, $price = null, array $options = [])
{
if ($this->isMulti($id)) {
return array_map(function ($item) {
return $this->add($item);
}, $id);
}
$cartItem = $this->createCartItem($id, $name, $qty, $price, $options);
$content = $this->getContent();
if ($content->has($cartItem->rowId)) {
$cartItem->qty += $content->get($cartItem->rowId)->qty;
}
$content->put($cartItem->rowId, $cartItem);
$this->events->fire('cart.added', $cartItem);
$this->session->put($this->instance, $content);
return $cartItem;
}
/**
* Update the cart item with the given rowId.
*
* #param string $rowId
* #param mixed $qty
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function update($rowId, $qty)
{
$cartItem = $this->get($rowId);
if ($qty instanceof Buyable) {
$cartItem->updateFromBuyable($qty);
} elseif (is_array($qty)) {
$cartItem->updateFromArray($qty);
} else {
$cartItem->qty = $qty;
}
$content = $this->getContent();
if ($rowId !== $cartItem->rowId) {
$content->pull($rowId);
if ($content->has($cartItem->rowId)) {
$existingCartItem = $this->get($cartItem->rowId);
$cartItem->setQuantity($existingCartItem->qty + $cartItem->qty);
}
}
if ($cartItem->qty <= 0) {
$this->remove($cartItem->rowId);
return;
} else {
$content->put($cartItem->rowId, $cartItem);
}
$this->events->fire('cart.updated', $cartItem);
$this->session->put($this->instance, $content);
return $cartItem;
}
/**
* Remove the cart item with the given rowId from the cart.
*
* #param string $rowId
* #return void
*/
public function remove($rowId)
{
$cartItem = $this->get($rowId);
$content = $this->getContent();
$content->pull($cartItem->rowId);
$this->events->fire('cart.removed', $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Get a cart item from the cart by its rowId.
*
* #param string $rowId
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function get($rowId)
{
$content = $this->getContent();
if ( ! $content->has($rowId))
throw new InvalidRowIDException("The cart does not contain rowId {$rowId}.");
return $content->get($rowId);
}
/**
* Destroy the current cart instance.
*
* #return void
*/
public function destroy()
{
$this->session->remove($this->instance);
}
/**
* Get the content of the cart.
*
* #return \Illuminate\Support\Collection
*/
public function content()
{
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
/**
* Get the number of items in the cart.
*
* #return int|float
*/
public function count()
{
$content = $this->getContent();
return $content->sum('qty');
}
/**
* Get the total price of the items in the cart.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
* #return string
*/
public function total($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$content = $this->getContent();
$total = $content->reduce(function ($total, CartItem $cartItem) {
return $total + ($cartItem->qty * $cartItem->priceTax);
}, 0);
return $this->numberFormat($total, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the total tax of the items in the cart.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
* #return float
*/
public function tax($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$content = $this->getContent();
$tax = $content->reduce(function ($tax, CartItem $cartItem) {
return $tax + ($cartItem->qty * $cartItem->tax);
}, 0);
return $this->numberFormat($tax, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the subtotal (total - tax) of the items in the cart.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
* #return float
*/
public function subtotal($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$content = $this->getContent();
$subTotal = $content->reduce(function ($subTotal, CartItem $cartItem) {
return $subTotal + ($cartItem->qty * $cartItem->price);
}, 0);
return $this->numberFormat($subTotal, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Search the cart content for a cart item matching the given search closure.
*
* #param \Closure $search
* #return \Illuminate\Support\Collection
*/
public function search(Closure $search)
{
$content = $this->getContent();
return $content->filter($search);
}
/**
* Associate the cart item with the given rowId with the given model.
*
* #param string $rowId
* #param mixed $model
* #return void
*/
public function associate($rowId, $model)
{
if(is_string($model) && ! class_exists($model)) {
throw new UnknownModelException("The supplied model {$model} does not exist.");
}
$cartItem = $this->get($rowId);
$cartItem->associate($model);
$content = $this->getContent();
$content->put($cartItem->rowId, $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Set the tax rate for the cart item with the given rowId.
*
* #param string $rowId
* #param int|float $taxRate
* #return void
*/
public function setTax($rowId, $taxRate)
{
$cartItem = $this->get($rowId);
$cartItem->setTaxRate($taxRate);
$content = $this->getContent();
$content->put($cartItem->rowId, $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Store an the current instance of the cart.
*
* #param mixed $identifier
* #return void
*/
public function store($identifier)
{
$content = $this->getContent();
if ($this->storedCartWithIdentifierExists($identifier)) {
throw new CartAlreadyStoredException("A cart with identifier {$identifier} was already stored.");
}
$this->getConnection()->table($this->getTableName())->insert([
'identifier' => $identifier,
'instance' => $this->currentInstance(),
'content' => serialize($content)
]);
$this->events->fire('cart.stored');
}
/**
* Restore the cart with the given identifier.
*
* #param mixed $identifier
* #return void
*/
public function restore($identifier)
{
if( ! $this->storedCartWithIdentifierExists($identifier)) {
return;
}
$stored = $this->getConnection()->table($this->getTableName())
->where('identifier', $identifier)->first();
$storedContent = unserialize($stored->content);
$currentInstance = $this->currentInstance();
$this->instance($stored->instance);
$content = $this->getContent();
foreach ($storedContent as $cartItem) {
$content->put($cartItem->rowId, $cartItem);
}
$this->events->fire('cart.restored');
$this->session->put($this->instance, $content);
$this->instance($currentInstance);
$this->getConnection()->table($this->getTableName())
->where('identifier', $identifier)->delete();
}
/**
* Magic method to make accessing the total, tax and subtotal properties possible.
*
* #param string $attribute
* #return float|null
*/
public function __get($attribute)
{
if($attribute === 'total') {
return $this->total();
}
if($attribute === 'tax') {
return $this->tax();
}
if($attribute === 'subtotal') {
return $this->subtotal();
}
return null;
}
/**
* Get the carts content, if there is no cart content set yet, return a new empty Collection
*
* #return \Illuminate\Support\Collection
*/
protected function getContent()
{
$content = $this->session->has($this->instance)
? $this->session->get($this->instance)
: new Collection;
return $content;
}
/**
* Create a new CartItem from the supplied attributes.
*
* #param mixed $id
* #param mixed $name
* #param int|float $qty
* #param float $price
* #param array $options
* #return \Gloudemans\Shoppingcart\CartItem
*/
private function createCartItem($id, $name, $qty, $price, array $options)
{
if ($id instanceof Buyable) {
$cartItem = CartItem::fromBuyable($id, $qty ?: []);
$cartItem->setQuantity($name ?: 1);
$cartItem->associate($id);
} elseif (is_array($id)) {
$cartItem = CartItem::fromArray($id);
$cartItem->setQuantity($id['qty']);
} else {
$cartItem = CartItem::fromAttributes($id, $name, $price, $options);
$cartItem->setQuantity($qty);
}
$cartItem->setTaxRate(config('cart.tax'));
return $cartItem;
}
/**
* Check if the item is a multidimensional array or an array of Buyables.
*
* #param mixed $item
* #return bool
*/
private function isMulti($item)
{
if ( ! is_array($item)) return false;
return is_array(head($item)) || head($item) instanceof Buyable;
}
/**
* #param $identifier
* #return bool
*/
private function storedCartWithIdentifierExists($identifier)
{
return $this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->exists();
}
/**
* Get the database connection.
*
* #return \Illuminate\Database\Connection
*/
private function getConnection()
{
$connectionName = $this->getConnectionName();
return app(DatabaseManager::class)->connection($connectionName);
}
/**
* Get the database table name.
*
* #return string
*/
private function getTableName()
{
return config('cart.database.table', 'shoppingcart');
}
/**
* Get the database connection name.
*
* #return string
*/
private function getConnectionName()
{
$connection = config('cart.database.connection');
return is_null($connection) ? config('database.default') : $connection;
}
/**
* Get the Formated number
*
* #param $value
* #param $decimals
* #param $decimalPoint
* #param $thousandSeperator
* #return string
*/
private function numberFormat($value, $decimals, $decimalPoint, $thousandSeperator)
{
if(is_null($decimals)){
$decimals = is_null(config('cart.format.decimals')) ? 2 : config('cart.format.decimals');
}
if(is_null($decimalPoint)){
$decimalPoint = is_null(config('cart.format.decimal_point')) ? '.' : config('cart.format.decimal_point');
}
if(is_null($thousandSeperator)){
$thousandSeperator = is_null(config('cart.format.thousand_seperator')) ? ',' : config('cart.format.thousand_seperator');
}
return number_format($value, $decimals, $decimalPoint, $thousandSeperator);
}
}
MY "VIEW"
#foreach($cartItems as $cartItem)
<tr>
<td style="border-style: solid">{{$cartItem->name}}</td>
<td style="border-style: solid">{{$cartItem->price}}</td>
<td style="border-style: solid">
{!! Form::open(['route' => ['cart.update',$cartItem->rowId], 'method' => 'PUT']) !!}
<input name="qty" type="text" value="{{$cartItem->qty}}">
</td>
<td style="border-style: solid">
<input style="float: left" type="submit" class="btn btn-success" value="Ok">
{!! Form::close() !!}
</td>
<td style="border-style: solid">
<form action="{{route('cart.destroy',$cartItem->rowId)}}" method="POST" >
{{csrf_field()}}
{{method_field('DELETE')}}
<input class="btn btn-danger" type="submit" value="Delete">
</form>
</td>
</tr>
#endforeach
My inspector shows the rowID, i can understand that the rowID is generated by the cart when i add the item but where to located this rowID is something different.
<tr>
<td style="border-style: solid">ASGHJSDFGHJDF</td>
<td style="border-style: solid">56</td>
<td style="border-style: solid">
<form method="POST" action="http://rorisangmaimane.co.za/cart/ce5452f389f041ab17e46324cc050c0d" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT"><input name="_token" type="hidden" value="iXJ3ncGwro7lVA07Mph4rbZloVF1UTQ0m8mlmpK6">
<input name="qty" type="text" value="2">
</td>
<td style="border-style: solid">
<input style="float: left" type="submit" class="btn btn-success" value="Ok">
</form>
</td>
<td style="border-style: solid">
<form action="http://rorisangmaimane.co.za/cart/ce5452f389f041ab17e46324cc050c0d" method="POST" >
<input type="hidden" name="_token" value="iXJ3ncGwro7lVA07Mph4rbZloVF1UTQ0m8mlmpK6">
<input type="hidden" name="_method" value="DELETE">
<input class="btn btn-danger" type="submit" value="Delete">
</form>
</td>
</tr>
I also face the same problem. But my problem happen when user click the update/remove button twice at a same time.
I solved the issue by following ways -
First check whether the rowId is available or not. Then implement actions -
$cart = Cart::content()->where('rowId',$id);
if($cart->isNotEmpty()){
Cart::remove($id);
}
Same way in the updated functions also.

Upload a pdf in Codeigniter

I want to upload a file from a form. It's working fine with .doc files but .pdf's don't work all the time. I'm not able to load my pdf named compositionFinale.pdf (3.67 MB)
I tried with another big pdf that was more than my $_FILES["size"] and I have an error that tells me:"Ce fichier est trop volumineux" (the file is too big).
But with compositionFinale.pdf that is also too big it doesn't pass in my
if ($_FILES["offre"]["size"] > 500000) (I put a echo to test). I don't have an error at the end and it tells me that the file is uploaded, but when I check in the file it is not.
EDIT: I tried to save this pdf as a reduced size pdf and when I upload my file it tells me that my file is too big. Which is fine. But why does not tell me it is too big when it was not reduced in size?
Is anyone see something I don't?
My controller
function publierOffreEmploi()
{
// validation
$this->form_validation->set_rules('poste', 'Poste', 'required|max_length[255]');
$this->form_validation->set_rules('ville', 'Ville', 'required|max_length[50]');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('secteurs[]', "Secteur(s) d'activité", 'required');
$this->form_validation->set_rules('date_fin_publication', 'Date de la fin de publication', 'required');
$this->form_validation->set_error_delimiters('<br /><span class="error erreur">', '</span>');
// si erreur dans la validation
if ($this->form_validation->run() == FALSE)
{
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view');
$this->_layoutBas();
}
// si aucune erreur dans la validation
else
{
// +++++++++++++++++++++++++++++++++++++++++++
$target_dir = "assets/uploads/";
$name = basename($_FILES["offre"]["name"]);
$target_file = $target_dir . basename($_FILES["offre"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$message = '';
// Si le formulaire a bien été envoyé
if(isset($_POST["submit"]))
{
// Vérifie si un fichier est bien sélectionné
if(($_FILES['offre']['name'])!= '')
{
$uploadOk = 1;
$pasDeFichier = "";
}
else
{
// définir le message d'erreur de l'image si le fichier choisi n'est pas une image
$uploadOk = 0;
$pasDeFichier = "Vous devez importer un fichier";
}
// si le fichier existe déja
if (file_exists($target_file))
{
// définir le message d'erreur de l'image si l'image existe déja dans le fichier de téléchargement
$uploadOk = 0;
$message.= "Ce fichier exite déja. Veillez le renommer<br>";
}
// si le fichier est plus gros que 500Ko
if ($_FILES["offre"]["size"] > 500000)
{
echo "too big";
die();
$uploadOk = 0;
// définir le message d'erreur si l'image est trop volumineuse
$message.= "Ce fichier est trop volumineux<br>";
}
// définir les formats autorisés
if($imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "DOC" && $imageFileType != "DOCX" && $imageFileType != "PDF")
{
// définir le message d'erreur si l'image n'est pas d'un format accepté
$uploadOk = 0;
$message.= "Seuls les fichiers .pdf, .doc et .docx sont acceptés";
}
// si erreur donc pas d'upload et retour au formulaire avec message d'erreur en fonction de l'erreur
if ($uploadOk == 0)
{
if ($pasDeFichier != "") {
$data=array();
$data["message"]= $pasDeFichier;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
else{
$data=array();
$data["message"]= $message;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
}
/*si l'image a été uploadé*/
else
{
if (move_uploaded_file($_FILES["offre"]["tmp_name"], $target_file)){
}
// Création d'une variable contenant le id de l'entreprise connectée
$idEntreprise = $this->entreprise_model->lire('id', $conditions = array('courriel' => $_SESSION["courriel_entreprise"]));
/*Transformer l'objet en tableau. Nous permet de stocker le id*/
$data=array();
$data["idEntreprise"]= $idEntreprise;
foreach ($idEntreprise as $id) {
}
// ------------------------------ CHECKBOX SECTEURS -----------------------------------------
// Récupération et concaténation des valeurs du checkbox multiple (secteurs)
//déclaration de la variable qui contiendra tous les secteurs
$secteurs ='';
//boucle afin d'optenir tous les secteurs
for ($i=0;$i<count($_POST['secteurs']);$i++)
{
//concaténation des champs
$secteurs .= $_POST['secteurs'][$i];
}
// données envoyées au modèle
$form_data = array(
'poste' => set_value('poste'),
'ville' => set_value('ville'),
'description' => set_value('description'),
'date_fin_publication' => set_value('date_fin_publication'),
'entreprise_id' => $id['id'],
'secteur' => $secteurs,
'type_offre_id' => 2,
'statut_offre_id' => 2,
'offre' => $name
);
// insertion dans la bd
// si l'insertion est un succes
if ($this->offre_model->inserer($form_data) == TRUE)
{
redirect('offre_controller/succes_publication_offre_emploi');
}
// si l'insertion est un echec
else
{
redirect('offre_controller/echec_publication_offre');
}
}
}
}
}
My pdf file
My form
<!-- UPLOAD DE L'OFFRE (PDF, DOC, DOCX) -->
<p>
<!-- affichage du message (gestion des messages d'erreurs) -->
<label for="offre" class="labelVisible labelFile">Veuillez importer votre offre d'emploi<span class="required"></span></label>
<?php echo form_error('offre'); ?>
<input id="offre" type="file" name="offre"/>
<br />
<?php
// si un mesasge d'erreur existe
if(isset($message))
{
?>
<span class="erreur"> <?php echo $message; ?></span>
<?php
}
?>
</p>
Thanks
I bet that PHP upload_max_filesize is set as default (2MB) you need to go to php.ini file and search for upload_max_filesize and change that to whatever you need (8MB, 32MB...). Also you need to set post_max_size to same size or higher.
I assume you are on Windows machine, running XAMPP, right click on icon and look for php.ini file open it and do your magic.

Magento admin : Fatal error: Call to a member function toOptionArray() on a non-object

I am getting error in admin panel after adding plugin.
Error :
Fatal error: Call to a member function toOptionArray() on a non-object in /var/lib/openshift/5374ca8999fc775bdc00009d/app-root/runtime/repo/php/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php on line 463
Here is the code :
public function toOptionArray() {
return array(
array('value'=>'0', 'label'=>'No Credit'),
array('value'=>'1', 'label'=>'Credit Only Invited Customer'),
array('value'=>'2', 'label'=>'Credit Only Customer who invite'),
array('value'=>'3', 'label'=>'Credit Both Customer')
);
Form.php file :
<?php
class Mage_Adminhtml_Block_System_Config_Form extends Mage_Adminhtml_Block_Widget_Form
{
const SCOPE_DEFAULT = 'default';
const SCOPE_WEBSITES = 'websites';
const SCOPE_STORES = 'stores';
/**
* Config data array
*
* #var array
*/
protected $_configData;
/**
* Adminhtml config data instance
*
* #var Mage_Adminhtml_Model_Config_Data
*/
protected $_configDataObject;
/**
* Enter description here...
*
* #var Varien_Simplexml_Element
*/
protected $_configRoot;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Model_Config
*/
protected $_configFields;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Fieldset
*/
protected $_defaultFieldsetRenderer;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Field
*/
protected $_defaultFieldRenderer;
/**
* Enter description here...
*
* #var array
*/
protected $_fieldsets = array();
/**
* Translated scope labels
*
* #var array
*/
protected $_scopeLabels = array();
/**
* Enter description here...
*
*/
public function __construct()
{
parent::__construct();
$this->_scopeLabels = array(
self::SCOPE_DEFAULT => Mage::helper('adminhtml')->__('[GLOBAL]'),
self::SCOPE_WEBSITES => Mage::helper('adminhtml')->__('[WEBSITE]'),
self::SCOPE_STORES => Mage::helper('adminhtml')->__('[STORE VIEW]'),
);
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
protected function _initObjects()
{
/** #var $_configDataObject Mage_Adminhtml_Model_Config_Data */
$this->_configDataObject = Mage::getSingleton('adminhtml/config_data');
$this->_configRoot = $this->_configDataObject->getConfigRoot();
$this->_configData = $this->_configDataObject->load();
$this->_configFields = Mage::getSingleton('adminhtml/config');
$this->_defaultFieldsetRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_fieldset');
$this->_defaultFieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
return $this;
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initForm()
{
$this->_initObjects();
$form = new Varien_Data_Form();
$sections = $this->_configFields->getSection(
$this->getSectionCode(),
$this->getWebsiteCode(),
$this->getStoreCode()
);
if (empty($sections)) {
$sections = array();
}
foreach ($sections as $section) {
/* #var $section Varien_Simplexml_Element */
if (!$this->_canShowField($section)) {
continue;
}
foreach ($section->groups as $groups){
$groups = (array)$groups;
usort($groups, array($this, '_sortForm'));
foreach ($groups as $group){
/* #var $group Varien_Simplexml_Element */
if (!$this->_canShowField($group)) {
continue;
}
$this->_initGroup($form, $group, $section);
}
}
}
$this->setForm($form);
return $this;
}
/**
* Init config group
*
* #param Varien_Data_Form $form
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param Varien_Data_Form_Element_Fieldset|null $parentElement
*/
protected function _initGroup($form, $group, $section, $parentElement = null)
{
if ($group->frontend_model) {
$fieldsetRenderer = Mage::getBlockSingleton((string)$group->frontend_model);
} else {
$fieldsetRenderer = $this->_defaultFieldsetRenderer;
}
$fieldsetRenderer->setForm($this)
->setConfigData($this->_configData);
if ($this->_configFields->hasChildren($group, $this->getWebsiteCode(), $this->getStoreCode())) {
$helperName = $this->_configFields->getAttributeModule($section, $group);
$fieldsetConfig = array('legend' => Mage::helper($helperName)->__((string)$group->label));
if (!empty($group->comment)) {
$fieldsetConfig['comment'] = Mage::helper($helperName)->__((string)$group->comment);
}
if (!empty($group->expanded)) {
$fieldsetConfig['expanded'] = (bool)$group->expanded;
}
$fieldset = new Varien_Data_Form_Element_Fieldset($fieldsetConfig);
$fieldset->setId($section->getName() . '_' . $group->getName())
->setRenderer($fieldsetRenderer)
->setGroup($group);
if ($parentElement) {
$fieldset->setIsNested(true);
$parentElement->addElement($fieldset);
} else {
$form->addElement($fieldset);
}
$this->_prepareFieldOriginalData($fieldset, $group);
$this->_addElementTypes($fieldset);
$this->_fieldsets[$group->getName()] = $fieldset;
if ($group->clone_fields) {
if ($group->clone_model) {
$cloneModel = Mage::getModel((string)$group->clone_model);
} else {
Mage::throwException($this->__('Config form fieldset clone model required to be able to clone fields'));
}
foreach ($cloneModel->getPrefixes() as $prefix) {
$this->initFields($fieldset, $group, $section, $prefix['field'], $prefix['label']);
}
} else {
$this->initFields($fieldset, $group, $section);
}
}
}
/**
* Return dependency block object
*
* #return Mage_Adminhtml_Block_Widget_Form_Element_Dependence
*/
protected function _getDependence()
{
if (!$this->getChild('element_dependense')){
$this->setChild('element_dependense',
$this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'));
}
return $this->getChild('element_dependense');
}
/**
* Init fieldset fields
*
* #param Varien_Data_Form_Element_Fieldset $fieldset
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param string $fieldPrefix
* #param string $labelPrefix
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initFields($fieldset, $group, $section, $fieldPrefix='', $labelPrefix='')
{
if (!$this->_configDataObject) {
$this->_initObjects();
}
// Extends for config data
$configDataAdditionalGroups = array();
foreach ($group->fields as $elements) {
$elements = (array)$elements;
// sort either by sort_order or by child node values bypassing the sort_order
if ($group->sort_fields && $group->sort_fields->by) {
$fieldset->setSortElementsByAttribute(
(string)$group->sort_fields->by,
$group->sort_fields->direction_desc ? SORT_DESC : SORT_ASC
);
} else {
usort($elements, array($this, '_sortForm'));
}
foreach ($elements as $element) {
if (!$this->_canShowField($element)) {
continue;
}
if ((string)$element->getAttribute('type') == 'group') {
$this->_initGroup($fieldset->getForm(), $element, $section, $fieldset);
continue;
}
/**
* Look for custom defined field path
*/
$path = (string)$element->config_path;
if (empty($path)) {
$path = $section->getName() . '/' . $group->getName() . '/' . $fieldPrefix . $element->getName();
} elseif (strrpos($path, '/') > 0) {
// Extend config data with new section group
$groupPath = substr($path, 0, strrpos($path, '/'));
if (!isset($configDataAdditionalGroups[$groupPath])) {
$this->_configData = $this->_configDataObject->extendConfig(
$groupPath,
false,
$this->_configData
);
$configDataAdditionalGroups[$groupPath] = true;
}
}
$data = $this->_configDataObject->getConfigDataValue($path, $inherit, $this->_configData);
if ($element->frontend_model) {
$fieldRenderer = Mage::getBlockSingleton((string)$element->frontend_model);
} else {
$fieldRenderer = $this->_defaultFieldRenderer;
}
$fieldRenderer->setForm($this);
$fieldRenderer->setConfigData($this->_configData);
$helperName = $this->_configFields->getAttributeModule($section, $group, $element);
$fieldType = (string)$element->frontend_type ? (string)$element->frontend_type : 'text';
$name = 'groups[' . $group->getName() . '][fields][' . $fieldPrefix.$element->getName() . '][value]';
$label = Mage::helper($helperName)->__($labelPrefix) . ' '
. Mage::helper($helperName)->__((string)$element->label);
$hint = (string)$element->hint ? Mage::helper($helperName)->__((string)$element->hint) : '';
if ($element->backend_model) {
$model = Mage::getModel((string)$element->backend_model);
if (!$model instanceof Mage_Core_Model_Config_Data) {
Mage::throwException('Invalid config field backend model: '.(string)$element->backend_model);
}
$model->setPath($path)
->setValue($data)
->setWebsite($this->getWebsiteCode())
->setStore($this->getStoreCode())
->afterLoad();
$data = $model->getValue();
}
$comment = $this->_prepareFieldComment($element, $helperName, $data);
$tooltip = $this->_prepareFieldTooltip($element, $helperName);
$id = $section->getName() . '_' . $group->getName() . '_' . $fieldPrefix . $element->getName();
if ($element->depends) {
foreach ($element->depends->children() as $dependent) {
/* #var $dependent Mage_Core_Model_Config_Element */
if (isset($dependent->fieldset)) {
$dependentFieldGroupName = (string)$dependent->fieldset;
if (!isset($this->_fieldsets[$dependentFieldGroupName])) {
$dependentFieldGroupName = $group->getName();
}
} else {
$dependentFieldGroupName = $group->getName();
}
$dependentFieldNameValue = $dependent->getName();
$dependentFieldGroup = $dependentFieldGroupName == $group->getName()
? $group
: $this->_fieldsets[$dependentFieldGroupName]->getGroup();
$dependentId = $section->getName()
. '_' . $dependentFieldGroupName
. '_' . $fieldPrefix
. $dependentFieldNameValue;
$shouldBeAddedDependence = true;
$dependentValue = (string)(isset($dependent->value) ? $dependent->value : $dependent);
if (isset($dependent['separator'])) {
$dependentValue = explode((string)$dependent['separator'], $dependentValue);
}
$dependentFieldName = $fieldPrefix . $dependent->getName();
$dependentField = $dependentFieldGroup->fields->$dependentFieldName;
/*
* If dependent field can't be shown in current scope and real dependent config value
* is not equal to preferred one, then hide dependence fields by adding dependence
* based on not shown field (not rendered field)
*/
if (!$this->_canShowField($dependentField)) {
$dependentFullPath = $section->getName()
. '/' . $dependentFieldGroupName
. '/' . $fieldPrefix
. $dependent->getName();
$dependentValueInStore = Mage::getStoreConfig($dependentFullPath, $this->getStoreCode());
if (is_array($dependentValue)) {
$shouldBeAddedDependence = !in_array($dependentValueInStore, $dependentValue);
} else {
$shouldBeAddedDependence = $dependentValue != $dependentValueInStore;
}
}
if ($shouldBeAddedDependence) {
$this->_getDependence()
->addFieldMap($id, $id)
->addFieldMap($dependentId, $dependentId)
->addFieldDependence($id, $dependentId, $dependentValue);
}
}
}
$sharedClass = '';
if ($element->shared && $element->config_path) {
$sharedClass = ' shared shared-' . str_replace('/', '-', $element->config_path);
}
$requiresClass = '';
if ($element->requires) {
$requiresClass = ' requires';
foreach (explode(',', $element->requires) as $groupName) {
$requiresClass .= ' requires-' . $section->getName() . '_' . $groupName;
}
}
$field = $fieldset->addField($id, $fieldType, array(
'name' => $name,
'label' => $label,
'comment' => $comment,
'tooltip' => $tooltip,
'hint' => $hint,
'value' => $data,
'inherit' => $inherit,
'class' => $element->frontend_class . $sharedClass . $requiresClass,
'field_config' => $element,
'scope' => $this->getScope(),
'scope_id' => $this->getScopeId(),
'scope_label' => $this->getScopeLabel($element),
'can_use_default_value' => $this->canUseDefaultValue((int)$element->show_in_default),
'can_use_website_value' => $this->canUseWebsiteValue((int)$element->show_in_website),
));
$this->_prepareFieldOriginalData($field, $element);
if (isset($element->validate)) {
$field->addClass($element->validate);
}
if (isset($element->frontend_type)
&& 'multiselect' === (string)$element->frontend_type
&& isset($element->can_be_empty)
) {
$field->setCanBeEmpty(true);
}
$field->setRenderer($fieldRenderer);
if ($element->source_model) {
// determine callback for the source model
$factoryName = (string)$element->source_model;
$method = false;
if (preg_match('/^([^:]+?)::([^:]+?)$/', $factoryName, $matches)) {
array_shift($matches);
list($factoryName, $method) = array_values($matches);
}
$sourceModel = Mage::getSingleton($factoryName);
if ($sourceModel instanceof Varien_Object) {
$sourceModel->setPath($path);
}
if ($method) {
if ($fieldType == 'multiselect') {
$optionArray = $sourceModel->$method();
} else {
$optionArray = array();
foreach ($sourceModel->$method() as $value => $label) {
$optionArray[] = array('label' => $label, 'value' => $value);
}
}
} else {
$optionArray = $sourceModel->toOptionArray($fieldType == 'multiselect');
}
$field->setValues($optionArray);
}
}
}
return $this;
}
/**
* Return config root node for current scope
*
* #return Varien_Simplexml_Element
*/
public function getConfigRoot()
{
if (empty($this->_configRoot)) {
$this->_configRoot = Mage::getSingleton('adminhtml/config_data')->getConfigRoot();
}
return $this->_configRoot;
}
/**
* Set "original_data" array to the element, composed from nodes with scalar values
*
* #param Varien_Data_Form_Element_Abstract $field
* #param Varien_Simplexml_Element $xmlElement
*/
protected function _prepareFieldOriginalData($field, $xmlElement)
{
$originalData = array();
foreach ($xmlElement as $key => $value) {
if (!$value->hasChildren()) {
$originalData[$key] = (string)$value;
}
}
$field->setOriginalData($originalData);
}
/**
* Support models "getCommentText" method for field note generation
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldComment($element, $helper, $currentValue)
{
$comment = '';
if ($element->comment) {
$commentInfo = $element->comment->asArray();
if (is_array($commentInfo)) {
if (isset($commentInfo['model'])) {
$model = Mage::getModel($commentInfo['model']);
if (method_exists($model, 'getCommentText')) {
$comment = $model->getCommentText($element, $currentValue);
}
}
} else {
$comment = Mage::helper($helper)->__($commentInfo);
}
}
return $comment;
}
/**
* Prepare additional comment for field like tooltip
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldTooltip($element, $helper)
{
if ($element->tooltip) {
return Mage::helper($helper)->__((string)$element->tooltip);
} elseif ($element->tooltip_block) {
return $this->getLayout()->createBlock((string)$element->tooltip_block)->toHtml();
}
return '';
}
/**
* Append dependence block at then end of form block
*
*
*/
protected function _afterToHtml($html)
{
if ($this->_getDependence()) {
$html .= $this->_getDependence()->toHtml();
}
$html = parent::_afterToHtml($html);
return $html;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $a
* #param Varien_Simplexml_Element $b
* #return boolean
*/
protected function _sortForm($a, $b)
{
return (int)$a->sort_order < (int)$b->sort_order ? -1 : ((int)$a->sort_order > (int)$b->sort_order ? 1 : 0);
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseDefaultValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
if ($this->getScope() == self::SCOPE_WEBSITES && $field) {
return true;
}
return false;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseWebsiteValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
return false;
}
/**
* Checking field visibility
*
* #param Varien_Simplexml_Element $field
* #return bool
*/
protected function _canShowField($field)
{
$ifModuleEnabled = trim((string)$field->if_module_enabled);
if ($ifModuleEnabled && !Mage::helper('Core')->isModuleEnabled($ifModuleEnabled)) {
return false;
}
switch ($this->getScope()) {
case self::SCOPE_DEFAULT:
return (int)$field->show_in_default;
break;
case self::SCOPE_WEBSITES:
return (int)$field->show_in_website;
break;
case self::SCOPE_STORES:
return (int)$field->show_in_store;
break;
}
return true;
}
/**
* Retrieve current scope
*
* #return string
*/
public function getScope()
{
$scope = $this->getData('scope');
if (is_null($scope)) {
if ($this->getStoreCode()) {
$scope = self::SCOPE_STORES;
} elseif ($this->getWebsiteCode()) {
$scope = self::SCOPE_WEBSITES;
} else {
$scope = self::SCOPE_DEFAULT;
}
$this->setScope($scope);
}
return $scope;
}
/**
* Retrieve label for scope
*
* #param Mage_Core_Model_Config_Element $element
* #return string
*/
public function getScopeLabel($element)
{
if ($element->show_in_store == 1) {
return $this->_scopeLabels[self::SCOPE_STORES];
} elseif ($element->show_in_website == 1) {
return $this->_scopeLabels[self::SCOPE_WEBSITES];
}
return $this->_scopeLabels[self::SCOPE_DEFAULT];
}
/**
* Get current scope code
*
* #return string
*/
public function getScopeCode()
{
$scopeCode = $this->getData('scope_code');
if (is_null($scopeCode)) {
if ($this->getStoreCode()) {
$scopeCode = $this->getStoreCode();
} elseif ($this->getWebsiteCode()) {
$scopeCode = $this->getWebsiteCode();
} else {
$scopeCode = '';
}
$this->setScopeCode($scopeCode);
}
return $scopeCode;
}
/**
* Get current scope code
*
* #return int|string
*/
public function getScopeId()
{
$scopeId = $this->getData('scope_id');
if (is_null($scopeId)) {
if ($this->getStoreCode()) {
$scopeId = Mage::app()->getStore($this->getStoreCode())->getId();
} elseif ($this->getWebsiteCode()) {
$scopeId = Mage::app()->getWebsite($this->getWebsiteCode())->getId();
} else {
$scopeId = '';
}
$this->setScopeId($scopeId);
}
return $scopeId;
}
/**
* Enter description here...
*
* #return array
*/
protected function _getAdditionalElementTypes()
{
return array(
'export' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_export'),
'import' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_import'),
'allowspecific' => Mage::getConfig()
->getBlockClassName('adminhtml/system_config_form_field_select_allowspecific'),
'image' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_image'),
'file' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_file')
);
}
/**
* Temporary moved those $this->getRequest()->getParam('blabla') from the code accross this block
* to getBlala() methods to be later set from controller with setters
*/
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getSectionCode()
{
return $this->getRequest()->getParam('section', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getWebsiteCode()
{
return $this->getRequest()->getParam('website', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getStoreCode()
{
return $this->getRequest()->getParam('store', '');
}
}
Guide me how to resolve this.
Thanks in advance
Since you did not provide any code I can break down the basics.
That error means the object is empty.
If your code looked like this for example.
$results->toOptionArray()
Then the error is telling you $results is not an instance of an object.

Resources