XF 2.0 Alert after a thread is created externally

LPH

Well-known member
I'm attempting to create a post externally then have an alert sent to the author's XenForo account.

An exception occurred: [InvalidArgumentException] Attempted to convert NULL to integer [content_id] in src/XF/Mvc/Entity/Entity.php on line 688

Here is the code:

PHP:
/**
 * @param $post
 *
 * @return string
 * @throws \Exception
 */
public function insert( $post ) {

   $title = $this->getTitle( $post );
   $message = $this->getMessage( $post );

   // Get the forum using forum_id
   $forum_id = $this->getForumId( $post );

   $forum = \XF::em()->find( 'XF:Forum', $forum_id );

   /** @var \XF\Entity\User $author **/
   $author = \XF::app()->find('XF:User', $post->post_author);

   $thread = \XF::asVisitor($author, function() use ($forum, $title, $message, $post)
   {
      /** @var \XF\Service\Thread\Creator $creator */
      $creator = \XF::service('XF:Thread\Creator', $forum);
      $creator->setContent( $title, $message );
      $creator->setPrefix( $this->getForumId( $post ) );
      $creator->setTags( $this->getTags( $post ) );
      $creator->setIsAutomated();

      if (!$creator->validate())
      {
         return null;
      }

      $creator->save();
      $this->postMeta( $creator, $post );

   });

   $user = \XF::visitor();

   /** @var \XF\Repository\UserAlert $alertRepo */
   $alertRepo = \XF::app()->repository('XF:UserAlert');
   $alert = $alertRepo->alertFromUser($user, $author, 'post', $thread->first_post_id, 'mention');

   return $alert;
}
 
OK. Figured out which in the NULL. The $thread is not being pulled. As soon as I pull the $thread_id from the WP post meta table then the alert fires without the error.

However, I'm using 'mention' and wonder if there is a better alert.

Looks like 'insert' is more appropriate.
 
I feel like I should warn you that using $this inside anonymous functions / closures can be dodgy depending on the PHP versions you are targetting.

Support for it was introduced in PHP 5.4.


Fillip
 
  • Like
Reactions: LPH
Thank you. I’m very new to closures. I’m not sure of any other way to calling the postMeta method, and passing the $creator and $post.
 
You can always just require 5.4 as the minimum version, I'm not sure if XF2 even supports 5.3. I know it won't in 2.1.

I just wanted to let you know, you shouldn't have to change your code :)


Fillip
 
You can always just require 5.4 as the minimum version, I'm not sure if XF2 even supports 5.3. I know it won't in 2.1.

I just wanted to let you know, you shouldn't have to change your code :)


Fillip

5.4 is the minimum for my plugin; however, I’m not sure if there is a better way.
 
Top Bottom