im have this code, but in need set user session programatically because, chanel entry check status permisson before insert data <?php namespace AndresMolina\ComparadorProductos\Commands;
use ExpressionEngine\Cli\Cli;
class CommandImportar extends Cli { public $name = ‘importar’; public $signature = ‘comparador_productos:make:importar’; public $description = ‘Importa productos json’; public $summary = ‘Importa productos json’; public $usage = ‘php eecli.php comparador_productos:make:importar’;
public function handle()
{
ee()->load->library('session');
$session = ee('session');
$data = array(
'user_id' => 1,
'username' => 'amolina',
'logged_in' => TRUE
);
// Establece los datos en la sesión
$session->setValue($data);
echo ee()->session->userdata('username');
$filePath = '/var/www/data.json';
$jsonData = json_decode(file_get_contents($filePath));
foreach ($jsonData as $product) {
$sku = $product->sku;
$url_original = $product->url_original;
//print_r($sku);
// Buscar si el producto ya existe
/*echo "\n";
echo ($this->getChannelID());
echo "\n";
echo ($this->getfieldID('sku'));
echo "\n";*/
//echo ($this->getfieldID('url_original'));
//$id_sku=$this->getfieldID('sku');
/* $entry_object = ee('Model')
->get('ChannelEntry')
->filter('field_id_'.$this->getfieldID('sku'), $sku)
->filter('field_id_'.$this->getfieldID('url_original'), $url_original)
->first();
print_r($entry_object);*/
$existingEntry = ee('Model')->get('ChannelEntry')
->filter('channel_id', $this->getChannelID()) // Usa el ID correcto del canal
->filter('field_id_'.$this->getfieldID('sku'), $sku)
->filter('field_id_'.$this->getfieldID('url_original'), $url_original)
->first();
if ($existingEntry) {
// Actualizar producto existente
$existingEntry->{'field_id_'.$this->getfieldID('descripcion')} = $product->descripcion;
$existingEntry->{'field_id_'.$this->getfieldID('precio_oferta')} = $product->precio_oferta;
$result = $existingEntry->validate();
if ($result->isValid()) {
$existingEntry->save();
$this->info('Update Producto actualizado: ' . $sku);
} else {
$this->error('Update Error al validar el producto: ' . $sku);
}
} else {
// Insertar nuevo producto
//print_r(ee('Model')->get('Status', 1)->first()->status);
$entry = ee('Model')->make('ChannelEntry');
$entry->author_id = 1;
$entry->channel_id = $this->getChannelID(); // ID del canal de productos
$entry->title = $product->nombre . ' ' . $sku . ' streto';
$entry->url_title = ee('Format')->make('Text', $entry->title)->urlSlug()->compile();
$entry->status ="insertado";
$entry->entry_date = ee()->localize->now;
//print_r($entry);
// Asignar campos personalizados
foreach ($product as $fieldName => $fieldValue) {
$fieldId = $this->getfieldID($fieldName);
if ($fieldId) {
//print_r('field_id_'.$fieldId);
//echo ":".$fieldValue;
//echo "\n";
$entry->{'field_id_'.$fieldId} = $fieldValue;
}
}
$result = $entry->validate();
print_r($result->getAllErrors());
if ($result->isValid()) {
$entry->save();
$this->info('Insertar Producto insertado: ' . $sku);
} else {
$this->error('Insertar Error al validar nuevo producto: ' . $sku);
}
}
}
}
private function getfieldID($fieldName)
{
$field = ee('Model')->get('ChannelField')
->filter('field_name', $fieldName)
->first();
return $field ? $field->field_id : null;
}
private function getChannelID()
{
// Retorna el ID correcto del canal de productos
return 4;
}
}
Thanks for posting this! Whats the error your currently receiving? It may also be helpful to know what version of ExpressionEngine your currently running.
I believe the following github issues has an exmaple of a CLI command that generates an entry as well.
Thanks,
-Tom Jaeger
From the code read, it appears to be mostly correct, insofar as what the ChannelEntry Model expects. Only thing I’d suggest is, instead of using the session stuff, just to hard code the member_id as author_id within the Model.
Barring that, considering these Entries have to be dynamically managed, could be an idea to backdoor the author details. For example, hard code said entries to a Super Admin member_id, and then use the db libraries to just update the column appropriately.
Version: ExpressionEngine 7, latest version. Issues: If I don’t include the session library, a facade error (legacy code) is thrown. If I include the Session library, that error disappears, and it proceeds to the process of inserting the new entry. At that moment, it indicates that the selected status is not valid.
If I create Status for the channel, it only lets me select members with access to that status.
Therefore, I need to programmatically establish the user session for CLI. The code is invoked by the command “php system/ee/eecli.php comparador_productos:make:importar”
The result is:
“Array ( [status] => Array ( [callback] => invalid_selection )
) Insert Error validating new product: PROD123 Array ( [status] => Array ( [callback] => invalid_selection )
) Insert Error validating new product: PROD124 “
the code is:
<?php namespace AndresMolina\ComparadorProductos\Commands;
use ExpressionEngine\Cli\Cli;
class CommandImportar extends Cli { public $name = ‘importar’; public $signature = ‘comparador_productos:make:importar’; public $description = ‘Importa productos json’; public $summary = ‘Importa productos json’; public $usage = ‘php eecli.php comparador_productos:make:importar’;
public function handle()
{
ee()->load->library('session');
//echo ee()->session->userdata('username');
$filePath = '/var/www/data.json';
$jsonData = json_decode(file_get_contents($filePath));
foreach ($jsonData as $product) {
$sku = $product->sku;
$url_original = $product->url_original;
//print_r($sku);
// Buscar si el producto ya existe
/*echo "\n";
echo ($this->getChannelID());
echo "\n";
echo ($this->getfieldID('sku'));
echo "\n";*/
//echo ($this->getfieldID('url_original'));
//$id_sku=$this->getfieldID('sku');
/* $entry_object = ee('Model')
->get('ChannelEntry')
->filter('field_id_'.$this->getfieldID('sku'), $sku)
->filter('field_id_'.$this->getfieldID('url_original'), $url_original)
->first();
print_r($entry_object);*/
$existingEntry = ee('Model')->get('ChannelEntry')
->filter('channel_id', $this->getChannelID()) // Usa el ID correcto del canal
->filter('field_id_'.$this->getfieldID('sku'), $sku)
->filter('field_id_'.$this->getfieldID('url_original'), $url_original)
->first();
if ($existingEntry) {
// Actualizar producto existente
$existingEntry->{'field_id_'.$this->getfieldID('descripcion')} = $product->descripcion;
$existingEntry->{'field_id_'.$this->getfieldID('precio_oferta')} = $product->precio_oferta;
$result = $existingEntry->validate();
if ($result->isValid()) {
$existingEntry->save();
$this->info('Update Producto actualizado: ' . $sku);
} else {
$this->error('Update Error al validar el producto: ' . $sku);
}
} else {
// Insertar nuevo producto
//print_r(ee('Model')->get('Status', 1)->first()->status);
$entry = ee('Model')->make('ChannelEntry');
$entry->author_id = 1;
$entry->channel_id = $this->getChannelID(); // ID del canal de productos
$entry->title = $product->nombre . ' ' . $sku . ' streto';
$entry->url_title = ee('Format')->make('Text', $entry->title)->urlSlug()->compile();
$entry->status ="insertado";
$entry->entry_date = ee()->localize->now;
//print_r($entry);
// Asignar campos personalizados
foreach ($product as $fieldName => $fieldValue) {
$fieldId = $this->getfieldID($fieldName);
if ($fieldId) {
//print_r('field_id_'.$fieldId);
//echo ":".$fieldValue;
//echo "\n";
$entry->{'field_id_'.$fieldId} = $fieldValue;
}
}
$result = $entry->validate();
print_r($result->getAllErrors());
if ($result->isValid()) {
$entry->save();
$this->info('Insertar Producto insertado: ' . $sku);
} else {
$this->error('Insertar Error al validar nuevo producto: ' . $sku);
}
}
}
}
private function getfieldID($fieldName)
{
$field = ee('Model')->get('ChannelField')
->filter('field_name', $fieldName)
->first();
return $field ? $field->field_id : null;
}
private function getChannelID()
{
// Retorna el ID correcto del canal de productos
return 4;
}
}
To be honest, I’ve written lots of Channel Entry Command line logic and haven’t encountered your situation. Not to say member session isn’t the problem, just that it’s an odd one.
That said, from your error message, EE is saying it’s failing due to the status being invalid. Have you pursued that as the culprit. Array ( [status] => Array ( [callback] => invalid_selection ) and your status being insertado makes me wonder if your channel is setup to use that for a status. Can you confirm?
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.