How to get more datas from database in a .tpl file in Prestashop - database

I'm working on prestashop 1.7.
I added a field to the specific_price table.
I would like to use the data in this field in the cart-detailed-product-line.tpl
How should I do this ?
Do I need to connect to the price_specific table in the Cart.php class?
If yes, how?
Thanks in advance!

Yes, the simplest in view of your situation, is to create an override Link.php, and in there make a call to your table to fetch your information.
In the tpl you only have to put {$link->nameoffunction(parametre)}
Regards

Thanks a lot ethercreation!!
I put in the Link.php :
public static function getSpecificPriceRatioAjout($id_product_attribute)
{
$unit_price_ratio_ajout = Db::getInstance()->executeS(
'SELECT unit_price_ratio_ajout FROM '._DB_PREFIX_.'specific_price WHERE id_product_attribute = '.$id_product_attribute
);
var_dump($unit_price_ratio_ajout);
return $unit_price_ratio_ajout;
}
In my .tpl :
{$link->getSpecificPriceRatioAjout({$product.id_product_attribute})}
The Response: htmlspecialchars() expects parameter 1 to be string, array given
Have you an ideo of what I've done wrong?

Related

How can i fetch dynamic data from database based on selected language.?

Hi i am working on a project in laravel 7.0, in back-end i have a table called Posts which contains 2 text language input one in french and the other is arabic added by the back-end application.
what i am trying to do is when the user uses the French Language i want the title_fr to be displayed on the view and same thing in Arabic language the title should be title_ar.
P.S data are stored in French and Arabic
I have tried the similar solution given in an other similar question but none of it worked in my case!
Any idea how i might get this to work ?
Thanks in advance.
You can do something similar to below. We have a model Post, this model has an attribute title. I also assume that you have an attribute that will return user's language from the User model.
class Post extends Model
{
public function getTitleAttribute(): string
{
return Auth::user()->language === 'fr' ? $this->title_fr : $this->title_ar;
}
}
FYI above is just a demo on what can be done. For a full blow solution I would recommend decorator pattern.
Also it might be worth considering using morph for things like that. You can have a service provider that will initiate the morph map for you post model relevant to the language that user has, I.e.
Class ModelProvider {
Protected $models = [
‘fr’ => [
‘post’ => App/Models/Fr/Post::class,
],
‘ar’ => [
‘post’ => App/Models/Ar/Post::class,
]
];
Public function boot() {
$language = Auth::user()->Settings->language;
Relation::morphMap($This->models[$language]);
}
}
Afterwards you just need to call to Relation::getMorphModel(‘post’) to grab Post class that will return correct language.
I.e. App/Models/Fr/Post can have a an attribute title:
Public function getTitleAttribute(): string {
Return $this->title_fr;
}
For example above you would also want to utilise interfaces to make sure that all models follow the same contract, something below would do the trick:
Interface I18nPostInterface {
Public function getTitleAttribute(): string
}
Also, depending on the database you use, to store titles (and other language data) in a JSON format in the database. MySQL 8 has an improve support for JSON data, but there are limitations with that.
So I was Able to fetch data from my database based on the Language selected by the user.
Like i said before I have a table called Posts and has columns id,title_fr and title_ar. I am using laravel Localization.
Inside my PostController in the index function i added this code:
public function index()
{
//
$post = Post::all();
$Frtitle = post::get()->pluck('title_fr');
$Artitle = post::get()->pluck('title_ar');
return view('post.index',compact('post','Frtitle','Artitle'));
}
if anyone has a better way then mine please let me know, i am sure
there is a better way.

How format datetime for sql server in laravel?

