[英]How to use annotations with z3c.form's DictionaryField
好吧,不幸的是,這個要求似乎沒有簡單的解決方案。 我曾經在z3c表單中使用datagrid字段遇到同樣的問題。
以下指令解決了datagrid字段的問題,該字段是一個list
( dicts
of dicts
(PersistentMappings))。
我想你可以根據你的情況調整這個解決方案。
首先,您需要將以下代碼添加到getContent
方法:
from plone.directives import form
class MyForm(form.SchemaEditForm):
schema = IMyFormSchema
ignoreContext = False
def getContent(self):
annotations = IAnnotations(self.context)
if ANNOTATION_KEY not in annotations:
annotations[ANNOTATION_KEY] = PersistentMapping()
return YourStorageConfig(annotations[ANNOTATION_KEY])
重要說明:我包裝注釋存儲以滿足z3c表單的get / set行為。 檢查以下YourStorageConfig
實現,您將看到原因:-)。
class YourStorageConfig(object):
implements(IMyFormSchema)
def __init__(self, storage):
self.storage = storage
def __getattr__(self, name):
if name == 'storage':
return object.__getattr__(self, name)
value = self.storage.get(name)
return value
def __setattr__(self, name, value):
if name == 'storage':
return object.__setattr__(self, name, value)
if name == 'yourfieldname':
self.storage[name] = PersistentList(map(PersistentMapping, value))
return
raise AttributeError(name)
yourfieldname
應該是您在表單架構中使用的字段名稱。
要實現數據網格字段,還有一些工作要做,但這對您的情況來說已經足夠了。
請發表評論或追溯,以便我可以提供進一步的幫助。 如有必要,我會添加更多細節/解釋;-)
事實證明,答案就像下面的ZCML適配器注冊一樣簡單:
<adapter
for="persistent.dict.PersistentDict zope.schema.interfaces.IField"
provides="z3c.form.interfaces.IDataManager"
factory="z3c.form.datamanager.DictionaryField"
/>
有了這個,表單的以下自定義就足以使用( PersistentDict
)注釋來加載和存儲表單數據:
def getContent(self):
"return the object the form will manipulate (load from & store to)"
annotations = IAnnotations(self.context)
return annotations[SOME_ANNOTATIONS_KEY_HERE]
這是假設一個PersistentDict
先前已存儲在annotations[SOME_ANNOTATIONS_KEY_HERE]
-否則,上面的代碼將導致KeyError
。 更改上面的getContent
可能是一個好主意,這樣如果注釋尚不存在,則會創建並使用一些默認值進行初始化。
最后,請注意,由於某種原因, z3c.form
警告不要為每種映射類型啟用DictionaryField
,因此例如對於表單存儲子類PersistentDict
可能是謹慎的,而不是直接使用它。 我向z3c.form提交了一個問題 ,要求澄清該警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.