diff --git a/core/modules/comment/src/CommentForm.php b/core/modules/comment/src/CommentForm.php
index f8b2e75c6f97fe622d0a9f6b9035e120d39c26b5..1b2d8f02201df0131d12a8a2587680032054c034 100644
--- a/core/modules/comment/src/CommentForm.php
+++ b/core/modules/comment/src/CommentForm.php
@@ -320,7 +320,7 @@ public function buildEntity(array $form, FormStateInterface $form_state) {
     // Validate the comment's subject. If not specified, extract from comment
     // body.
     if (trim($comment->getSubject()) == '') {
-      if ($comment->hasField('comment_body')) {
+      if ($comment->hasField('comment_body') && !$comment->comment_body->isEmpty()) {
         // The body may be in any format, so:
         // 1) Filter it into HTML
         // 2) Strip out all HTML tags
@@ -330,7 +330,7 @@ public function buildEntity(array $form, FormStateInterface $form_state) {
       }
       // Edge cases where the comment body is populated only by HTML tags will
       // require a default subject.
-      if ($comment->getSubject() == '') {
+      if (trim($comment->getSubject()) == '') {
         $comment->setSubject($this->t('(No subject)'));
       }
     }
diff --git a/core/modules/comment/tests/src/Functional/CommentInterfaceTest.php b/core/modules/comment/tests/src/Functional/CommentInterfaceTest.php
index c82d1b91a81d585baa14d4a87800a164419c36df..dfc8a21dc8fbebf674db117ed5d3da97a1878547 100644
--- a/core/modules/comment/tests/src/Functional/CommentInterfaceTest.php
+++ b/core/modules/comment/tests/src/Functional/CommentInterfaceTest.php
@@ -8,6 +8,7 @@
 use Drupal\comment\Entity\Comment;
 use Drupal\Core\Entity\Entity\EntityViewDisplay;
 use Drupal\Core\Entity\Entity\EntityViewMode;
+use Drupal\field\Entity\FieldConfig;
 use Drupal\user\RoleInterface;
 use Drupal\filter\Entity\FilterFormat;
 
@@ -238,6 +239,16 @@ public function testAutoFilledSubject() {
     $body_text2 = 'AQuickBrownFoxJumpedOverTheLazyDog';
     $comment2 = $this->postComment(NULL, $body_text2, '', TRUE);
     $this->assertEquals('AQuickBrownFoxJumpedOverTheL…', $comment2->getSubject());
+
+    // Make the body field non required.
+    $comment_body_field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
+    $comment_body_field->setRequired(FALSE)->save();
+    // Try to post a comment without any value in body and subject fields.
+    $this->drupalGet('node/' . $this->node->id());
+    // Ensure that there are no PHP errors or warnings when automatically
+    // generating the subject. This occurs when the comment body is empty.
+    $comment2 = $this->postComment(NULL, '', '', TRUE);
+    $this->assertEquals('(No subject)', $comment2->getSubject());
   }
 
   /**