We use cookies to improve your experience. No personal information is gathered and we don't serve ads. Cookies Policy.

ExpressionEngine Logo ExpressionEngine
Features Pricing Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University
Log In or Sign Up
Log In Sign Up
ExpressionEngine Logo
Features Pro new Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University Blog
  • Home
  • Forums

How can create a Emntry from CLi

How Do I?

Andrés Molina's avatar
Andrés Molina
50 posts
one year ago
Andrés Molina's avatar Andrés Molina

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&#40;$filePath&#41;);

    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;
}

}

       
Tom Jaeger's avatar
Tom Jaeger
449 posts
one year ago
Tom Jaeger's avatar Tom Jaeger

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

       
mithra62's avatar
mithra62
63 posts
one year ago
mithra62's avatar mithra62

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.

       
Andrés Molina's avatar
Andrés Molina
50 posts
one year ago
Andrés Molina's avatar Andrés Molina

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&#40;$filePath&#41;);

    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;
}

}

       
mithra62's avatar
mithra62
63 posts
one year ago
mithra62's avatar mithra62

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?

       
Andrés Molina's avatar
Andrés Molina
50 posts
one year ago
Andrés Molina's avatar Andrés Molina

More info: Server: Alicloud Ec2, 1CPU, 1GB RAM(only for test) aliyun_3_9_x64_20G_alibase_20231219.vhd

Tested with super admin user(id 1) and “rastreador” user(id2)

       
Andrés Molina's avatar
Andrés Molina
50 posts
one year ago
Andrés Molina's avatar Andrés Molina

OK, if im remove entry validation line, code works fine.

thanks

       

Reply

Sign In To Reply

ExpressionEngine Home Features Pro Contact Version Support
Learn Docs University Forums
Resources Support Add-Ons Partners Blog
Privacy Terms Trademark Use License

Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.