XF 2.2 Creating entity while installation

tom3

Active member
I'm currently trying to create an ApiKey directly during the installation, in installation step number one I add a boolean field to the entity.

In step two I try to create an ApiKey with the help of the Entity Manager but I get the error message that the field does not exist (probably because the event listener has not been run yet?).

Same goes for uninstalling.

Code:
In Finder.php line 1640:
  [InvalidArgumentException]
  Unknown column test on XF:ApiKey

PHP:
public function installStep1()
   {
       $this->schemaManager()->alterTable('xf_api_key', function(Alter $table)
       {
           $table->addColumn('test', 'tinyint')->setDefault(0);
       });
   }

public function installStep2()
   {
       if (!$this->assertExistingKey())
       {
           $key = \XF::em()->create('XF:ApiKey');
           $key->set('title', 'testkey');
           $key->set('test', true);
           $key->save();
       }
   }

   public function uninstallStep1()
   {
       if ($key = $this->assertExistingKey())
       {
           $key->delete();
       }
   }

   public function uninstallStep2()
   {
       $this->schemaManager()->alterTable('xf_api_key', function(Alter $table)
       {
           $table->dropColumns('test');
       });
   }

How can I create an entity during installation while extending?
 

tom3

Active member
Before the question comes up: yes in the listener the entity was extended.
PHP:
public static function apiKeyEntityStructure(\XF\Mvc\Entity\Manager $em, \XF\Mvc\Entity\Structure &$structure)
{
    $structure->columns['test'] = ['type' => Entity::BOOL, 'default' => false];
}
 

tom3

Active member
During the installation I was able to solve it with the postInstall(array &$stateChanges) function. Unfortunately I haven't found a solution for uninstalling yet.
 

Mike

XenForo developer
Staff member
During the install, upgrade and uninstall, your listeners aren't active. If they were, there are situations where fatal errors can occur. So if you want to do something in those steps that involves your tables or alters you've made to tables, you need to use raw queries.

Alternatively, as you noticed, there are postInstall and postUpgrade methods you can use to take certain actions and your listeners will be available then. For uninstalling, you have to use raw queries if you need to query for something involving your data. In your example, you could query for the key, get the ID, and then fetch the entity by that and delete it.
 

tom3

Active member
Alternatively, as you noticed, there are postInstall and postUpgrade methods you can use to take certain actions and your listeners will be available then. For uninstalling, you have to use raw queries if you need to query for something involving your data. In your example, you could query for the key, get the ID, and then fetch the entity by that and delete it.
That's a really good workaround I haven't thought about. Thanks!
 
Top