简体   繁体   中英

Typo3 - how to add a custom field in join collection?

Problem

There is an Extension, let's named ProjectExams, which shows the list of exams. There is a structure with Controller, Model, ModelRepository, Tables and Template. Everything works using Extbase for retrieving the data collections (lazy loading models bindings).

We have two requests:
* bypass the bindings and retrieve the collection using only one "raw" SQL query, with joins in DB;
* return in View(Template) an array without objects elements

Background and code

The Model Collection represents a list of exams. Apart from UID, Title, Description and rest of the fields which are in MySQL Table "domain_model_exams", the Template file must show also the location (the City) for each exam. Then the ModelRepository uses to have a method "findExamsByDate", called by the Controller, where it's requested to implement this single "raw" SQL query.

Controller code

public function listAction($success = null, $message = '')
{
    // here some code, not related to the issue

    $examStartFrom = $_POST['exams']['examStartFrom'] ?? null;
    $examStartTo   = $_POST['exams']['examStartTo'] ?? null;
    $dateBoundary = new DateBoundary($examStartFrom, $examStartTo);

    $isAdmin = ($role === User::USER_TYPES_EXAMINER_ADMIN && $dateBoundary->isValid());

    $exams = $this->examRepository->findExamsByDate(
            $dateBoundary->getFromDate(),
            $dateBoundary->getToDate(),
            $isAdmin
        );

    // here some code, not related to the issue

    $this->view->assign('exams', $exams);

    // here some code, not related to the issue
}

The Template(View) file expects a variable exams.city

In the Model file, we have a protected var $city with set and get functions

ModelRepository code

/**
 * Get all exams within a certain time frame
 *
 * @param \DateTime $from
 * @param \DateTime $to
 * @param bool      $isAdmin
 *
 * @return QueryResultInterface|array|Exam[]
 *
 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException
 */
 public function findExamsByDate(\DateTime $from, \DateTime $to, bool $isAdmin = false)
 {
    $whereConditions = []; 
    $query = $this->createQuery();

    // here some lines with where conditions related to time frame
    if ($from instanceof \DateTime) {
        $whereConditions[] = 's.course_start >= ' . $from->getTimestamp();
    }

    if ($to instanceof \DateTime) {
        $whereConditions[] = 's.course_start <= ' . $to->getTimestamp();
    }

    $query->statement(sprintf('
        SELECT s.*, a.place as city
         FROM domain_model_exams AS s
           LEFT JOIN domain_model_address AS a ON s.address_id = a.uid
         WHERE %1$s
         ORDER BY s.course_start ASC
    ', implode(' AND ', $whereConditions)));

    return $query->execute();
}

Results

Using \\TYPO3\\CMS\\Extbase\\Utility\\DebuggerUtility::var_dump($exams); we get this object:

TYPO3\CMS\Extbase\Persistence\Generic\QueryResultprototypeobject (762 items)
   0 => Domain\Model\Examprototypepersistent entity (uid=5, pid=568)
      title => protected 'The mighty title for this exam' (xx chars)
      descriptionText => protected '' (0 chars)
      courseStart => protectedDateTimeprototypeobject (2014-12-05T09:00:00+00:00, 1417770000)
      courseEnd => protectedDateTimeprototypeobject (2014-12-07T11:30:00+00:00, 1417951800)
      .
      . other fields
      .
      city => protected NULL
      .
      . other fields
      .

Our expectation is to have city => protected 'Frankfurt am Main' (17 chars) not NULL , because we get this when the SQL query is run against database.

Solution

  1. remove from the Model the property and get-set functions related to this field 'city'; in our specific case:
/**
 * @var \Domain\Repository\AddressRepository
 */
  1. Typo3 extension use to have a specific config file, used for custom Model configurations, like add a new custom field /Exams/Configuration/ TCA /domain_model_exam.php In this file, in return array, we must add a new element, which contains specific configuration for this new field:
return call_user_func(function ($_EXTKEY) {
    // some other settings
    return [
        'ctrl' => [
            // other fields
            'city' => 'city',
            // more fields
        ],
        'interface' => [
            'showRecordFieldList' => 'field_a, field_b, city, field_n',
        ],
        'types' => [
            '1' => ['showitem' => 'field_a, field_b, city, field_n'],
        ],
        'columns' => [    
            'city' => [
                'exclude' => 1,
                'label' => 'LLL:EXT:exams/Resources/Private/Language/locallang_db.xlf:domain_model_exam.city',
                'config' => [
                    'type' => 'input',
                    'size' => 30,
                    'eval' => 'trim'
                ],
          ],
    ];
}, 'seminars');

Any other better solution for these specific requests, it will be highly appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM