Drupal custom module code working differently for logged in users and anonymous users I have the below simple if else condition for a custom module form page in buildForm method for recommendation submission. I would like my form to be displayed to all user who visit for the first time and submits and cannot submit again from the same url. If the url is used again it should just display the thank you message(if already submitted). The below code wrks perfectly if the user is logged in. Like if the user is logged in, he comes and submit, thank you message is displayed everything is saved in DB correctly. The problem comes when anonymous user comes. The page loads as expected. But after filling up the details and submit button is clicked. It reloads and the same form is displayed again(instead of the thank yo message) and then if I submit again it displays validation errors even though the fields are there and gives the thank you message. Can anyone explain me why its behaving differently for logged in and anonymous users.

    public function buildForm(array $form, FormStateInterface $form_state)
    {
       if($this-&gt;CheckRecommendationStatus())
       {
          $form = array();
          $form['form_label'] = [
          '#type' =&gt; 'processed_text',
          '#text' =&gt; t('&lt;h3&lt;strong&gt;Thank you already submitted&lt;/h3&gt;'),
          ];
        }
        else if($this-&gt;validateUrl())
        {
           $form = array();
           //it will have controls and submit button.if submit is clicked those values will be saved
        }
        return $form;
     }
     //This below method check the Database whether already the submission is made or not
     public function CheckRecommendationStatus()
     {
           $this-&gt;setUniqueIdentifier(htmlspecialchars($_GET["rec"]));
           $query = \Drupal::database()-&gt;select('m_tablename', 'mr');
           $query-&gt;fields('mr',array('id'));
           $query-&gt;condition('mr.column_name',$this-&gt;getUniqueIdentifier());
           $query-&gt;range(0,1);      
           $results = $query-&gt;execute()-&gt;fetchAll();
           return $results;
     }
This sounds like a caching issue. Check the cache api and make sure to set the $form['#cache'] appropriately. 

When the anonymous user submits the form, it's submitted fine, but when the form loads the second time Drupal doesn't know that it should not be serving the original cached form.

You can quickly confirm that it is a caching issue by set the form to not be cached like:

$form['#cache'] = [
  'max-age' =&gt; 0,
];