Showing posts with label Dynamic constraint alfresco. Show all posts
Showing posts with label Dynamic constraint alfresco. Show all posts

Saturday

Dynamic List Constraints in Alfresco

In Alfresco Share, how do I populate the drop down values from a database. This is something possible using dynamic constraint. So here I go.

To achieve this you need to extend the "ListOfValuesConstraint" class which present in org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint package.

Step-1 (Extend the class):

package org.alfresco.diary.constraint;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;


public class CustomConstraint extends ListOfValuesConstraint implements Serializable {

   private final Logger logger = Logger.getLogger(CustomConstraint.class);
   private static final long serialVersionUID=1;

   @Override
    public void setAllowedValues(List allowedValues) {
    }

    @Override
    public void setCaseSensitive(boolean caseSensitive) {
    }

   public void initialize() {
       super.setCaseSensitive(false);
       this.getDataFromDb();
    }

    protected void getDataFromDb() {

String driverName = "org.gjt.mm.mysql.Driver";
        String serverName = "localhost:3306";
        String dbName = "alfdiary";
        String userName = "alfdiary";
        String password = "alfdiary";

        List<String> allowedValue = new ArrayList<String>();

        try {
            Connection connection = null;
            Class.forName(driverName);
            String url = "jdbc:mysql://" + serverName +  "/" + dbName;
            connection = DriverManager.getConnection(url, userName, password);
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select dropdowns from alfdiary");
            while (rs.next()) {
                allowedValue.add(rs.getString("dropdowns"));
            }
        }
        catch (Exception e) {}
super.setAllowedValues(allowedValue);
   }
}

Step-2 (Create Metadata Model):

Add the following configurations in your meta model.

<constraint name="alfdiary:dropDowns" type="org.alfresco.diary.constraint.CustomConstraint">
<parameter name="allowedValues">
<list></list>
</parameter>
</constraint>

Apply the above constraint to the metadata

Thats it!!!