001/*
002 *  Copyright 2022 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.forms;
017
018import org.apache.commons.lang.StringUtils;
019
020import org.ametys.runtime.i18n.I18nizableText;
021
022import com.google.common.collect.ArrayListMultimap;
023import com.google.common.collect.Multimap;
024
025/**
026 * Form errors.
027 */
028public class FormErrors
029{
030    /** The errors as a Map of field ID -> error messages. */
031    protected Multimap<String, I18nizableText> _errors;
032    
033    /**
034     * Default constructor.
035     */
036    public FormErrors()
037    {
038        this(ArrayListMultimap.create());
039    }
040    
041    /**
042     * Constructor with parameters.
043     * @param errors the errors.
044     */
045    public FormErrors(Multimap<String, I18nizableText> errors)
046    {
047        this._errors = errors;
048    }
049    
050    /**
051     * Get the errors.
052     * @return the errors
053     */
054    public Multimap<String, I18nizableText> getErrors()
055    {
056        return _errors;
057    }
058    
059    /**
060     * Set the errors.
061     * @param errors the errors to set
062     */
063    public void setErrors(Multimap<String, I18nizableText> errors)
064    {
065        this._errors = errors;
066    }
067    
068    /**
069     * Add an error.
070     * @param fieldId the field ID.
071     * @param error the error message.
072     */
073    public void addError(String fieldId, I18nizableText error)
074    {
075        if (StringUtils.isNotEmpty(fieldId) && error != null)
076        {
077            if (_errors.containsKey(fieldId))
078            {
079                _errors.get(fieldId).add(error);
080            }
081            else
082            {
083                _errors.put(fieldId, error);
084            }
085        }
086    }
087    
088    /**
089     * Tests if the form has errors.
090     * @return true if there are errors, false otherwise.
091     */
092    public boolean hasErrors()
093    {
094        if (!_errors.isEmpty())
095        {
096            return true;
097        }
098        return false;
099    }
100}