0

I have created a custom module that should show my custom block above the controller generated table. The block shows in other pages but not in the page where it is supposed to show. Found out that it does not appear in all the controller generated tables I have created. i don't know what I did wrong. Here are my codes:

My custom block:

namespace Drupal\positions\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block with a simple text.
 *
 * @Block(
 *   id = "positionref_block",
 *   admin_label = @Translation("PositionRef Block"),
 * )
 */
class SearchPositionRefBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    // return [
    //   '#markup' => $this->t('This is a simple block!'),
    // ];
     return \Drupal::formBuilder()->getForm('Drupal\positions\Form\SearchPositionRefForm');
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access positions');
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['my_block_settings'] = $form_state->getValue('my_block_settings');
  }
}

My Custom Form:

namespace Drupal\positions\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

class SearchPositionRefForm extends FormBase {
  /**
     * {@inheritdoc}
     */
    public function getFormId() {
      return 'search_positionref_form';
    }
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $conn = Database::getConnection();
        $record = array();
        $userid = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->uid->value;


        $form = array();

        $form['p'] =[
          '#type'=>'fieldset',
          '#prefix' => '<div class="container"><div class="col-sm-11">',
          '#suffix' => '</div></div>',
        ];

        $form['p']['position'] = array(
            '#type' => 'textfield',
            '#title' => 'Position Name',
            '#required' => TRUE,
            '#maxlength' => 255,
        );

        $form['p']['submit'] = array([
            '#type' => 'submit',
            '#value' => 'Search',
        ]);

        return $form;
    }


    /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $userid = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->uid->value;
    $username = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->getUsername();

    $field=$form_state->getValues();
    $position = $field['position'];

        global $base_url;
        $response = new RedirectResponse($base_url.'/positions/reference_list');
        $response->send();
    }   

}

My Controller:

namespace Drupal\positions\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Component\Render\FormattableMarkup;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Form\FormBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Component\Utility\Html;
use Drupal\Core\Block\BlockBase;


class PositionRefController extends ControllerBase {
    public function index(){

        global $base_path;
        $add_record_form = $this->add_record_form();
        $add_record_form = render($add_record_form);

        $display = $this->display();
        $display = render($display);


        return [
          '#markup' =>
            $add_record_form.
            $display
          ];

    }

    public function add_record_form(){
      $user = \Drupal::currentUser();
      $uid = $user->id();

      $add_button = [
        '#type' => 'link',
        '#prefix' => '<div class="col-sm-2"><div class="btn btn1" id="button-create-new">
          <i class="fa fa-plus-square"></i> Add New Record</div></div>',
        '#suffix' => '',
        ];

        $add_url = Link::fromTextAndUrl($add_button, Url::fromRoute('positions.add_positionref'))->toString();
        return $add_url;
    }

    public function display()
    {
      $positionrefList = $this->positionrefList();
      $positionrefList = render($positionrefList);
      $content ='
      <br>
      <div class="container">
        <div class="row">

          <div class="col-sm-12">
            <div class="panel panel-default">

              <div class="panel-body">
                <div class="tab">
           ';
                  $content .= $positionrefList;
                  $content .='

                </div>

              </div>
            </div>



        </div>
      </div>


      ';
      return $content;
    }

    public function positionrefList(){
        $user = \Drupal::currentUser();
        $uid = $user->id();

        $header_table = array(
            '#',
            'position' => t('Position'),
            'edit' => t('Edit'),
            'delete' => t('Delete'),
        );

        $conn = \Drupal\Core\Database\Database::getConnection();
        $query= $conn->select('position_ref', 'p');
        $query->fields('p');
        $query->orderBy('position');

        $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
        ->orderByHeader($header_table);
        $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')
        ->limit(15);
        $result = $pager->execute();

        $edit_button = [
          '#type' => 'link',
          '#prefix' => '<div class="center"><i class="fa fa-edit">',
          '#suffix' => '</i></div>',
        ];
        $delete_button = [
          '#type' => 'link',
          '#prefix' => '<div class="center"><i class="fa fa-trash">',
          '#suffix' => '</i><div>',

        ];            


        $rows = array();
        $nr = 1;
        foreach ($result as $data) {
          $edit_url = Link::fromTextAndUrl($edit_button, Url::fromRoute('basic_info.edit_education_form', ['educ'=>$data->id]))->toString(); 
          $delete_url = Link::fromTextAndUrl($delete_button, Url::fromRoute('basic_info.delete_education_form', ['educ'=>$data->id]))->toString(); 


          $rows[] = 
            ['data' => [
            '#' => $nr,
            'position' => $data->position,
            'edit' =>  $edit_url,
            'delete' =>  $delete_url,

            ]];
            $nr++;
        }


        $form['table'] = [
            '#type' => 'table',
            '#header' => $header_table,
            '#rows' => $rows,
            '#empty' => t('No record found'),
            '#sticky' => TRUE,
        ];
        $form['pager'] = array(
          '#type' => 'pager'
        );
        return $form;

    }

}
  • You should never render() in a controller. But you don't need the block, you can put the form directly in the controller or ditch the controller too, and put the table in the form. – 4k4 Sep 30 at 8:27
  • I can put the table in the form? How? – ylleigh12 Sep 30 at 23:43
  • $form['table'] = ['#type' => 'table', ...] and if you want to rebuild the form and the table then don't redirect, but request a rebuild in the submit handler: $form_state->setRebuild(), see drupal.stackexchange.com/questions/223780/… – 4k4 Oct 1 at 6:18
  • Thanks, I already added the table directly on the form and redirect it to the same form for the searching and is working just fine. – ylleigh12 Oct 2 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.