Create taxonomy reference field programatically in Drupal 8 How to create taxonomy reference field programatically in a custom form?

$tags = array();// get taxonomy terms from a vocabulary.

$form['custom_tags'] = array(
  '#type' =&gt; 'select',
  '#options' =&gt; $tags,
  '#title' =&gt; $this-&gt;t('Preffered Tags'),
  '#default_value' =&gt; $this-&gt;store-&gt;get('custom_tags') ? $this-&gt;store-&gt;get('custom_tags') : '',
);


How can I get taxonomy terms from a vocabulary? Or how to create a term reference field in custom form?
I did it by following method. If any other better way to achieve this, please suggest.

$tag_terms = \Drupal::entityManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree('tags');
$tags = array();
foreach ($tag_terms as $tag_term) {
    $tags[$tag_term-&gt;tid] = $tag_term-&gt;name;
}

$form['custom_tags'] = array(
  '#type' =&gt; 'select',
  '#options' =&gt; $tags,
  '#title' =&gt; $this-&gt;t('Preffered Tags'),
  '#default_value' =&gt; $this-&gt;store-&gt;get('custom_tags') ? $this-&gt;store-&gt;get('custom_tags') : '',
);