sourcetip

연락처 양식 7 수신자의 동적 수

fileupload 2023. 10. 25. 23:41
반응형

연락처 양식 7 수신자의 동적 수

저는 메인과 "기타 수신자"라는 두 개의 필드 집합을 핵심으로 하는 양식을 작성하고 있습니다. "기타 수신자" 필드 집합의 끝에는 "다른 수신자 추가" 링크가 있습니다.

여기 필요한 사람이 있습니다.

주 수신자: 모든 것

기타 수신인: "기타 수신인" 필드 집합;

후속 수신인:각 필드 집합

지금까지 Documentation을 살펴보았지만 거기서 운이 별로 없었고, 기대했던 것도 아닙니다.


편집

저는 이것이 명확하지 않다고 생각하기 때문에 문맥이 무엇인지 조금 더 명확하게 말씀드리겠습니다. 저의form는 여러 사람을 등록할 수 있는 등록입니다. 필드 중 하나는 "당신의 이메일"로 표시됩니다.한 번에 한 명 이상 등록이 가능하기 때문에 중복해서 등록해야 합니다.fieldset"당신의 이메일"을 포함하고 있습니다.


편집2

명확한 설명을 돕기 위해, 우리가 여름 캠프에 아이들을 등록한다고 상상해 보세요.첫번째fieldset부모님의 청구 정보라고 하면 일반적이고, 두 번째는fieldset아이의 정보입니다.부모는 단일 항목을 작성할 수 있어야 합니다.form부모가 원하는 만큼 동적으로 자녀를 추가할 수 있습니다.

각각의 아이들의 집에서fieldset, 이메일이 필요하고 이 아이와 관련된 정보를 받습니다. 이메일은 다음과 유사합니다.

