Skip to content

Instantly share code, notes, and snippets.

@pengmaradi
Created April 23, 2016 19:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pengmaradi/442e8a41f24b4bc7b7334f6e1a5fdec2 to your computer and use it in GitHub Desktop.
Save pengmaradi/442e8a41f24b4bc7b7334f6e1a5fdec2 to your computer and use it in GitHub Desktop.
TYPO3 extbase use eID

TYPO3 Extbase Ajax

ext_localconf.php

<?php
if (!defined('TYPO3_MODE')) {
	die('Access denied.');
}

\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
	'Xp.' . $_EXTKEY,
	'Category',
	array(
		'Category' => 'list, show, search, top, recommend',
		
	),
	// non-cacheable actions
	array(
		'Category' => 'list,search',
		
	)
);

// set ajax get/post site
//$TYPO3_CONF_VARS['FE']['eID_include']['youreidkey'] = 'EXT:extension/Classes/Utility/Ajax.php';
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['youreidkey'] = Xp\Extension\Utility\Ajax::class . '::searchAction';
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['youreidkey2'] = Xp\Extension\Utility\Autocomplete::class . '::competeAction';

Classes/Utility/Ajax.php

<?php
namespace Xp\Extension\Utility;
use TYPO3\CMS\Frontend\Plugin\AbstractPlugin;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Resource\Hook\FileDumpEIDHookInterface;
use TYPO3\CMS\Core\Resource\ProcessedFileRepository;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;

class Ajax extends AbstractPlugin
{
	
	/**
	 * Main method to search a file
	 *
	 * @param ServerRequestInterface $request
	 * @param ResponseInterface $response
	 * @return NULL|ResponseInterface
	 *
	 * @throws \InvalidArgumentException
	 * @throws \RuntimeException
	 * @throws \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
	 * @throws \UnexpectedValueException
	 */
	public function searchAction(ServerRequestInterface $request, ResponseInterface $response) 
	{
		$parameters = array();
		/* $variable = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('variable');
		echo json_encode($parameters); */
		$eid = $this->getGetOrPost($request, 'eID');
		if ($eid) {
			$parameters['eID'] = $eid;
		}

		$variable = $this->getGetOrPost($request, 'variable');
		if ($variable) {
			$parameters['variable'] = $variable;
		}

		$search = trim($parameters['variable'][6]['value']);
		$uid = intval($parameters['variable'][7]['value']);
		//echo json_encode($parameters);

		$content = array();

		foreach ($this->getTheProducts($uid, $search) as $row) {
			$content = $row;
		}
		
		//file
		if($content['file'] == 1) {
			$files = $this->getSysfile($content['uid'], 'file');
			foreach ($files as $row) {
				$content['file'] = $row;
			}
		}
		
		if($content['img'] == 1) {
			$imgs = $this->getSysfile($content['uid'], 'img');
			foreach ($imgs as $row) {
				$content['img'] = $row;
			}
		}
		echo json_encode($content);
	}
	
	/**
	 * 
	 * @param int $uid
	 * @param string $type
	 * @return array
	 */
	protected function getSysfile($uid = 1, $type = 'img')
	{
		$rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
			'*',
			'sys_file',
			'sys_file.uid IN ( SELECT sys_file_reference.uid_local FROM sys_file_reference WHERE sys_file_reference.tablenames = "tx_werkstatt_domain_model_product" AND sys_file_reference.fieldname="'.$type.'" AND sys_file_reference.uid_foreign = "'.$uid.'")'
		);
		
		if (!$rows) {
			$rows = array();
		}
		return $rows;
	}
		
	/**
	 * @param ServerRequestInterface $request
	 * @param string $parameter
	 * @return NULL|mixed
	 */
	protected function getGetOrPost(ServerRequestInterface $request, $parameter)
	{
		return isset($request->getParsedBody()[$parameter])
			? $request->getParsedBody()[$parameter]
			: (isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : null);
	}

	/**
	 * returns the result of the product
	 * 
	 * @param int $uid
	 * @param string $search
	 * @return array
	 */
	protected function getTheProducts($uid = 0, $search = '')
	{

		$now = date('Y-m-d');

		$rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
			'*',
			'tx_werkstatt_domain_model_product',
			'(`name` LIKE "%' .$search. '%" OR `description` LIKE "%'. $search. '%" ) AND `category` = '.$uid.' AND `hidden` = 0 AND `deleted` = 0 AND (`end` = 0 OR `end` >= '.$now.')'
		);


		if (!$rows) {
			$rows = array();
		}


		return $rows;
	}

	/**
	 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
	 */
	protected function getDatabaseConnection()
	{
		return $GLOBALS['TYPO3_DB'];
	}
}

