cakephp form validation for counting multiple textareas as a group - forms

Is it possible to validate a group of form textareas at once? I would like to check that at least 5 out of 15 text areas are notEmpty. Any suggestions on a method for doing this?
If you're going to down vote, explain why.
I've read http://book.cakephp.org/view/150/Custom-Validation-Rules#Adding-your-own-Validation-Methods-152 but it isn't clear to me how I would group multiple field items together and only check for a minimum of 5 notEmpty cases.
Edit: I'm using version 2.3.7
I don't really have any code to show because I'm just trying to do a data validation on a form with many textareas. My form isn't working right now due to other issues. If this was the only problem I could post all the code, but right now it would just confuse matters. I'm looking for a descriptive answer of how to validate a group of fields together.

Attach the validation rule to one textarea
You can do this by attaching the validation rule to any one of the text areas e.g.
class Foo extends AppModel {
public $validate = array(
'textarea_1' => array(
'atLeast5' => array(
'rule' => array('validate5Textareas'),
'message' => 'Please put text in at least 5 of the little boxes'
)
)
);
public function validate5Textareas() {
$filledTextAreas = 0;
// adapt this to match the names/logic of the real form
for ($i = 1; $i <= 15; $i++) {
if (!empty($this->data[$this->alias]['textarea_' . $i])) {
$filledTextAreas++;
}
}
return $filledTextAreas >= 5;
}
}
The $validate array defines a rule such that validate5Textareas is called if textarea_1 is in the data passed to save.
The function validate5Textareas will return true if 5 or more have text in them and false otherwise.

Related

How do you access Gravity Form fields pre-submission?

I'm trying to access the Gravity Forms fields pre-submission to check for gibberish entries. I've tried pretty much everything on StackOverflow and no luck.
The form is id #1. Some of the 1000 things I've tried include:
GFFormsModel::get_form_meta(1);
GFFormsModel::get_leads(1);
$_POST['input_1']
and reading this:
https://docs.gravityforms.com/gform_pre_submission/
How do I do this?
If you want to fail silently for spam entries, I would recommend using the gform_validation filter and, if you determine that the submission is spam, dynamically enable the honey pot. Gravity Forms will then fail the submission silently. The confirmation will be displayed but the entry will not be created.
Here's how my GP Blacklist plugin handles this:
$honeypot_field_id = GFFormDisplay::get_max_field_id( $form ) + 1;
$_POST[ "input_{$honeypot_field_id}" ] = true;
$form['enableHoneypot'] = true;
$result['is_valid'] = true;
EDIT
To actually retrieve the value, the simplest way is to just fetch it from the $_POST (FYI, there are more thorough techniques). Here's a more robust example.
add_filter( 'gform_validation', function( $result ) {
// Get the value of field ID 1
$value = rgpost( 'input_1' );
if( $value == 'gibberish' ) {
// activate honeypot
}
return $result;
} );

MailChimp Campaign Content Update

MailChimp campaign content docs - https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/content
I'm trying to replace some placeholders in a campaign content with actual values via the API. At first, I thought there might be some syntax errors or internal logic errors like non-unique mc:edits into a mc:repeatable that would get the HTML refused/declined by MailChimp, hence the update not taking place, however, that was not the case.
Tried replacing html with a simple <p>test</p> and it was still not working.
Here are a couple of local logs, I'll use xyz as my campaign id:
2018-02-26 16:26:13 [::1][9804][-][warning][application] calling GET /campaigns/xyz/content []
2018-02-26 16:26:13 [::1][9804][-][warning][application] got both plain_text and html versions of content
2018-02-26 16:26:13 [::1][9804][-][warning][application] calling PUT /campaigns/xyz/content {"html":"<p>test</p>"}
2018-02-26 16:26:14 [::1][9804][-][warning][application] got response [
'plain_text' => 'test' + other MailChimp stuff such as footer, that were appended automatically by MailChimp,
'html' => '<p>test</p>'
]
// calling GET immediately after PUT in order to see if any update occurred
2018-02-26 16:26:14 [::1][9804][-][warning][application] calling GET /campaigns/xyz/content []
2018-02-26 16:26:14 [::1][9804][-][warning][application] got updated html (my "test" paragraph + auto footer from MailChimp) and proper plain_text
Everything looks fine according to these, that means both versions updated as they were supposed to. However, on the next API/MailChimp dashboard request, it displays the old HTML content, preserving the update I've just made in the plain text version only.
No errors, nothing to look into. It could be any internal MailChimp behaviour.
PS: I know about Setting Mailchimp campaign content html not working or MailChimp API v3 campaign content template sections, but none of the answers provided to those are helpful.
PS2: I know I should contact MailChimp, but according to
Our MailChimp Support Team isn't trained at in-depth API troubleshooting. If you need a developer to help you configure something using the API, check out our great Experts Directory, which lists third-party MailChimp experts who can be hired to help out.
they don't provide support for API troubleshooting.
MailChimp doesn't allow updating the campaign's HTML content because the campaign type is based on a template.
In order to update the HTML content, the campaign has to be set to custom HTML instead of a template. You can check the type by sending a GET API request to /campaigns or /campaigns/{campaign_id} and finding the content_type attribute in the response (documentation).
Alternatively, in the dashboard, the type can be determined by editing the design of the email. Anything under 'Code your own' is HTML and templates are of course templates.
I'm not entirely sure why the first response to a PUT request on a template campaign shows the updated content, but changing the content type should let you update as you want to.
Hope this helps!
If anyone's still looking for an answer to this.
I managed to solve the issue several weeks ago without creating the campaign via API, but actually updating it.
I used placeholders like [product_card id=123], 3 cards per block/row, all repeatable, which are wrapped in a class that I named product-card. In the MailChimp dashboard, you may still see the placeholders, but on preview and any form of preview like thumbnail, it will display correctly.
On the server, I crawl through the campaign's content, "detect" section names based on how they seemed to me in MailChimp and update each section with the content that I want.
PHP snippet below, some Yii2 stuff, but mostly plain PHP. I use $preview to display a preview of how the template would look, I know it's not visible in the function.
/**
* #param $id - Id of the campaign
* #param $s - Whether to save or just preview
*
* #return bool
*/
function changeContent($id, $s = false)
{
$mcCampaign = new McCampaign();
$mcCampaign::$itemId = $id;
$content = $this->api->get("/campaigns/{$id}/content");
if (!isset($content['html'])) return false;
$template = $content['html'];
$forgedDom = new \DOMDocument();
$forgedDom->loadHTML($template);
$mcSections = [];
$finder = new \DOMXPath($forgedDom);
$nodes = $finder->query('//td[contains(#class, "product-card")]');
// disabling this shit in order to avoid strict errors
libxml_use_internal_errors(true);
$mcEditId = 1;
$mcEditIndex = 0;
foreach ($nodes as $key => $node) {
/** #var \DOMElement $node */
$textContent = $node->textContent;
if (!preg_match("#\[product_card id=\d+\]#", $textContent)) continue;
$productId = filter_var($textContent, FILTER_SANITIZE_NUMBER_INT);
$node->textContent = false;
$product = Product::findOne($productId);
$productDetails = $product ? $this->renderPartial('/partials/_mc-product', [
'product' => $product
]) : 'Product not found.';
if ($key != 0) {
if ($key % 3 == 0) {
$mcEditId = 1;
$mcEditIndex++;
} else {
$mcEditId++;
}
}
$mcSections["repeat_1:{$mcEditIndex}:product_card_{$mcEditId}"] = $productDetails;
$fragment = $forgedDom->createDocumentFragment();
$fragment->appendXML($productDetails);
$node->appendChild($fragment);
}
libxml_use_internal_errors(false);
$preview = $forgedDom->saveHTML();
// just in case
/* $preview = str_replace(["\n", "\t", "\r"], "", $preview); */
if ($s) {
if (!empty($mcSections)) {
$res = $this->api->put("/campaigns/{$id}/content", [
'template' => [
'id' => *template_id_here*,
'sections' => $mcSections
],
]);
// forcing Mc to rebuild cache
$this->api->get("/campaigns/{$id}/content");
Yii::$app->session->setFlash('success', 'Done.');
return $this->redirect(['campaign/index']);
} else {
Yii::$app->session->setFlash('error', 'Something went wrong.');
}
}
}

SugarCRM 6.5 CE: how to remove button in detailview according to a condition

