Hi all,
I'm working around OneToMany relationships between objects,
I wont to add them to my web interface just with CRUDify so I'm working on a 
couple of special fields.
I have already done them but it seems that I need to do some save every time 
one reference is added or deleted and this cause me some issues in 
the "create" page obviously... any idea?
I post below my code of a couple of fields

First one --> generical reference to other objects 

class MultiReferenceField [T<:KeyedMapper[Long,T],O<:KeyedMapper[Long,O]]
(theOwner: T,
                                                                 foreign: => 
KeyedMetaMapper[Long, O],
                                                                 foreignField: 
=> MappedLongForeignKey[O,T])
extends MappedField[List[O], T] with LifecycleCallbacks {
  
  type KeyType = Long
  type KeyedForeignType = O
  type OwnerType = T
  
  def defined_? = !getAll.isEmpty
  def fieldOwner = theOwner
  def doneWithSave = {}

  /* I wont to not save it in a column on the databast but because of 
metamapper I need to
   * otherwise I cannot provide visualization
   */
  override def ignoreField_? = false
  override def dbDisplay_? = true
  override def writePermission_? = true
  /*override def dbPrimaryKey_? = false
  override def dbForeignKey_? = false
  override def dbIndexed_? = false
*/
  
  def can: Box[List[O]] = if (defined_?) Full(is) else Empty

  override def toString = if (defined_?) super.toString else "NULL"

  override def is = getAll
  
  def apply(v: Box[O]): T = 
          (v) match {
                case Full(o) => this(o)
                case _ => theOwner
          }
  def apply(v: O): T = 
    this + v
  
  def empty_!(): Unit = getAll.foreach{ o => this - o}
  
  def set_!(l: List[O]) = {
    this.empty_!
    l.foreach{o => this + o}
  }
  
  def + (l: Long): T = this + foreign.find(By(foreignField,l))
  def + (v: Box[O]): T = (v) match {
    case Full(ext: O) => this + ext
    case _ => theOwner
  }
  def + (v: O): T = {
    (v.fieldByName(foreignField.name)) match {
      case Full(f) => {
                if 
(theOwner.primaryKeyField==theOwner.primaryKeyField.defaultValue) 
                        {
                          theOwner.save
                          this + (v)
                        }
                f.setFromAny(theOwner.primaryKeyField.is)
                v.save
      }
      case _ => {}
    }
    theOwner
  }
  
  def - (l: Long): T = this + foreign.find(By(foreignField,l))
  def - (v: Box[O]): T = (v) match {
    case Full(ext: O) => this - ext
    case _ => theOwner
  }
  def - (v: O): T = {
    (v.fieldByName(foreignField.name)) match {
      case Full(f) => 
        if (f == theOwner.primaryKeyField) {
          beforeRemoveElem(v)
          if (theOwner.primaryKeyField==theOwner.primaryKeyField.defaultValue) 
                        {
                          theOwner.save
                          this - (v)
                        }
          f.setFromAny(null)
          v.save
          afterRemoveElem(v)
        }
      case _ => {}
    }
    this.is
    theOwner
  }
  
  /* To override for deleting the relationship KeyedMapper*/
  def afterRemoveElem(v: O) = {}
  def beforeRemoveElem(v: O) = {}
  
  override def beforeDelete = this.empty_!
  
  def getAll: List[O] = 
foreign.findAll(By(foreignField,theOwner.primaryKeyField.is))
  
  def defaultValue: List[O] = Nil
  def dbFieldClass = classOf[List[O]]

  def targetSQLType = Types.BOOLEAN

  def asJsExp = JE.Num(theOwner.primaryKeyField.is)

  def real_convertToJDBCFriendly(value: List[O]): Object = new 
_root_.java.lang.Integer(if (!(value.isEmpty)) 1 else 0)

  // def asJsExp = JE.Num(is)

  def jdbcFriendly(field : String) = new _root_.java.lang.Integer(if (!
(this.getAll.isEmpty)) 1 else 0)
  
  protected def i_obscure_!(in : List[O]) = defaultValue

  protected def i_is_! = getAll
  protected def i_was_! = Nil
  
  override def setFromAny(in: Any) = {
    in match {
      case n: Long => this + n
      case n: Number => this + n.longValue
      case Some(n: Number) => this + n.longValue
      case null => this.empty_!
      case s: String => this + Helpers.toLong(s)
      case o => this + Helpers.toLong(o)
    }
    getAll
  }
  
  /**
   * Set the field to the value
   */
    
  protected def real_i_set_!(value : List[O]): List[O] = getAll
  
  def buildSetActualValue(accessor: Method, data: AnyRef, columnName: 
String) : (T, AnyRef) => Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferenceField[ T, O] =>
  try {
        (foreign.find(By(foreignField,v.asInstanceOf[Long]))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }}
  catch {case _ => null}})

  def buildSetLongValue(accessor: Method, columnName : String) : (T, Long, 
Boolean) => Unit =
  (inst, v, isNull) => doField(inst, accessor, {case f: MultiReferenceField[ 
T, O] => 
  (foreign.find(By(foreignField,v))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }})

  def buildSetStringValue(accessor: Method, columnName: String): (T, String) 
=> Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferenceField[ T, O] => 
  (foreign.find(By(foreignField,v.toLong))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }})

  def buildSetDateValue(accessor : Method, columnName : String) : (T, Date) => 
Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferenceField[ T, O] => 
null})

  def buildSetBooleanValue(accessor : Method, columnName : String) : (T, 
Boolean, Boolean) => Unit = null

  /**
   * Given the driver type, return the string required to create the column in 
the database
   */
  def fieldCreatorString(dbType: DriverType, colName: String): String = 
colName + " " + dbType.longColumnType
  
  
  /* HTML visualization */

  override def _toForm: Box[NodeSeq] = Full(doFormHtml)
  def doFormListHtml = 
    <ul>
         <table>
     {for ( o <- this.getAll) 
        yield(<tr>
                        <td><li>{calcLink(o)}</li></td>
                        <td>{removeButton(o)}</td>
                  </tr>
        )}
     </table>
        </ul>
  def doFormHtml: NodeSeq = 
    <div id={"_values-"+this.name} class={divFormClass}>
        {doFormListHtml}
    {addButton}
    </div>
    
  def divFormClass = "multiReferenceField"
    
  def removeButtonName = "-"
                                                                          
  def removeButton(foreignElem: O): NodeSeq =
          SHtml.ajaxButton(removeButtonName, () => doRemoveElement(foreignElem))
  
  def doRemoveElement(foreignElem: O): JsCmd = {
    this - foreignElem
    applyChanges
  } 
  
  def addButtonName = "+"

  var actualSelection = ""
  def addButton: NodeSeq =
          <div>
          {SHtml.ajaxSelect(
                                ((foreign.findAll(By(foreignField,null)).map(o 
=> 
(calcForeignName(o),o.primaryKeyField.is.toString))) ::: 
List(("",""))).toSeq, Full(""),
                 s => setActualSelection(s), ("id",
{this.name+"-addSelection"}))}
          {SHtml.ajaxButton(addButtonName, () => doAddElement)}
      </div>
  
  def setActualSelection(s: String) = {
    actualSelection = s
    JsCmds.Noop
  }
      
  def doAddElement: JsCmd = {
    this + 
foreign.getSingleton.find(By(foreign.primaryKeyField,tryo(actualSelection.toLong)
 
openOr 0L))
    applyChanges
  }

  def applyChanges = JsCmds.SetHtml(("_values-"+this.name),doFormHtml)
  
  def makeLinkOnView = false
  
  /* to override if you wont right links*/
  def foreignViewPathString: String = "" 
  
  def calcForeignName(foreignElem: O): String = 
foreignElem.primaryKeyField.toString
  def calcForeignNameHtml(foreignElem: O): NodeSeq = 
Text(calcForeignName(foreignElem))
  
  def calcLink(foreignElem: O): NodeSeq = if (makeLinkOnView) 
                                                                        <a 
href={foreignViewPathString+"/"+foreignElem.primaryKeyField}>{calcForeignNameHtml(foreignElem)}</a>
                                 else 
                                        {calcForeignNameHtml(foreignElem)}
  
  override def asHtml = <ul>
                                                {for ( o <- this.getAll) 
                                                        
yield(<li>{calcLink(o)}</li>)}
                                                </ul>
  
}

Second one --> Field to map one field on another object to obtain list of 
values as mapped fields