Resources/Private/Templates/Category/List.html

<f:layout name="Default" />
<f:section name="main">
<f:flashMessages />
<div  class="tx_werkstatt" >
	<f:form action="list" name="category" object="{category}" class="werkstatt_form">
		<div class="werkstatt_form">
			<f:form.textfield property="name" class="werkstatt_search" />
			<f:form.select property="uid" options="{categories}" optionValueField="uid" optionLabelField="name"></f:form.select>
			<f:form.submit value="Search" class="werkstatt_submit" />
		</div>
		<div id="results">
		</div>
	</f:form>
	<f:for each="{categories}" as="category">
		<div class="category cat_uid_{category.uid}">
			<f:if condition="{category.products}">
				<br/>
				<h1 class="category_name">
					<f:image image="{category.icon}" alt="{category.icon.originalResource.name}" width="50" />
					{category.name}
				</h1>
			</f:if>
			<f:for each="{category.products}" as="product">
				<div class="product pro_uid_{product.uid}">
					<h2 class="product_name" style="color:{f:if(condition: product.top, then: ' red', else: 'green')}; ">{product.name}</h2>
					<div class="product_img"><f:image image="{product.img}" alt="{product.img.originalResource.name}" width="150" /></div>
					<div class="product_desc">{product.description->f:format.html()}</div>
					<f:link.page pageUid="fileadmin{product.file.originalResource.identifier}" target="_blank" class="product_link">{product.file.originalResource.name}</f:link.page>
				</div>
			</f:for>
		</div>
	</f:for>
	<div class="ajax_test">
		<h2 class="ajax_name" style="color:green;"></h2>
		<div class="ajax_img"></div>
		<div class="ajax_desc"></div>
		<div class="ajax_link"></div>
	</div>
</div>
</f:section>

Configuration/TypoScript/setup.txt

page.includeJSFooter {
	WerkstattAjax = EXT:extension/Resources/Public/Js/extension.js
}
page.includeCSS {
	Werkstatt = EXT:extension/Resources/Public/Css/extension.css
}

Resources/Public/Js/extension.js

(function($){
	$('.werkstatt_submit').click(function(event){
		var search = $('.werkstatt_form').serializeArray();
		$.post(
			'index.php',
			{eID:'youreidkey',variable: search},
			function(data) {
				$('.category').hide();
				$('.ajax_name').text(data.name);
				if(data.top == 1) {
					$('.ajax_name').css({'color':'red'});
				}
				$('.ajax_desc').html(data.description);
				if(data.file.identifier) {
					$('.ajax_link').html('<a href="fileadmin'+data.file.identifier+'"> '+ data.file.name +' </a>');
				}
				if(data.img.identifier) {
					$('.ajax_img').html('<img src="fileadmin'+data.img.identifier+'" width="150" />');
				}
			},'json');
		event.preventDefault();
	});
	/*
	var MIN_LENGTH = 3;
	$('.werkstatt_search').keyup(function() {
		var keyword = $(this).val();
		if(keyword.length >= MIN_LENGTH) {
			$.get( 'index.php', {eID: 'youreidkey2', keyword: keyword })
			.done(function( data ) {
				console.log(data);
				var results = jQuery.parseJSON(data);
				$(results).each(function(key, value) {
					console.log(value);
					$('#results').append('<div class="item">' + value.name + '</div>');
				});
				$('.item').click(function() {
					var text = $(this).text();
					$('.werkstatt_search').val(text);
				});
			});
		}else {
			$('.werkstatt_search').html('');
		}
	}).blur(function(){
			$('#results').fadeOut(500);
	}).focus(function() {		
		$('#results').show();
	});
	*/
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment