Media::validate_field( mixed $value, awsmug\Torro_Forms\DB_Objects\Elements\Element $element, awsmug\Torro_Forms\DB_Objects\Submissions\Submission $submission )

Validates a field value for an element.

Description

See also

Parameters

$value

(mixed) (Required) The value to validate. It is already unslashed when it arrives here.

$element

(awsmug\Torro_Forms\DB_Objects\Elements\Element) (Required) Element to validate the field value for.

$submission

(awsmug\Torro_Forms\DB_Objects\Submissions\Submission) (Required) Submission the value belongs to.

Return

(mixed|WP_Error) Validated value, or error object on failure.

Source

File: src/db-objects/elements/element-types/base/media.php

	public function validate_field( $value, $element, $submission ) {
		$settings = $this->get_settings( $element );

		$value = absint( $value );

		$file_id = $this->get_file_id( $element );

		if ( ! empty( $settings['required'] ) && 'no' !== $settings['required'] && empty( $value ) && empty( $_FILES[ $file_id ] ) ) {
			return $this->create_error( 'value_required', __( 'You must upload a file.', 'torro-forms' ), $value );
		}

		if ( ! empty( $_FILES[ $file_id ] ) ) {
			$form = $submission->get_form();

			$mimes = null;
			if ( ! empty( $settings['file_type'] ) && 'any' !== $settings['file_type'] ) {
				$mimes = array();

				if ( 0 === strpos( $settings['file_type'], 'type_' ) ) {
					$settings['file_type'] = substr( $settings['file_type'], 5 );

					$media_types = $this->get_media_types();
					if ( isset( $media_types[ $settings['file_type'] ] ) ) {
						$file_mime_types = $this->get_file_mime_types();

						foreach ( $media_types[ $settings['file_type'] ] as $extension ) {
							if ( isset( $file_mime_types[ $extension ] ) ) {
								$mimes[ $extension ] = $file_mime_types[ $extension ];
							}
						}
					}
				} else {
					$file_mime_types = $this->get_file_mime_types();

					if ( isset( $file_mime_types[ $extension ] ) ) {
						$mimes[ $extension ] = $file_mime_types[ $extension ];
					}
				}
			}

			$attachment_id = torro()->form_uploads()->upload_file( $file_id, $submission, $form, $element->id, '_main', $mimes );

			if ( ! empty( $value ) ) {
				if ( is_wp_error( $attachment_id ) ) {
					$attachment_id->add_data( array( 'validated_value' => $value ) );
				} else {
					wp_delete_attachment( $value, true );
				}
			}

			return $attachment_id;
		}

		return $value;
	}

Changelog

Changelog
Version Description
1.0.0 Introduced.