美文网首页
处理block的配置表单

处理block的配置表单

作者: liboxiang | 来源:发表于2019-02-19 21:00 被阅读3次

    官网:https://www.drupal.org/docs/8/creating-custom-modules/add-a-form-to-the-block-configuration

    代码:

    <?php
    
    namespace Drupal\first_form\Plugin\Block;
    
    use Drupal\Core\Block\BlockBase;
    use Drupal\Core\Block\BlockPluginInterface;
    use Drupal\Core\Form\FormStateInterface;
    
    /**
     * Provides a 'Hello' Block.
     *
     * @Block(
     *   id = "first_form_block",
     *   admin_label = @Translation("first form block"),
     *   category = @Translation("First Form World"),
     * )
     */
    class FirstFormBlock extends BlockBase {
    
      /**
       * {@inheritdoc}
       */
      public function build() {
         
        $config = $this->getConfiguration();
      
        if (isset($config['first_form_block_setting']) && !empty($config['first_form_block_setting'])) {
          $name = $config['first_form_block_setting'];
        }
        else {
          $name = $this->t('to no one');
        }
      
        return array(
          '#markup' => $this->t('Hello @name!', array('@name' => $name)),
        );
      }
    
        /**
       * {@inheritdoc}
       */
      public function blockForm($form, FormStateInterface $form_state) {
        $form = parent::blockForm($form, $form_state);
    
        $config = $this->getConfiguration();
    
        $form['first_form_block_setting'] = array(
          '#type' => 'textfield',
          '#title' => $this->t('Who'),
          '#description' => $this->t('Who do you want to say hello to?'),
          '#default_value' => isset($config['first_form_block_setting']) ? $config['first_form_block_setting'] : '',
        );
    
        return $form;
      }
      
      /**
       * {@inheritdoc}
       */
      public function blockSubmit($form, FormStateInterface $form_state) {
        parent::blockSubmit($form, $form_state);
        $values = $form_state->getValues();
        $this->configuration['first_form_block_setting'] = $values['first_form_block_setting'];
      }
    }
    

    相关文章

      网友评论

          本文标题:处理block的配置表单

          本文链接:https://www.haomeiwen.com/subject/zokjpxtx.html