class 
MultiReferencedValueField[T<:KeyedMapper[Long,T],O<:KeyedMapper[Long,O],F <: 
Any] 
                                                                                
                (theOwner: T,
                                                                 foreign: => 
KeyedMetaMapper[Long, O],
                                                                 foreignField: 
=> MappedLongForeignKey[O,T],
                                                                                
                                                 referenceField: => 
MappedField[F, O])
extends MappedField[List[F], T] with LifecycleCallbacks {
  
  type KeyType = Long
  type KeyedForeignType = O
  type OwnerType = T
  
  def defined_? = !getAll.isEmpty
  def fieldOwner = theOwner
  def doneWithSave = {}

  /* I wont to not save it in a column on the databast but because of 
metamapper I need to
   * otherwise I cannot provide visualization
   */
  override def ignoreField_? = false
  override def dbDisplay_? = true
  override def writePermission_? = true
  /*override def dbPrimaryKey_? = false
  override def dbForeignKey_? = false
  override def dbIndexed_? = false
*/
  
  def can: Box[List[F]] = if (defined_?) Full(is) else Empty

  override def toString = if (defined_?) is.toString else "NULL"

  override def is = getValues
  
  override def validate : List[FieldError] = {
    val cv = getAll
    validations.flatMap{
      case pf: PartialFunction[List[O], List[FieldError]] =>
        if (pf.isDefinedAt(cv)) pf(cv)
        else Nil
      case f => f(getValues)
    }
  }
  
  def apply(v: Box[O]): T = 
          (v) match {
                case Full(o) => this(o)
                case _ => theOwner
          }
  def apply(v: O): T = 
    this + v
  
  def empty_!(): Unit = getAll.foreach{ o => this - o}
  
  def set_!(l: List[O]) = {
    this.empty_!
    l.foreach{o => this + o}
  }
  
  def + (f: F): Box[T] = {
    val rec = foreign.create
    (rec.fieldByName(referenceField.name)) match {
            case Full(f) => {
                f.setFromAny(f)
                Full(this + rec)
        }
        case _ => {Empty}}
  }
  
  def + (l: Long): T = this + foreign.find(By(foreignField,l))
  def + (v: Box[O]): T = (v) match {
    case Full(ext: O) => this + ext
    case _ => theOwner
  }
  def + (v: O): T = {
    (v.fieldByName(foreignField.name)) match {
      case Full(f) => {
                if 
(theOwner.primaryKeyField==theOwner.primaryKeyField.defaultValue) 
                        {
                          theOwner.save
                          this + (v)
                        }
                f.setFromAny(theOwner.primaryKeyField.is)
                v.save
      }
      case _ => {}
    }
    theOwner
  }
  
  def - (f: F): Box[T] = {
    val rec = foreign.find(By(referenceField,f))
    (rec) match {
            case Full(v) => Full(this - v)
        case _ => Empty
    }
  }
  
  def - (l: Long): T = this + foreign.find(By(foreignField,l))
  def - (v: Box[O]): T = (v) match {
    case Full(ext: O) => this - ext
    case _ => theOwner
  }
  def - (v: O): T = {
    (v.fieldByName(foreignField.name)) match {
      case Full(f) => 
        if (f == theOwner.primaryKeyField) {
          beforeRemoveElem(v)
          if (theOwner.primaryKeyField==theOwner.primaryKeyField.defaultValue) 
                        {
                          theOwner.save
                          this - (v)
                        }
          f.setFromAny(null)
          v.save
          afterRemoveElem(v)
        }
      case _ => {}
    }
    //this.is
    theOwner
  }
  
  /* To override for deleting the relationship KeyedMapper*/
  def afterRemoveElem(v: O) = v.delete_!
  def beforeRemoveElem(v: O) = {}
  
  override def beforeDelete = this.empty_!
  
  def getAll: List[O] = 
foreign.findAll(By(foreignField,theOwner.primaryKeyField.is))
  
  def getValues: List[F] = getAll.flatMap(r => 
    (r.fieldByName[F](referenceField.name)) match {
      case Full(x : F) => {
        List(x)
      }
      case _ => Nil
    }
  )
  
  def defaultValue: List[F] = Nil
  def dbFieldClass = classOf[List[F]]

  def targetSQLType = Types.BOOLEAN

  def asJsExp = JE.Num(theOwner.primaryKeyField.is)

  def real_convertToJDBCFriendly(value: List[F]): Object = new 
_root_.java.lang.Integer(if (!(value.isEmpty)) 1 else 0)

  // def asJsExp = JE.Num(is)

  def jdbcFriendly(field : String) = new _root_.java.lang.Integer(if (!
(this.getAll.isEmpty)) 1 else 0)
  
  protected def i_obscure_!(in : List[F]) = defaultValue

  protected def i_is_! = getValues
  protected def i_was_! = Nil
  
  override def setFromAny(in: Any) = {
    in match {
      case n: Long => this + n
      case n: Number => this + n.longValue
      case Some(n: Number) => this + n.longValue
      case null => this.empty_!
      case s: String => this + Helpers.toLong(s)
      case o => this + Helpers.toLong(o)
    }
    getValues
  }
  
  /**
   * Set the field to the value
   */
    
  protected def real_i_set_!(value : List[F]): List[F] = getValues
  
  def buildSetActualValue(accessor: Method, data: AnyRef, columnName: 
String) : (T, AnyRef) => Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferencedValueField[ T, 
O,F] =>
  try {
        (foreign.find(By(foreignField,v.asInstanceOf[Long]))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }}
  catch {case _ => null}})

  def buildSetLongValue(accessor: Method, columnName : String) : (T, Long, 
Boolean) => Unit =
  (inst, v, isNull) => doField(inst, accessor, {case f: 
MultiReferencedValueField[ T, O,F] => 
  (foreign.find(By(foreignField,v))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }})

  def buildSetStringValue(accessor: Method, columnName: String): (T, String) 
=> Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferencedValueField[ T, 
O,F] => 
  (foreign.find(By(foreignField,v.toLong))) match {
    case Full(ext: O) => f + ext
    case _ => null
  }})

  def buildSetDateValue(accessor : Method, columnName : String) : (T, Date) => 
Unit =
  (inst, v) => doField(inst, accessor, {case f: MultiReferencedValueField[ T, 
O,F] => null})

  def buildSetBooleanValue(accessor : Method, columnName : String) : (T, 
Boolean, Boolean) => Unit = null

  /**
   * Given the driver type, return the string required to create the column in 
the database
   */
  def fieldCreatorString(dbType: DriverType, colName: String): String = 
colName + " " + dbType.longColumnType
  
  
  /* HTML visualization */

  override def _toForm: Box[NodeSeq] = Full(doFormHtml)
  def doFormListHtml = 
    <ul>
         <table>
     {for ( o <- this.getAll) 
        yield(<tr>
                        <td><li>{calcLink(o)}</li></td>
                        <td>{removeButton(o)}</td>
                  </tr>
        )}
     </table>
        </ul>
  def doFormHtml: NodeSeq = 
    <div id={"_values-"+this.name} class={divFormClass}>
        {doFormListHtml}
    {addButton}
    </div>
    
  def divFormClass = "multiReferenceField"
    
  def removeButtonName = "-"
                                                                          
  def removeButton(foreignElem: O): NodeSeq =
          SHtml.ajaxButton(removeButtonName, () => doRemoveElement(foreignElem))
  
  def doRemoveElement(foreignElem: O): JsCmd = {
    this - foreignElem
    applyChanges
  } 
  
  def addButtonName = "+"

  var actualSelection = ""
  
  def referenceFieldForm = SHtml.ajaxText("", s => setActualSelection(s)) % 
("id" -> ("_input-"+referenceField.name))
  
  def customReferencedValidation: Function1[String,Boolean] =
    (value) => true
  
  def addButton: NodeSeq = {
          val rec = foreign.create
   
          <div>
          {referenceFieldForm}
          {SHtml.ajaxButton(addButtonName, () => doAddElement(rec))}
      </div>
  }
  
  def doAddElement(o: O) = {
    if (!customReferencedValidation.apply(actualSelection)) {
      JsCmds.Alert(S.?("cannot.set.this.value"))
    } else {
    (o.fieldByName(referenceField.name)) match {
            case Full(f) => f.setFromAny(actualSelection)
        case _ => {}}
    (o.validate) match {
      case Nil => {
        this + o 
        applyChanges
      }
      case x => {
        JsCmds.Alert(S.?("cannot.set.this.value"))
      }
    }}
  }
  
  def setActualSelection(s: String) = {
    actualSelection = s
    JsCmds.Noop
  }
      
  def doAddElement: JsCmd = {
    this + 
foreign.getSingleton.find(By(foreign.primaryKeyField,tryo(actualSelection.toLong)
 
openOr 0L))
    applyChanges
  }

  def applyChanges = JsCmds.SetHtml(("_values-"+this.name),doFormHtml)
  
  def makeLinkOnView = false
  
  /* to override if you wont right links*/
  def foreignViewPathString: String = "" 
  
  def calcForeignName(foreignElem: O): String = 
foreignElem.primaryKeyField.toString
  def calcForeignNameHtml(foreignElem: O) = 
    (foreignElem.fieldByName(referenceField.name)) match {
      case Full(f) => {f.asHtml}
      case _ => {referenceField.displayHtml}
    }                                                                          
                                                                          
  def calcLink(foreignElem: O): NodeSeq = calcForeignNameHtml(foreignElem)      
                                                                                
                                                                   
  
  override def asHtml = <ul>
                                                {for ( o <- this.getAll) 
                                                        
yield(<li>{calcLink(o)}</li>)}
                                                </ul>
  
}

Thanx in advance for the help!

Andrea

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Lift" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/liftweb?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to