I'm trying to remove buttons in detail view of a Lead if it is alredy converted.
I saw a similar question and it use javascript to hide buttons. I'm trying to obtain same result via php.
This is my view.detail.php in custom\modules\Leads\views\ folder
class LeadsViewDetail extends ViewDetail {
function __construct(){
parent::__construct();
}
function preDisplay() {
parent::preDisplay();
if($this->bean->converted==1) {
echo "hide";
foreach ($this->dv->defs['templateMeta']['form']['buttons'] as $key => $value) {
unset($this->dv->defs['templateMeta']['form']['buttons'][$key]);
}
} else {
echo "show";
}
}
}
Using this code, after a Quick Repair & Rebuilt, I see "hide" or "show" correctly according to the Lead status but buttons are not updated correctly.
If I open a converted Lead after QR&R, I will never see the buttons.
If I open a unconverted Lead after QR&R, I will see the buttons all times.
I'm stuck with this situation. Can anyone explain me where is the problem? How I can solve it?
Every help is very appreciated.
You can probably handle this without extending the ViewDetail by using Smarty logic ("customCode") in custom/modules/Leads/metadata/detailviewdefs.php. It looks like the Convert button is already only rendered when the user has Edit privileges, so it's not a big deal to add one more condition to it...
$viewdefs['Leads']['DetailView']['templateMeta']['form]['buttons'][] = array('customCode' => '
{if $bean->aclAccess("edit") && $bean->converted}
<input title="{$MOD.LBL_CONVERTLEAD_TITLE}"
accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}"
type="button"
class="button"
name="convert"
value="{$MOD.LBL_CONVERTLEAD}"
onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" />
{/if}');
Alternatively, if you do have several conditions and they'd get too messy or difficult for Smarty logic to be reasonable, we can combine a small amount of Smarty Logic with the extended ViewDetail.
This except of custom/modules/Leads/metadata/detailviewdefs.php is actually the out-of-the-box file from SugarCRM CE 6.5.24, where it looks like they've actually tried to make this customization easier by supplying a Smarty var $DISABLE_CONVERT_ACTION. For reference, it simply needs the global config variable disable_convert_lead to be set and enabled, but I suspect that this was a relatively new feature not included in earlier versions. Still, it's a good example of using the View to set a simple Smarty variable that we can pivot on:
<?php
$viewdefs['Leads']['DetailView'] = array (
'templateMeta' => array (
'form' => array (
'buttons' => array (
'EDIT',
'DUPLICATE',
'DELETE',
array (
'customCode' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}<input title="{$MOD.LBL_CONVERTLEAD_TITLE}" accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}" type="button" class="button" onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" name="convert" value="{$MOD.LBL_CONVERTLEAD}">{/if}',
//Bug#51778: The custom code will be replaced with sugar_html. customCode will be deplicated.
'sugar_html' => array(
'type' => 'button',
'value' => '{$MOD.LBL_CONVERTLEAD}',
'htmlOptions' => array(
'title' => '{$MOD.LBL_CONVERTLEAD_TITLE}',
'accessKey' => '{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}',
'class' => 'button',
'onClick' => 'document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'',
'name' => 'convert',
'id' => 'convert_lead_button',
),
'template' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}[CONTENT]{/if}',
),
),
We can combine this $DISABLE_CONVERT_ACTION reference with a custom/modules/Leads/views/view.detail.php like the following to set it based on whatever condition we want:
<?php
require_once('modules/Leads/views/view.detail.php');
class CustomLeadsViewDetail extends LeadsViewDetail {
/*
* while we might normally like to call parent::display() in this method to
* best emulate what the parnts will do, we instead here copy-and-paste the
* parent methods' content because LeadsViewDetail::display() will set the
* DISABLE_CONVERT_ACTION Smarty var differently than we want.
*/
public function display(){
global $sugar_config;
// Example One: Disable Conversion when status is Converted
$disableConvert = ($this->bean->status == 'Converted');
// Example Two: Disable Conversion when there is at lead one related Call
// where the status is Held
$disableConvert = FALSE;
$this->bean->load_relationships('calls');
foreach($this->bean->calls->getBeans() as $call){
if($call->status == 'Held'){
$disableConvert = TRUE;
break; // exit foreach()
}
}
// Example Three: Disable Conversion if the User is in a specific Role, e.g.
// Interns who are great for data entry in Leads but shouldn't be making
// actual sales
global $current_user;
$disableConvert = $current_user->check_role_membership('No Lead Conversions');
// In any of the above examples, once we have $disableConvert set up
// as we want, let the Smarty template know.
$this->ss->assign("DISABLE_CONVERT_ACTION", $disableConvert);
// copied from ViewDetail::display();
if(empty($this->bean->id)) {
sugar_die($GLOBALS['app_strings']['ERROR_NO_RECORD']);
}
$this->dv->process();
echo $this->dv->display();
}
}

Trying to copy values into multiple embedded forms

I have a Symfony 1.4 application to allow users to enter data to a electrical appliance testing database. The page in questions consists of multiple embedded "new" forms so the user can submit many tests in one go. The form validates and saves correctly, but feedback is that it will be tedious to use.
As much of the data may be the same in each test (e.g. same date, same result, same person doing the testing), I would like the user to be able to fill in values in the top row, then click a button to fill the same information in the rows below. I'm pretty sure this would require javascript, but I don't have much experience.
I would appreciate any suggestions.
Many Thanks.
Well, I managed to figure it out without using javascript.
I put a button on the page
<input type="submit" name="copy_values" value="duplicate">
In the action for the page I included the code...
elseif (isset($_POST['copy_values'])) {
// get values from first embedded test
$newTests = $testList['new_tests'];
$testDate = $newTests[0]['et_date_tested'];
$testedBy = $newTests[0]['et_tester_id'];
$formOptions = array('test_date'=>$testDate, 'tester'=>$testedBy);
$this->form = new MultiTestForm(null, $formOptions);
}
$this->setTemplate('multiAdd');
... which takes the values from the widgets in the top row of the form and creates an array. This is passed as the options array to create a new form.
In the top level form class..
public function configure()
{
...
$subform = new sfForm();
for($i = 0;$i < sfConfig::get('app_new_test_rows'); $i ++)
{
$formToAdd = new TestsForMultiAddForm(null,$this->getOptions());
$subform->embedForm($i, $formToAdd);
}
$this->embedForm('new_tests', $subform);
}
...and in the embedded form class...
public function configure()
{
...
if ($this->getOption('test_date')) {
$this->setDefault('et_date_tested', $this->getOption('test_date'));
}
if ($this->getOption('tester')) {
$this->setDefault('et_tester_id', $this->getOption('tester'));
}
...
}
Not sure if this is the conventional way to approach the problem, but it works!

Conditional File Count Validator for a Zend_Form_File_Element

In my project we have a Form where the user either needs to upload a file or specify some other information, for example in a text input.
I know that there is the possibility to attach a Count validator to the Form Element, and this works like this:
$upload->addValidator('Count', false, array('min' => 1, 'max' => 3));
This validator gets called, no matter if there are files uploaded or not. But as soon as i replace the validator with a custom version, and do not upload any files, the validator does not get called.
Looking at the isValid() method of Zend_File_Transfer_Adapter_Abstract, I can see the problem:
[...]
foreach($check as $key => $content) {
if (array_key_exists('validators', $content) &&
in_array('Zend_Validate_File_Count', $content['validators'])) {
$validator = $this->_validators['Zend_Validate_File_Count'];
$count = $content;
[...]
Seems like the Count Validator got some special treatment here. But how can I include my customized Validator, without overwriting Zend Files?
Because we do not extend the Zend_Form class, sadly I also cannot overwrite the isValid() method of the involved Form. Any Ideas left? Thanks for your time!
This would probably be easiest with a bit of ajax. That way you could evaluate the selection prior to posting the form.
To do it in PHP, an Element validator is probably not the way to go. It would be better to handle the selection with an if() statment.
pseudocode...
//if file element contains something and text doesn't
if($this->getRequest->getPost('file'=='' && 'text' != ''){
$file = $form->file->receive();
//do some stuff
//if text element contains something and file dosen't
}elseif ($this->getRequst->getPost('file' != '' && 'text' == '') {
if($form->isValid($this->_request->getPost('text')) {
//do some stuff
}
}
This is the idea, hope it helps.