Hello {children's name},

You've been registered to StackOverflow Summer Camp. Here's the information you need to know:

[...]

Thanks for being a good sport!

도움이 되길 바랍니다.

이와 같은 특정 사용 사례가 있는 경우 주변 관련 플러그인에 기능을 추가하면 종종 불만이 발생합니다.그렇기는 하지만, 특정 플러그인이나 접근 방식과 결혼을 할 때가 있고, 그 위에 기반을 두기만 하면 되는 경우가 있습니다.

그 주의사항을 무시하고 연락처 양식 7에 대한 새로운 필드 유형을 만드는 각도에서 접근해야 한다고 생각합니다.이렇게 하면 필드의 HTML, 데이터 유효성 검사 등을 렌더링할 수 있습니다.또한 나중에 다른 답변에 대한 의견에서 언급했듯이 DB 저장 및 알림 전송을 위한 시작 지점을 제공할 수도 있습니다.

이러한 접근 방식을 실행에 옮깁니다.

Testing CF7 Duplication

새 필드 유형이 호출됩니다.emailplus, 그리고 당신은 그것을 다음과 같은 형태로 포함시킵니다.

<div class="cf7-duplicable-recipients">
    <label>Main Recipient (required)</label>
    [emailplus emails]
    [submit "Sign Up"]
</div>

또한 양식 설정의 "메일" 패널 아래 수신인을 다음과 같이 설정했습니다.[emails].

만약에emailsplus필드가 수신자로 설정되고 클래스는 기본 wpcf7 동작을 재정의하고 메일을 의 각 값으로 보냅니다.emailarray, 메시지 본문의 [emails] 자리 표시자를 이메일 단위로 대체합니다.

emailplusfieldtype은 클래스에서 캡슐화되며 자유롭게 주석을 달게 됩니다.

<?php

class WPCF7_Duplicable_Email
{
    /**
     * The emails this form's field is addressed to
     *
     * @var array
     */
    public $emails = array();

    /**
     * The name of the tag bearing the emailplus type
     *
     * @var string
     */
    public $tag_name;

    /**
     * Instantiate the class & glom onto the wpcf7 hooks
     *
     * @return void
     */
    public function __construct()
    {
        add_action('wpcf7_init', array($this, 'add_emailplus_tag'));
        add_action('wpcf7_form_tag', array($this, 'assign_values_to_field'));
        add_filter('wpcf7_validate_emailplus', array($this, 'validate'), 2);
        add_action('wpcf7_before_send_mail', array($this, 'send_email'));
        add_action('wp_enqueue_scripts', array($this, 'emailplus_scripts'));
    }

    /**
     * Add our the [emailplus __YOUR_FIELD_NAME__] shortcode for use in wpcf7 forms.
     *
     * @uses wpcf7_add_shortcode
     *
     * @return void
     */
    public function add_emailplus_tag()
    {
        wpcf7_add_shortcode(
            array('emailplus'),
            array($this, 'shortcode_handler'),
            true
        );
    }

    /**
     * Renders the HTML for the [emailplus] shortcode
     *
     * Referenced from wpcf7_text_shortcode_handler in wp-content/plugins/contact-form-7/modules/text.php
     *
     * @param array $tag The data relating to the emailplus form field.
     *
     * @uses wpcf7_get_validation_error
     * @uses wpcf7_form_controls_class
     *
     * @return string
     */
    public function shortcode_handler(array $tag) {
        $tag = new WPCF7_Shortcode($tag);

        if (true === empty($tag->name)) {
            return '';
        }

        $validation_error = wpcf7_get_validation_error($tag->name);
        $class            = wpcf7_form_controls_class($tag->type);

        if ($validation_error) {
            $class .= ' wpcf7-not-valid';
        }

        $atts = array(
            'class'        => $tag->get_class_option($class),
            'id'           => $tag->get_id_option(),
            'tabindex'     => $tag->get_option('tabindex', 'int', true),
            'aria-invalid' => $validation_error ? 'true' : 'false',
            'type'         => 'email',
            'name'         => $tag->name.'[]', // <-- Important! the trailing [] Tells PHP this is an array of values
            'value'        => $tag->get_default_option()
        );

        $atts = wpcf7_format_atts($atts);

        $html = sprintf(
            '<div class="emailplus-wrapper %1$s"><input %2$s />%3$s</div>',
            sanitize_html_class($tag->name),
            $atts,
            $validation_error
        );

        // We identify the container that will hold cloned fields with the [data-wpcf7-duplicable-email] attr
        return '<div class="wpcf7-form-control-wrap %1$s" data-wpcf7-duplicable-email>'.$html.'</div>';
    }

    /**
     * Validates the value of the emailplus tag.
     *
     * Must be handled separately from other text-based form inputs,
     * since the submitted POST value is an array.
     *
     * We can safely assume emailplus while creating the WPCF7_Shortcode,
     * because we know we hooked this function onto 'wpcf7_validate_emailplus'
     *
     * @uses wpcf7_is_email
     * @uses WPCF7_Validation::invalidate
     *
     * @param WPCF7_Validation $result The validation helper class from wpcf7.
     * @param array            $tag    The array of values making up our emailplus tag
     *
     */
    public function validate(WPCF7_Validation $result, $tag)
    {
        $tag = new WPCF7_Shortcode(
            array(
                'basename' => 'emailplus',
                'name' => $this->tag_name,
                'raw_values' => $this->emails
            )
        );

        // Check each value of the form field.
        // Emails must be validated individually.
        foreach($tag->raw_values as $email) {
            if (false === wpcf7_is_email($email)) {
                $result->invalidate($tag, wpcf7_get_message('invalid_email'));
            }
        }

        return $result;
    }

    /**
     * For completeness' sake, manually assign the value to the emailplus fieldtype.
     *
     * Wpcf7 doesn't know how to treat our fieldtype's value by default.
     *
     * As a side effect, this sets the email addresses that are up for delivery.
     *
     * @param array $scanned_tag The tag that wpcf7 is scanning through, and processing.
     *
     * @return $array;
     */
    public function assign_values_to_field($scanned_tag)
    {
        if ($scanned_tag['type'] !== 'emailplus') {
            return $scanned_tag;
        }

        $this->tag_name = $scanned_tag['name'];

        if (key_exists($scanned_tag['name'], $_POST)) {
            // Stores the emails on a class property for use later.
            $this->emails = $_POST[$scanned_tag['name']];
            $scanned_tag['raw_values'] = $this->emails;
            $scanned_tag['values']     = $this->emails;
        }

        return $scanned_tag;
    }

    /**
     * Performs a substitution on the emailplus field's fieldname, on a per-value basis.
     *
     * Ex. in two parts
     *  1 - The shortcode [emailsplus emails] renders into <input type="email" name="emails[]" value="" >
     *      Which the user clones and submits, processing into something like
     *      ['test1@gmail.com', 'test2@gmail.com'].
     *  2 - The user has set [emails] as the recipient in the "mail" panel for the form.
     *
     * Because wpcf7 isn't aware of how to process a field w/ multiple values when emailing,
     * we loop over the values of [emails], replace the tag, and invoke WPCF7_Mail::send()
     * for each value.
     *
     * @param WPCF7_ContactForm $form The contact form object.
     *
     * @uses WPCF7_Mail::send
     *
     * @return void
     */
    public function send_email(WPCF7_ContactForm $form)
    {
        $placeholder = '['.$this->tag_name.']';

        if (false === strpos($form->prop('mail'), $placeholder)) {
            return;
        }

        foreach ($this->emails as $email) {
            $template = $form->prop('mail');
            $template['recipient'] = str_replace($placeholder, $email, $template['recipient']);
            $template['body']      = str_replace($placeholder, $email, $template['body']);
            WPCF7_Mail::send($template);
        }

        // Tell cf7 to skip over the default sending behaviour in WPCF7_Submission->mail()
        $form->skip_mail = true;
    }

    /**
     * Adds our js that will clone the emailplus field.
     *
     * Could be optimized with a conditional that checks if there is a form with the [emailplus]
     * fieldtype somewhere on the page
     *
     * @return void
     */
    public function emailplus_scripts()
    {
        wp_enqueue_script(
            'cf7-duplication',
            get_template_directory_uri() . '/js/cf7-duplication.js',
            array('jquery'),
            '20161006',
            true
        );
    }
}

$wpcf7DuplicableEmail = new WPCF7_Duplicable_Email();

그리고 복제를 처리하는 .js 파일.안에서 살아야 합니다./path/to/your/theme/js/cf7-duplication.js'.

(function($) {
  $(document).ready(function() {
    var addEmailField = function(inputRow, container) {
      inputRow.find('input[type=email]').val('');

      var removeButton = $('<a href="#">&times;</a>')
        .click(function(e) {
          e.preventDefault();
          inputRow.remove();
        });

      inputRow.append(removeButton);
      inputRow.insertAfter(container.find('.emailplus-wrapper').last());
    }

    $.each($('[data-wpcf7-duplicable-email]'), function(i, el) {
      var container = $(el);
      var inputRow  = container.find('.emailplus-wrapper');
      var addButton = $('<a href="#">Add another email</a>');

      addButton.click(function(e) {
        e.preventDefault();
        var newEmailField = inputRow.clone();
        addEmailField(newEmailField, container);
      });

      container.append(addButton);
    });
  });
})(jQuery);

마지막으로, 유효하고 이메일이 나갔을 때 양식이 사라지도록 하려면 "추가 설정" 패널에 추가합니다.

on_sent_ok: "jQuery('.cf7-duplicable-recipients').fadeOut();"

이 접근 방식은 CF7의 AJAX 제출에 가장 적합합니다.바닐라 POST 요청을 처리하도록 확장하려면 쇼트코드 핸들러를 여러 개 렌더링하도록 업데이트할 수 있습니다.<input>당신이 보존해야 할 필드들.value잘못된 제출을 시도합니다.

옵션 1) 설정 메뉴의 메일 탭에서 메일(2)을 누른 후 수신인: 필드에서 이 줄을 추가합니다.부모가 명시된 자녀의 수보다 적을 경우 추가 이메일 주소는 아무런 도움이 되지 않습니다.[이메일], [이메일]이 기본 형식입니다.

[parents-email], [kid-email1], [kid-email2], [kid-email3], [kid-email4], [kid-email5], [kid-email6], [kid-email7]

옵션 2) [대상] 필드에 부모와 같은 전자 메일 주소 1개만 입력하고 [추가 머리글: 코드를 아래에 입력합니다.

CC: [kid-email1], [kid-email2], [kid-email3], [kid-email4], [kid-email5], [kid-email6], [kid-email7]

아니면

BCC: [kid-email1], [kid-email2], [kid-email3], [kid-email4], [kid-email5], [kid-email6], [kid-email7]

발생 가능한 문제:많은 호스트들이 스팸을 막기 위해 이와 같은 것들을 차단합니다.만약 이것들이 작동하지 않는다면, 아마 이런 경우일 것입니다.블록을 제거하려면 호스팅 공급자에게 문의해야 합니다.

연락처 양식 7에는 수신자 필드가 하나만 있지만, 해당 필드에 쉼표로 구분된 여러 개의 전자 메일 주소를 입력할 수 있습니다(예: "email1@domain.com,email2@domain.com,email3@domain.com ").

그러므로 당신의 경우, 자바스크립트를 사용하여 여러 개의 중복 수신자 필드를 동적으로 추가하고, 마지막으로 양식 제출 시 모든 수신자 이메일 주소를 조정하기 위한 자바스크립트 함수를 작성한 후, 그것을 주 수신자 필드에 보관하고 양식을 제출하면 됩니다.당신이 내 말을 이해하길 바랍니다.

언급URL : https://stackoverflow.com/questions/39754493/dynamic-number-of-contact-form-7-recipients

반응형