I want to display my own extension in TYPO3's CE Shortcut.
The button for my extension is displayed under the listview as button. And I can select an entry and it's saved. But I can't access the selected id in the frontend.
What I tried so far:
I added in /Configuration/TCA/Overrides/tt_content.php the Method addToInsertRecords. So the button to select an entry is shown up in the backend.
defined('TYPO3_MODE') or die();
call_user_func(function () {
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToInsertRecords('tx_eislist_domain_model_eis');
});
To show in Frontend the Typoscript is:
tt_content.shortcut.20.tables := addToList(tx_eislist_domain_model_eis)
tt_content.shortcut.20.conf.tx_eislist_domain_model_eis = USER
tt_content.shortcut.20.conf.tx_eislist_domain_model_eis {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
extensionName = EisList
pluginName = Eis
vendorName = Emma
controller = Eisbar
action = show
switchableControllerActions {
Eisbar {
1 = show
}
}
settings =< plugin.tx_eislist_eis.settings
settings {
insertRecord = 1
useStdWrap = singleRecords
displayMode = single
singleRecords.field = uid
}
}
tt_content.shortcut.variables.shortcuts.tables := addToList(tx_eislist_domain_model_eis)
tt_content.shortcut.variables.shortcuts.conf.tx_eislist_domain_model_eis < tt_content.shortcut.20.conf.tx_eislist_domain_model_eis
In PHP with
$this->settings['singleRecords']
I can access the variable from TypoScript. But I get the string "field" => "uid". Instead of the selected value ID.
I think you need to inject configurationManager to get stdWrap functionality from / in setup typoscript file. Just use a configurationManager variable and an injectFunction in your controller which contains the show action:
/**
* #var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
*/
protected $configurationManager;
/**
* Injects the Configuration Manager and is initializing the framework settings
*
* #param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager Instance of the
* Configuration Manager
*/
public function injectConfigurationManager(
\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
) {
$this->configurationManager = $configurationManager;
$originalSettings = $this->configurationManager->getConfiguration(
\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS
);
// Use stdWrap for given defined settings
if (isset($originalSettings['useStdWrap']) && !empty($originalSettings['useStdWrap'])) {
$typoScriptService = GeneralUtility::makeInstance(TypoScriptService::class);
$typoScriptArray = $typoScriptService->convertPlainArrayToTypoScriptArray($originalSettings);
$stdWrapProperties = GeneralUtility::trimExplode(',', $originalSettings['useStdWrap'], true);
foreach ($stdWrapProperties as $key) {
if (is_array($typoScriptArray[$key . '.'])) {
$originalSettings[$key] = $this->configurationManager->getContentObject()->stdWrap(
$typoScriptArray[$key],
$typoScriptArray[$key . '.']
);
}
}
}
$this->settings = $originalSettings;
}
I want to set the the page title within my extension, so the current {page} object in the Fluid Templates will also show the set title.
$GLOBALS['TSFE']->altPageTitle = $pageTitle; will only set the <title> tag and has no impact to the {page.title}
My Primary Goal: To show the 'correct' title of a detail page within a breadcrumb.
Any ideas how to manipulate that?
I don't know anything about a {page} object in fluid, so I did it with a ViewHelper similar to the one from here
/**
* A view helper for setting the document title in the <title> tag.
*
* = Examples =
*
* <page.title mode="prepend" glue=" - ">{blog.name}</page.title>
*
* <page.title mode="replace">Something here</page.title>
*
* <h1><page.title mode="append" glue=" | " display="render">Title</page.title></h1>
*
* #license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
*/
class PageTitleViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #var bool
*/
protected $escapeOutput = false;
/**
* #param string $mode Method for adding the new title to the existing one.
* #param string $glue Glue the new title to the old title with this string.
* #param string $display If render, this tag displays it's children. By default it doesn't display anything.
* #return string Rendered content or blank depending on display mode.
* #author Nathan Lenz <nathan.lenz#organicvalley.coop>
*/
public function render($mode = 'replace', $glue = ' - ', $display = 'none') {
$renderedContent = $this->renderChildren();
$existingTitle = $GLOBALS['TSFE']->page['title'];
if ($mode === 'prepend' && !empty($existingTitle)) {
$newTitle = $renderedContent.$glue.$existingTitle;
} else if ($mode === 'append' && !empty($existingTitle)) {
$newTitle = $existingTitle.$glue.$renderedContent;
} else {
$newTitle = $renderedContent;
}
$GLOBALS['TSFE']->page['title'] = $newTitle;
$GLOBALS['TSFE']->indexedDocTitle = $newTitle;
if ($display === 'render') {
return $renderedContent;
} else {
return '';
}
}
}
For cached pages and plugins this should work:
$GLOBALS['TSFE']->page['title'] = $pageTitle;
In a custom extbase extension, I need to call a show action, passing it another value than uid (this is a continuation of Use other than primary key as RealURL id_field).
As the value "other than uid" is not resolved, it results in the exception http://wiki.typo3.org/Exception/CMS/1297759968
EDIT: here's the current working (but ugly) Controller code:
/**
* ItemController
*/
class ItemController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
/**
* itemRepository
*
* #var \STUBR\Weiterbildung\Domain\Repository\ItemRepository
* #inject
*/
protected $itemRepository = NULL;
/**
* action list
*
* #return void
*/
public function listAction(\STUBR\Weiterbildung\Domain\Model\Item $item=null) {
if (!empty(\TYPO3\CMS\Core\Utility\GeneralUtility::_GET('tx_weiterbildung_pi1'))){
$this->forward('show');
}
$items = $this->itemRepository->findAll();
$this->view->assign('items', $items);
}
/**
* action show
*
* #param \STUBR\Weiterbildung\Domain\Model\Item $item
* #return void
*/
public function showAction(\STUBR\Weiterbildung\Domain\Model\Item $item=null) {
$tx_weiterbildung_pi1_get = \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('tx_weiterbildung_pi1');
if (!empty($tx_weiterbildung_pi1_get)){
$dfid = intval($tx_weiterbildung_pi1_get['durchfuehrungId']);
}
$items = $this->itemRepository->findByDurchfuehrungId($dfid);
// helpful:
//\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($item);
$this->view->assign('item', $items[0]);
}
}
PS here are the 5 lines that could be used in the Repository if the magical method wouldn't work:
//public function findByDurchfuehrungId($dfid) {
// $query = $this->createQuery();
// $query->matching($query->equals('durchfuehrungId', $dfid));
// return $query->execute();
//}
Yes, when you're using actions with model binding in param it will always look for object by field defined as ID - in our case it's always uid, but remember, that you do not need to bind model automatically, as you can retrive it yourself.
Most probably you remember, that some time ago I advised to use <f:link.page additionalParams="{originalUid:myObj.originalUid}"Click here</f:link.page> instead of <f:link.action...>
In that case your show action would look like this:
public function showAction() {
$item = $this->itemRepository->findByOriginalUid(intval(GeneralUtility::_GET('originalUid')));
$this->view->assign('item', $item);
}
Where findByOriginalUid should work magically without declaration, but even if it doesn't it's just matter of 5 lines in the repo ;)
Other sample
According to the code you pasted I'd use it rather like this, in this case listAction gets a role of dispatcher for whole plugin:
public function listAction() {
// access get param in array
$tx_weiterbildung_pi1_get = \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('tx_weiterbildung_pi1');
$dfId = intval($tx_weiterbildung_pi1_get['durchfuehrungId']);
if ($dfId > 0) { // tx_weiterbildung_pi1 exists and is positive, that means you want to go to showAction
$item = $this->itemRepository->findByDurchfuehrungId($dfId);
if (!is_null($item)) { // Forward to showAction with found $item
$this->forward('show', null, null, array('item' => $item));
}else { // Or redirect to the view URL after excluding single item ID from GET params
$this->redirectToUri($this->uriBuilder->setArgumentsToBeExcludedFromQueryString(array('tx_weiterbildung_pi1'))->build());
}
}
// No `tx_weiterbildung_pi1` param, so it should be displayed as a listAction
$items = $this->itemRepository->findAll();
$this->view->assign('items', $items);
}
/**
* #param \STUBR\Weiterbildung\Domain\Model\Item $item
*/
public function showAction(\STUBR\Weiterbildung\Domain\Model\Item $item = null) {
$this->view->assign('item', $item);
}
Your finder should also getFirst() object if possible:
public function findByDurchfuehrungId($DfId) {
$query = $this->createQuery();
$query->matching($query->equals('durchfuehrungId', $DfId));
return $query->execute()->getFirst();
}
I am experiencing some problems with Window Builder example:
https://developers.google.com/web-toolkit/tools/gwtdesigner/features/custom_composites
When I copy the codes to my Eclipse, I have an error in the code:
customComposite.setFirstFieldBackground(SWTResourceManager
.getColor(SWT.COLOR_YELLOW));
Eclipse tells me that there's no SWTResourceManager.
When I try to exhibit the form in design mode, another error occours in the code:
final Label thirdFieldLabel = new Label(customComposite.getComposite(),
SWT.NONE);
thirdFieldLabel.setText("Third Field");
Error:
org.eclipse.wb.internal.core.utils.exception.DesignerException: 2005 (Null as parent argument.).
Considering that this example is very common in Web, even in the Help Files of the own WindowBuilder, I supose that I hanven't the correct settings/files to my application.
What would I do differently? Thanks!
What is happening is that SWTResourceManager is a class that is created in the plugin when you use the design view to set things like color, it is specific to your plugin. So when you copy code into another plugin that references that class you will get a class not found exception. Easiest thing to do,is copy the code. Delete the set color, set the color in the editor in your new plugin and a SWTResourceManager wil be auto created for that plugin. The second NPE not sure sounds environment specific but as a rule of thumb swt resource manager is bundle specific.
The SWTResourceManager class is usually generated in a com.swtdesigner package when you create a new WindowBuilder project using Eclipse wizard (File > New > Other > WindowBuilder> SWTDesigner).
Try to generate your project using this wizard.
If you still don't have this class generated here is its code :
package com.swtdesigner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
/**
* Utility class for managing OS resources associated with SWT controls such as colors, fonts, images, etc.
* <p>
* !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code> method to release the
* operating system resources managed by cached objects when those objects and OS resources are no longer
* needed (e.g. on application shutdown)
* <p>
* This class may be freely distributed as part of any application or plugin.
* <p>
* #author scheglov_ke
* #author Dan Rubel
*/
public class SWTResourceManager {
////////////////////////////////////////////////////////////////////////////
//
// Color
//
////////////////////////////////////////////////////////////////////////////
private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>();
/**
* Returns the system {#link Color} matching the specific ID.
*
* #param systemColorID
* the ID value for the color
* #return the system {#link Color} matching the specific ID
*/
public static Color getColor(int systemColorID) {
Display display = Display.getCurrent();
return display.getSystemColor(systemColorID);
}
/**
* Returns a {#link Color} given its red, green and blue component values.
*
* #param r
* the red component of the color
* #param g
* the green component of the color
* #param b
* the blue component of the color
* #return the {#link Color} matching the given red, green and blue component values
*/
public static Color getColor(int r, int g, int b) {
return getColor(new RGB(r, g, b));
}
/**
* Returns a {#link Color} given its RGB value.
*
* #param rgb
* the {#link RGB} value of the color
* #return the {#link Color} matching the RGB value
*/
public static Color getColor(RGB rgb) {
Color color = m_colorMap.get(rgb);
if (color == null) {
Display display = Display.getCurrent();
color = new Color(display, rgb);
m_colorMap.put(rgb, color);
}
return color;
}
/**
* Dispose of all the cached {#link Color}'s.
*/
public static void disposeColors() {
for (Color color : m_colorMap.values()) {
color.dispose();
}
m_colorMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// Image
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps image paths to images.
*/
private static Map<String, Image> m_imageMap = new HashMap<String, Image>();
/**
* Returns an {#link Image} encoded by the specified {#link InputStream}.
*
* #param stream
* the {#link InputStream} encoding the image data
* #return the {#link Image} encoded by the specified input stream
*/
protected static Image getImage(InputStream stream) throws IOException {
try {
Display display = Display.getCurrent();
ImageData data = new ImageData(stream);
if (data.transparentPixel > 0) {
return new Image(display, data, data.getTransparencyMask());
}
return new Image(display, data);
} finally {
stream.close();
}
}
/**
* Returns an {#link Image} stored in the file at the specified path.
*
* #param path
* the path to the image file
* #return the {#link Image} stored in the file at the specified path
*/
public static Image getImage(String path) {
Image image = m_imageMap.get(path);
if (image == null) {
try {
image = getImage(new FileInputStream(path));
m_imageMap.put(path, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(path, image);
}
}
return image;
}
/**
* Returns an {#link Image} stored in the file at the specified path relative to the specified class.
*
* #param clazz
* the {#link Class} relative to which to find the image
* #param path
* the path to the image file, if starts with <code>'/'</code>
* #return the {#link Image} stored in the file at the specified path
*/
public static Image getImage(Class<?> clazz, String path) {
String key = clazz.getName() + '|' + path;
Image image = m_imageMap.get(key);
if (image == null) {
try {
image = getImage(clazz.getResourceAsStream(path));
m_imageMap.put(key, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(key, image);
}
}
return image;
}
private static final int MISSING_IMAGE_SIZE = 10;
/**
* #return the small {#link Image} that can be used as placeholder for missing image.
*/
private static Image getMissingImage() {
Image image = new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
//
GC gc = new GC(image);
gc.setBackground(getColor(SWT.COLOR_RED));
gc.fillRectangle(0, 0, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
gc.dispose();
//
return image;
}
/**
* Style constant for placing decorator image in top left corner of base image.
*/
public static final int TOP_LEFT = 1;
/**
* Style constant for placing decorator image in top right corner of base image.
*/
public static final int TOP_RIGHT = 2;
/**
* Style constant for placing decorator image in bottom left corner of base image.
*/
public static final int BOTTOM_LEFT = 3;
/**
* Style constant for placing decorator image in bottom right corner of base image.
*/
public static final int BOTTOM_RIGHT = 4;
/**
* Internal value.
*/
protected static final int LAST_CORNER_KEY = 5;
/**
* Maps images to decorated images.
*/
#SuppressWarnings("unchecked")
private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[LAST_CORNER_KEY];
/**
* Returns an {#link Image} composed of a base image decorated by another image.
*
* #param baseImage
* the base {#link Image} that should be decorated
* #param decorator
* the {#link Image} to decorate the base image
* #return {#link Image} The resulting decorated image
*/
public static Image decorateImage(Image baseImage, Image decorator) {
return decorateImage(baseImage, decorator, BOTTOM_RIGHT);
}
/**
* Returns an {#link Image} composed of a base image decorated by another image.
*
* #param baseImage
* the base {#link Image} that should be decorated
* #param decorator
* the {#link Image} to decorate the base image
* #param corner
* the corner to place decorator image
* #return the resulting decorated {#link Image}
*/
public static Image decorateImage(final Image baseImage, final Image decorator, final int corner) {
if (corner <= 0 || corner >= LAST_CORNER_KEY) {
throw new IllegalArgumentException("Wrong decorate corner");
}
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner];
if (cornerDecoratedImageMap == null) {
cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>();
m_decoratedImageMap[corner] = cornerDecoratedImageMap;
}
Map<Image, Image> decoratedMap = cornerDecoratedImageMap.get(baseImage);
if (decoratedMap == null) {
decoratedMap = new HashMap<Image, Image>();
cornerDecoratedImageMap.put(baseImage, decoratedMap);
}
//
Image result = decoratedMap.get(decorator);
if (result == null) {
Rectangle bib = baseImage.getBounds();
Rectangle dib = decorator.getBounds();
//
result = new Image(Display.getCurrent(), bib.width, bib.height);
//
GC gc = new GC(result);
gc.drawImage(baseImage, 0, 0);
if (corner == TOP_LEFT) {
gc.drawImage(decorator, 0, 0);
} else if (corner == TOP_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, 0);
} else if (corner == BOTTOM_LEFT) {
gc.drawImage(decorator, 0, bib.height - dib.height);
} else if (corner == BOTTOM_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, bib.height - dib.height);
}
gc.dispose();
//
decoratedMap.put(decorator, result);
}
return result;
}
/**
* Dispose all of the cached {#link Image}'s.
*/
public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Font
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps font names to fonts.
*/
private static Map<String, Font> m_fontMap = new HashMap<String, Font>();
/**
* Maps fonts to their bold versions.
*/
private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>();
/**
* Returns a {#link Font} based on its name, height and style.
*
* #param name
* the name of the font
* #param height
* the height of the font
* #param style
* the style of the font
* #return {#link Font} The font matching the name, height and style
*/
public static Font getFont(String name, int height, int style) {
return getFont(name, height, style, false, false);
}
/**
* Returns a {#link Font} based on its name, height and style. Windows-specific strikeout and underline
* flags are also supported.
*
* #param name
* the name of the font
* #param size
* the size of the font
* #param style
* the style of the font
* #param strikeout
* the strikeout flag (warning: Windows only)
* #param underline
* the underline flag (warning: Windows only)
* #return {#link Font} The font matching the name, height, style, strikeout and underline
*/
public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) {
String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline;
Font font = m_fontMap.get(fontName);
if (font == null) {
FontData fontData = new FontData(name, size, style);
if (strikeout || underline) {
try {
Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$
Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$
if (logFont != null && logFontClass != null) {
if (strikeout) {
logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
if (underline) {
logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
}
} catch (Throwable e) {
System.err
.println("Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
font = new Font(Display.getCurrent(), fontData);
m_fontMap.put(fontName, font);
}
return font;
}
/**
* Returns a bold version of the given {#link Font}.
*
* #param baseFont
* the {#link Font} for which a bold version is desired
* #return the bold version of the given {#link Font}
*/
public static Font getBoldFont(Font baseFont) {
Font font = m_fontToBoldFontMap.get(baseFont);
if (font == null) {
FontData fontDatas[] = baseFont.getFontData();
FontData data = fontDatas[0];
font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD);
m_fontToBoldFontMap.put(baseFont, font);
}
return font;
}
/**
* Dispose all of the cached {#link Font}'s.
*/
public static void disposeFonts() {
// clear fonts
for (Font font : m_fontMap.values()) {
font.dispose();
}
m_fontMap.clear();
// clear bold fonts
for (Font font : m_fontToBoldFontMap.values()) {
font.dispose();
}
m_fontToBoldFontMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// Cursor
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps IDs to cursors.
*/
private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>();
/**
* Returns the system cursor matching the specific ID.
*
* #param id
* int The ID value for the cursor
* #return Cursor The system cursor matching the specific ID
*/
public static Cursor getCursor(int id) {
Integer key = Integer.valueOf(id);
Cursor cursor = m_idToCursorMap.get(key);
if (cursor == null) {
cursor = new Cursor(Display.getDefault(), id);
m_idToCursorMap.put(key, cursor);
}
return cursor;
}
/**
* Dispose all of the cached cursors.
*/
public static void disposeCursors() {
for (Cursor cursor : m_idToCursorMap.values()) {
cursor.dispose();
}
m_idToCursorMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// General
//
////////////////////////////////////////////////////////////////////////////
/**
* Dispose of cached objects and their underlying OS resources. This should only be called when the cached
* objects are no longer needed (e.g. on application shutdown).
*/
public static void dispose() {
disposeColors();
disposeImages();
disposeFonts();
disposeCursors();
}
}
There is a multiselect element in form. It's needed to validate how many items are selected in it (min and max count).
The trouble is that when the element can have multiple values, then each value is validated separately.
I tried to set isArray to false to validate the value with my custom validator ArraySize, but new problem appeared: the whole array-value is passed to InArray validator and the validation fails. So I had to turn it off by setting registerInArrayValidator to false.
Now I can validate the value for number of selected values but can not validate for their correspondence to provided options.
Is there a way to solve the problem without creating one more custom validator?
Note: I have assume this is Zend 1.
The only way I could see to do this was to extend Multiselect and use a custom isValid. This way you can see the full array of values and not just one value at a time.
Below is my custom Multiselect class
<?php
/**
* My_MinMaxMultiselect
*/
class My_MinMaxMultiselect extends Zend_Form_Element_Multiselect
{
/**
* Validate element contains the correct number of
* selected items. Check value against minValue/maxValue
*
* #param mixed $value
* #param mixed $context
* #return boolean
*/
public function isValid($value, $context = null)
{
// Call Parent first to cause chain and setValue
$parentValid = parent::isValid($value, $context);
$valid = true;
if ((('' === $value) || (null === $value))
&& !$this->isRequired()
&& $this->getAllowEmpty()
) {
return $valid;
}
// Get All Values
$minValue = $this->getMinValue();
$maxValue = $this->getMaxValue();
$count = 0;
if (is_array($value)) {
$count = count($value);
}
if ($minValue && $count < $minValue) {
$valid = false;
$this->addError('The number of selected items must be greater than or equal to ' . $minValue);
}
if ($maxValue && $count > $maxValue) {
$valid = false;
$this->addError('The number of selected items must be less than or equal to ' . $maxValue);
}
return ($parentValid && $valid);
}
/**
* Get the Minimum number of selected values
*
* #access public
* #return int
*/
public function getMinValue()
{
return $this->getAttrib('min_value');
}
/**
* Get the Maximum number of selected values
*
* #access public
* #return int
*/
public function getMaxValue()
{
return $this->getAttrib('max_value');
}
/**
* Set the Minimum number of selected Values
*
* #param int $minValue
* #return $this
* #throws Bad_Exception
* #throws Zend_Form_Exception
*/
public function setMinValue($minValue)
{
if (is_int($minValue)) {
if ($minValue > 0) {
$this->setAttrib('min_value', $minValue);
}
return $this;
} else {
throw new Bad_Exception ('Invalid value supplied to setMinValue');
}
}
/**
* Set the Maximum number of selected values
*
* #param int $maxValue
* #return $this
* #throws Bad_Exception
* #throws Zend_Form_Exception
*/
public function setMaxValue($maxValue)
{
if (is_int($maxValue)) {
if ($maxValue > 0) {
$this->setAttrib('max_value', $maxValue);
}
return $this;
} else {
throw new Bad_Exception ('Invalid value supplied to setMaxValue');
}
}
/**
* Retrieve error messages and perform translation and value substitution.
* Overridden to avoid errors from above being output once per value
*
* #return array
*/
protected function _getErrorMessages()
{
$translator = $this->getTranslator();
$messages = $this->getErrorMessages();
$value = $this->getValue();
foreach ($messages as $key => $message) {
if (null !== $translator) {
$message = $translator->translate($message);
}
if (($this->isArray() || is_array($value))
&& !empty($value)
) {
$aggregateMessages = array();
foreach ($value as $val) {
$aggregateMessages[] = str_replace('%value%', $val, $message);
}
// Add additional array unique to avoid the same error for all values
$messages[$key] = implode($this->getErrorMessageSeparator(), array_unique($aggregateMessages));
} else {
$messages[$key] = str_replace('%value%', $value, $message);
}
}
return $messages;
}
}
To use this in the form where the User must select exactly 3 options:
$favouriteSports = new MinMaxMultiselect('favourite_sports');
$favouriteSports
->addMultiOptions(array(
'Football',
'Cricket',
'Golf',
'Squash',
'Rugby'
))
->setRequired()
->setLabel('Favourite Sports')
->setMinValue(3)
->setMaxValue(3);
While it's nice when you can squeeze by without needing to write a custom validator, there is nothing wrong with writing one when you need to do something slightly out of the ordinary.
This sounds like one of those cases.