im trying to format datetime values in laravel to make them match with sql server format, im getting this error:
The separation symbol could not be found Unexpected data found.
Unexpected data found. Trailing data
Im using a custom format in my model:
protected $dateFormat = 'd-m-Y H:i:s';
It works good for the create method con controllers, there is no problem, the error happen when try to update and I think is related to how the value is stored in the database.
Using tinker I retrieve the value of updated_at in my model and is shown in the next format:
updated_at: "2018-07-24 09:14:09.000"
So when Im updating this value the format used is:
protected $dateFormat = 'd-m-Y H:i:s';
I think it should be something like d-m-Y H:i:s.000 but doesnt work, how can I solve this?
I had exactly the same issue, when switching to laravel version 5.6. Now I found the correct way to handle this.
Create a Base class like this and add a public method getDateFormat.
There you return the date a little bit different
return 'Y-d-m H:i:s.v';
See that date (d) and month (m) are switched and at the end you need to put a .v which stands for milliseconds. This worked for me fine. See here my complete Base class:
<?php
namespace App\Models\Base;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
public function getDateFormat()
{
return 'Y-d-m H:i:s.v';
}
public $timestamps = false;
}
What version of Laravel are you using? This was fixed in a recent release (can't remember exactly which) that relies on PHP 7.
The dateFormat should be "Y-m-d H:i:s.v". v is Milliseconds (added in PHP 7.0.0). The problem you're experiencing with updates and inserts is caused when the updated/inserted model is returned. It is passed to Carbon to convert date and datetime fields into instances of Carbon, but the datetime fields have 'trailing
You can also try this one in SQL/Select Query:
\DB::raw ("DATE_FORMAT(comments.date,'%d-%m-%Y %H:%i:%s') as sth_date")
E.g:
Comment::orderBy('date','desc')->with('user')
->join('users','comments.id_user', '=', 'users.id')
->select('users.username', 'comments.id', 'comments.id_race', 'comments.status', 'comments.ip_address', 'comments.id_user',
\DB::raw ("DATE_FORMAT(comments.date,'%d-%m-%Y %H:%i:%s') as sth ") );
Time fraction is a configuration of your database, you can see it below, so you can just try to switch on your database.
https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
But using something like $d->format("Y-m-d H:i:s.u") you can format/manipulate using class Datetime().

how to encrypt data from a database query array in laravel controller?

$shares_data = Share::where('member_id', $member_id)->get();
I want to all data of $shares_data array in different variable. I am using Laravel 5.2
Firstly i used the code in the controller:
foreach($shares_data as $key=>$share_data):
$name= $share_data->name;
$mobile= $share_data->mobile;
endforeach
but it was not working. then try the code below:
foreach($shares_data as $key=>$share_data){
$name= $share_data->name;
$mobile= $share_data->mobile;
}
Now it's working. Thank you very much Saman for your kind help.

The record 999 can not be retrieved

In my sample database table, I have a record with post id 999.
I got a few lines of code to retrieve the record of post id 999:
function viewing($sid){
$this->Testing->post_id=$sid;
$this->set('posts', $this->Testing->read());
}
But no record can be record retrieved from the post with id 999 when I altered the code:
function viewing($sid){
$sid=999;
$this->Testing->post_id=$sid;
$this->set('posts', $this->Testing->read());
}
Could you tell help me please?
You want to set the model::id attribute, not post_id.
$this->Site1->id=$sid;
I think you messing the terms and functions. First you set id of the Site1 model. Then you trying to read record from the Testing model and setting post_id in the record. The proper code should look like:
function viewing($sid){
$sid=999;
$this->Post->id=$sid;
$this->set('post', $this->Post->read());
}
Alternatively and more short it will be:
function viewing($sid){
$sid=999;
$this->set('post', $this->Post->read(null, $sid));
}
But assuming that you want to get posts probably the actual code should look like:
function viewing($sid){
$sid=999;
$this->set('post', $this->Posts->fund('all', array('conditions'=>array('post_id'=>$sid))));
}
Or something similar. I think first you should take a look on the CakePHP Cookbook and on the CakePHP API
Better to use the form $this->Post->read(null, $sid)
If you want to control retrieval of associated tables, use $this->MyModel->contain()
E.g.
$this->Post->contain('Testing') //(Post & Testing but not Site1)
or
$this->Post->contain('Testing','Site1.someValue') //(Post & Testing and Site1.someValue)
I think you should also carefully reread the manual sections on http://book.cakephp.org/view/78/Associations-Linking-Models-Together & http://book.cakephp.org/view/73/Retrieving-Your-Data

What is the equivalent to getLastInsertId() in Cakephp?

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->getLastInsertId(); //here it works
}
function insertformname() {
echo $this->Form->getLastInsertId(); //this doesnt echo at all
}
Please suggest a way to get the functionality I want.
CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID().
Actually these methods are identical so it really doesn't matter which method you use.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
This methods can be found in cake/libs/model/model.php on line 2768
Just use:
$this->Model->id;
In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id
id - Value of the primary key ID of
the record that this model is
currently pointing to. Automatically
set after database insertions.
Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html
Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id
After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?
Can you explain the flow of your application and how it relates to your problem?
You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?
If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.
Try using this code in your model class (perhaps in AppModel):
function get_sql_insert_id() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastInsertId();
}
Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.
this is best way to find out last inserted id.
$this->ModelName->getInsertID();
other way is using
$this->ModelName->find('first',array('order'=>'id DESC'))
There are several methods to get last inserted primary key id while using save method
$this->loadModel('Model');
$this->Model->save($this->data);
This will return last inserted id of the model current model
$this->Model->getLastInsertId();
$this->Model-> getInsertID();
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of last loaded model
$this->id;
Try to use this code. try to set it to a variable so you can use it in other functions. :)
$variable = $this->ModelName->getLastInsertId();
in PHP native, try this.
$variable = mysqli_insert_id();
This will return last inserted id of last loaded model
$this->id;
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of the model current model
CakePHP has two methods for getting the last inserted id:
Model::getLastInsertID() and Model::getInsertID().
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
Below are the options:
echo $this->Registration->id;
echo $this->Registration->getInsertID();
echo $this->Registration->getLastInsertId();
Here, you can replace Registration with your model name.
Thanks
Use this one
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->id; //here it works
}
You can get last inseted id with many ways.Like Model name is User so best way to fetch the last inserted id is
$this->User->id; // For User Model
You can also use Model function but below code will return last inserted id of model with given model name for this example it will return User model data
$this->User->getLastInsertId();
$this->User->getInsertID();
When you use save(), the last insert ID is set to the model’s $id property. So:
if ($this->Model->save()) {
printf('Last insert ID was %s', $this->Model->id);
}
Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this
$id = $this->id;// within a model
$id = $this->{$this->modelName}->id;// in a controller
After insertion of data, we can use following code to get recently added record's id:
$last_insert_id=$this->Model->id;
each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.
so one can access it directly by $Model->id;,
no need to query again for lastInsertId.
I think it works with getLastInsertId() if you use InnoDB Tables in your MySQL Database. You also can use $this->Model->id
$Machinedispatch =
$this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));
Simplest way of finding last inserted row. For me getLastInsertId() this not works.
Actually you are using the getLastInsertId or getInsertId in a wrong manner.
getLastInsertId() is meant to work only after save() method.
It will even not work after a manual insert, as cake engine is storing the mysql_insert_id under $this->_insertID inside the save method which can be retrieved via the getLastInsertId or getInsertId.
Now in your case
$this->Model->id
OR
$this->Model->find('first',array('order'=>'id DESC'))
Will do.
This is interesting, I also stumbled upon this issue. What you asked perhaps how to get the last ID of a certain model regardless of it's state, whether it's just been inserted or not. To further understand what getInsertID does, we need to take a look at the source:
Link 1: http://api20.cakephp.org/view_source/model#line-3375
public function getInsertID() {
return $this->_insertID
}
Yup, that's the only piece of code inside that function. It means that cakephp caches any last inserted ID, instead of retrieve it from the database. That's why you get nothing if you use that function when you haven't done any record creation on the model.
I made a small function to get the last ID of a certain table, but please note that this should not be used as a replacement of getLastID() or getLastInsertID(), since it has an entirely different purpose.
Add the function lastID() to the AppModel as shown below so that it can be used system wide. It has it's limit, which can't be used on model with composite primary key.
class AppModel extends Model {
public function lastID() {
$data = $this->find('first',
array(
'order' => array($this->primaryKey . ' DESC'),
'fields' => array($this->primaryKey)
)
);
return $data[$this->name][$this->primaryKey];
}
}
Original Source : Class Model
In CakePHP you can get it by:
Model::getInsertID() //Returns the ID of the last record this model inserted.
Model::getLastInsertID() //Alias to getInsertID().
$this->Model->field('id', null, 'id DESC')

Resources