ラベル

2021-09-17

Salesforce - Attachment


添付ファイルに関するメモ書き
  • VFPage から任意のオブジェクトレコードに添付ファイルをアップロードしたい
  • VFPage に任意のオブジェクトレコードの添付ファイル一覧を表示したい(ファイル名のみ)





■ 添付ファイルのアップロード 

VFPage

<apex:form>

	<apex:outputLabel value="ファイル" for="file" />
	<apex:inputFile value="{!attachment.Body}" filename="{!attachment.Name}" id="file" />

	<apex:commandButton value="アップロード" action="{!doUpload}" />

</apex:form>

Apex

public class SampleController {

	private Id recordId;

	public Attachment attachment { get; set; }

	public SampleController(ApexPages.StandardController controller) {

		this.recordId = controller.getId();

		this.attachment= new Attachment();
	}

	public PageReference doUpload() {

		if(this.attachment.Body != null && String.isNotBlank(this.attachment.Name) ) {

			this.attachment.ParentId = this.recordId;

			insert this.attachment;
		}
		return null;
	}
}

■ 添付ファイル一覧の表示 

VFPage

<apex:dataList value="{!attachmentList}" var="attachment">
	<apex:outputText value="{!attachment.Name}"/>
</apex:dataList>

Apex

public class SampleController {

	private Id recordId;

	public List<Attachment> attachmentList { get; set; }

	public SampleController(ApexPages.StandardController controller) {

		this.recordId = controller.getId();

		this.attachmentList = [SELECT Id, Name FROM Attachment WHERE ParentId = :this.recordId ORDER BY CreatedDate ASC];
	}
}


ref: