- Drupal Русскоязычное сообщество
- Лучший ответ
- Комментарии
- Conditional Fields for Contact Form 7
- Создание обычной формы
- Создание условной логики
- Создание групп полей
- Создание условий
- Настройка шаблона письма
- WordPress.org
- Conditional Fields for Contact Form 7
- Description
- How to use it
- Main features
- Support for required fields
- Hide/show info in emails based on what groups are visible
- Groups can be nested
- Advanced
- Need more power?
- Screenshots
- Installation
- Email message is not showing the correct values / Wrong values are submitted
- All my groups show up all the time and never get hidden.
- Can I have conditional fields using Contact Form 7 plugin in WordPress?
- 5 Answers 5
Drupal Русскоязычное сообщество
Всем доброго дня. Стоит задача — при создании ноды делать видимыми дополнительные поля, в зависимости от выбранного термина из большого словаря с максимальной глубиной 4. Для этой задачи есть замечательные модули Conditional Fields или Conditional Fields States.
Имеем drupal 7.56 и следующую проблему: модули(которые я перепробовал) Hierarchical Select, Simple hierarchical select, Multilevel Select Taxonomy Widget вместе с Conditional Fields или Conditional Fields States отказываются работать. Картина такая — поле с выбором термина (виджет Hierarchical Select, например) — отрабатывает хорошо, термин выбирается из любой глубины, а условие в Conditional Fields или Conditional Fields States не отрабатывает
Я пробовал разные модули (из тех что перечислил), пробовал модули в песочнице, патчи — ничего не помогло. Поэтому прошу помощи у Вас, дорогие мои. Может кто сталкивался и победил. Если ткнёте носом в рабочий вариант — в долгу не останусь, а то проект встал капитально.
Лучший ответ
Справился своими силами. Обошёлся #states и написанием модуля для вывода иерархии. Вопрос закрыт.
Комментарии
Вообще вся эта структура (HS+Conditional Fields) сильно ограничена и «топорна».
Для подобных целей использую — DDF + #states, что позволяет использовать разные словари, отдельные поля, дефолтный «список выбора», views и любую связь.
Скорей всего дело в событиях js по ним надо дружить HS и CF доки по ним смотрели , события и тригеры для них в js проверяли?
В SHS есть такой прикол, что по приходу его аякса не срабатывают бихэйворы. Там это надо вручную ловить. По поводу того, как с этим в HS — не знаю.
if ( $form_id == ‘posts_node_form’ ) <
$form [ ‘title’ ] [ ‘#states’ ] = array (
‘visible’ = > array (
‘:input[name=»field_tx_razdel[und]»]’ = > array ( ‘value’ = > ‘3163’ ) ,
) ,
) ;
>
>
В форм альтер лучше добавить свой js, а в нём такой код:
- Войдите или зарегистрируйтесь, чтобы отправлять комментарии
js подключил с вашим кодом. но добиться результата так и не получилось, не могу в разделе «// Тут ваша логика» поставить условие с обращением к термину из списка формы shs т.к. в js не силён
- Войдите или зарегистрируйтесь, чтобы отправлять комментарии
Справился своими силами. Обошёлся #states и написанием модуля для вывода иерархии. Вопрос закрыт.
Источник
Conditional Fields for Contact Form 7
Позволяет добавлять условную логику в формы плагина Contact Form 7.
Создание обычной формы
Мы уже изучали, как создать форму в Contact Form 7, поэтому сразу перейдем к примерам. Пусть у нас есть форма «Запись на онлайн курсы»:
Создание условной логики
Рассмотрим варианты, где нужно отображать одни поля при одном условии и другие при другом, т.е. варианты условного отображения полей.
Допустим мы хотим дать возможность пользователю отображать ту или иную группу полей. Создадим в начале формы поле с выпадающим списком:
Создание групп полей
После установки плагина Conditional Fields for Contact Form 7 на странице редактирования формы появится новая кнопка Conditional fields Group:
По нажатию на кнопку появится всплывающее окно, в котором надо задать имя (оно генерируется автоматически, можно оставить как есть):
Генератор создал новый шорткод [group group-basic][/group] , после нажатия «Вставить тег» он попадёт в форму как есть. Этот шорткод создает условие, нечто очень похоже на конструкцию:
Шорткод должен приобрести вид:
Так как имя мы задали group-basic , соответственно этим контентом будут являться блок с основными полями. Обернем их в наш условный тег:
Если сейчас посмотреть как выглядит форма, то блок с основными полями будет скрыт, потому что мы ещё не задали условия при котором он должен отображаться.
Создание условий
После добавления полей и «условных шорткодов» очень важно сначала сохранить форму. В противном случае созданные поля и группы не будут отображаться на вкладке «Условные поля / Conditional Fields».
Добавим первое условие:
- За значением какого поля надо следить? Указываем имя поля, в нашем случае pick-fields .
- Само условие — «равно» или «не равно» значению, что будет указано в 3 пункте.
- Указываемое тут значение будет сверяться с выбранным значением у поля из 1 пункта.
- Какой блок отобразить при выполнении условия. В нашем случае это group-basic .
Условие будет читаться так:
Когда в поле pick-fields будет выбран вариант ответа «Основные поля» — отобразить контент внутри тега group-basic .
в старой версии можно было еще выбрать, что сделать, если условие выполнится — показать блок или скрыть? Теперь блок можно только показать (then show).
Но у нас несколько значений у поля pick-fields , поэтому нужно прописать больше условий, чтобы предусмотреть все варианты взаимодействия с формой.
Настройка шаблона письма
Начиная с версии плагина 0.2 можно генерировать сообщение электронной почты на основе того, какие группы были видны. Для этого вы можете просто обернуть части контента в шаблоне письма тегами [group-name] . [/ group-name] .
Составим шаблон письма для нашего примера:
Теперь, если пользователь заполнит только блок с основными полями, то на почту придёт письмо:
Если пользователь заполнил только блок с дополнительными полями и выбрал любой вариант CMS, кроме «Другую»:
Если пользователь заполнил только блок с дополнительными полями и выбрал вариант CMS «Другую»:
А если всё вместе:
Мы рассмотрели пример с выпадающими списками, так как такой вариант самый распространённый, но с помощью плагина Conditional Fields for Contact Form 7 можно создать условия на основе любого другого типа поля. В нашей специальной статье вы можете узнать, какие типы полей поддерживает Contact Form 7.
Спасибо за отличный контент!
Без плагина, сделать показ поля по условию можно следующим скриптом (пример для выпадающего списка):
Добрый вечер! А подскажите есть вариант , типа: если поле 1=А а поле 2=В, тогда поле 3=С?
Добрый. Этот плагин лишь управляет показом/скрытием полей и не может устанавливать полям какие-либо значения, поэтому условия 3=С сделать не сможет, лишь показать или скрыть его при условиях 1=А + 2=В.
а как проверить ID формы? Если показывать один заголовок всплывающего окна после отправки формы, если другой ID, то другой заголовок??
Здравствуйте, никак не могу разобраться. Помогите, пожалуйста
Вот код:
Ваше имя (обязательно)
[text* your-name]
Ваш e-mail (обязательно)
[email* your-email]
Ваш телефон (обязательно)
[tel tel-917]
Форма столешницы (обязательно)
[select menu-485 «Прямая» «Г-образная» «П-образная»]
Укажите параметр А столешницы>
[textarea textarea-338]
[/group] [group group-ab]
Укажите параметрs А и B столешницы
[textarea textarea-161] [/group] [group group-abc]
Укажите параметрs А,B и C столешницы
[textarea textarea-885] [/group]
Нужна ли нижняя подклейка мойки?
[select menu-194 «Да» «Нет»]
Нужен ли плинтус из HPL compact?
[select menu-657 «Да» «Нет»]
Форма переднего канта:
[select menu-461 «45 град.» «90 град.»]
Монтаж:
[select menu-445 «Да» «Нет»]
Сообщение. Укажите Ваши пожелания.
[textarea your-message]
Добавить изображение
[file file-190 filetypes:jpg|png|tif]
[submit «Отправить»]
Нужно, чтобы в зависимости от выбора формы столешницы («Прямая» «Г-образная» «П-образная»)показывались соответствующие поля.
Правила создал: show [group-basik] if [menu-485] equals «Прямая»
show [group-ab] if [menu-485] equals «Г-образная»
show [group-abc] if [menu-485] equals «П-образная»
Источник
WordPress.org
Conditional Fields for Contact Form 7
Description
This plugin adds conditional logic to Contact Form 7.
If you edit your CF7 form, you will see an additional tag called “Conditional fields Group”. Everything you put between the start and end tag will be hidden by default.
After you have added the field group(s), click Save and go to the “Conditional fields” tab to create one or more conditions that will make the group(s) appear.
How to use it
Main features
Support for required fields
Required fields inside hidden groups will never trigger validation errors.
Hide/show info in emails based on what groups are visible
Conditional groups can now be added to the emails as well.
Just wrap the content with [group-name] . [/group-name] tags.
Groups can be nested
Groups can be nested, both in the form and in the email
Advanced
Advanced users can code up the conditions as plain text instead of using the select boxes, using the Text View.
Need more power?
Just like WordPress, the power of Contact Form 7 lies in its rich eco-system of extensions that build on top of it. However, it can be difficult to find a set of complex extensions that work well together.
That’s why I created Conditional Fields Pro. It adds some powerful features to Contact form 7 and guarantees that everything will run smoothly with Conditional Fields.
Pro features include:
- Repeatable fields (repeaters)
- Forms with multiple steps (multistep)
- Custom conditions with JavaScript functions
- Additional operators ( greater than, less than, .. )
Screenshots
Conditional fields in action Defining rules to show/hide groups of input elements in the backend interface
Installation
Follow this tutorial if you are not sure how to use the plugin.
Email message is not showing the correct values / Wrong values are submitted
All field names should be unique
Even though your fields might never show up at the same time, it is still important to realize that WPCF7CF will not remove the fields, it merely hides them. So all fields will be submitted when the form is sent. Because of this no two fields can have the same name.
Incorrect form (2 input elements having the same name “a”):
Correct form (all groups and fields have unique names):
All my groups show up all the time and never get hidden.
Reason #1: Javascript error
Check your browser console (F12) for any javascript errors. WPCF7CF loads it’s scripts at the bottom of the HTML page, so if some javascript error gets triggered before that, the code will not be executed in most browsers.
Before reaching out to the support forum try to determine which plugin or theme is causing the problem, by gradually disabling plugins and changing theme.
Источник
Can I have conditional fields using Contact Form 7 plugin in WordPress?
What I want is simple.
User can select A or B and depending on this, they have different fields to fill.
I can’t find a way on doing this, I’ve only found a hack for the 1.0 version (current is 2.4.6)
5 Answers 5
This question should have been posted under Stack Overflow’s WordPress page initially. You probably would have gotten a quicker answer. 🙂
Here is the answer. 😀
I know this question was asked quite a while back but I have also found a solution to it as I was looking for this myself. So here is the answer for anyone else who might also be looking for a solution. The link listed below has helped me tons.
I’ve just written a WordPress plugin that adds conditional logic to Contact Form 7.
You can download the plugin from the wordpress repository here: https://wordpress.org/plugins/cf7-conditional-fields/
This changed with CF7 4.1 release around 1/2015. Details on the changes can be found here — http://contactform7.com/2015/01/06/contact-form-7-41-beta/
Code should look something like this —
The CF7 Conditional fields by @jules-colle is an obvious awesome solution.
However, if you want to conditionally show/hide one or two fields, adding some inline js works very well.
Here is an example copy of the CF7 form builder:
For further reading and more examples, check my article on this topic.
You can check this article of mine, if you want something more than simply hide/show elements: This is how to have simulated conditional fields in CF7 with jQuery.
For a real-life sample of what you can do, you can check this site selecting the tab «Richiedi quotazione». The site is in Italian, but easily gives you an idea.
Back to my article, the example given is based on the assumption you can have complex conditions in real-life cases (e.g.: you sell products that can be standard, but can also be tailored).
- Standard products will let users select a product code to which correspond pre-set shape, width and height, and then let the user input only the desired lenght. I also want a preview of shapes to be shown.
- Custom products will have users define shape, width, height and lenght.
Premise is that you work safely on your child-theme, so if you still don’t, do it now!
The code refers to an ipotetical child theme url /wp-content/themes/myTheme-child and to its subdirectories /catalogue and /js within the domain my-domain.it . You will have to change these values accordingly to your wordpress installation.
STEP 1: build your contact form. For the given example, I built one: it assumes you have a myCatalogue.pdf file into the /catalogue subdirectory of your child theme. Here it is.
STEP 2: style your contact form with an appropriate CSS set of directives. Mine contains some directives to manage classes I add via jQuery, too. Here it is.
STEP 3: write down some functions to manage the dirty job. Mine take care of checking the conditions, show/hide appropriate fields, pre-set values, substitute pre-set fields with grayed info boxes, show a preview of the product shape. You will have to save it as Cond1.js into the /js subdirectory of our child theme to make it work with the given example. You will also need to save some .jpg into the /catalogue subdirectory of your child theme for the product shape preview to work properly. And here’s the code.
Источник