我正在尝试在我的Magento网站中创建一个单词过滤器,基本上我有一个带有文本区域和提交按钮的表单,如下所示:
<form id="answer_form_<?php echo $id;?>" class="form" method="post"
action="<?php echo Mage::getUrl('productquestions/productquestions/saveanswers',array('product_questions_id'=>$id));?>">
<textarea id="txt_send" class="input-text required-entry " name="content"
id="answer_content_<?php echo $id;?>" title="Content"></textarea>
<button id="btn_send" style="float: left;" type="submit" class="button"
title="Send Message"><span><span><?php echo $this->__('Send Message') ?></span></span></button>
</form>
我需要做的是在表单提交时过滤文本区域中的单词,然后再将其保存到数据库中,因此我创建了一些php函数并对其进行了调整。最终代码为:
function wordFilter($text) {
$filter_terms = array('bass(es|holes?)?b','bshit(e|ted|ting|ty|head)b');
$filtered_text = $text;
foreach($filter_terms as $word) {
$match_count = preg_match_all('/' . $word . '/i', $text, $matches);
for($i = 0; $i < $match_count; $i++) {
$bwstr = trim($matches[0][$i]);
$filtered_text = preg_replace('/b' . $bwstr . 'b/', str_repeat("*", strlen($bwstr)), $filtered_text);
}
}
return $filtered_text;
}
if(isset($_POST['btn_send'])) {
$text = htmlentities($_POST['txt_send']);
$text = wordFilter($text);
}
到目前为止,我只是添加了两个单词进行测试,当我使用这两个单词执行文本时,它会正常保存而不会将它们更改为"*****"。我避免使用JS,因为它是客户端。
有人可以告诉我我错过了什么吗?
谢谢!
编辑:
作为Magento插件。该操作将表单重定向到: productquestions/productquestions/saveanswers',array('product_questions_id'=>$id));
并根据 ID 更改 URL。例如:siteurl/index.php/productquestions/productquestions/saveanswers/product_questions_id/40
在此控制器页面中,我有以下功能:
public function saveanswersAction()
{
$answers = $this->getRequest()->getPost();
$answerCollection = array();
$model = Mage::getModel('productquestions/answers');
$id = $this->getRequest()->getParam('product_questions_id');
$model->setData('product_questions_id',$id);
$model->setData('answers',$answers['content']);
$model->save();
$answerCollection[] = $model;
}
难以确定,因为您不包含执行保存的代码,但看起来您没有将过滤器函数的结果保存回保存的变量中。尝试:
if(isset($_POST['btn_send'])) {
$text = htmlentities($_POST['txt_send']);
$text = wordFilter($text);
//Code to save $text here
}
刚刚将代码移动到控制器即可工作,感谢您的提示。
$text = $this->getRequest()->getParam('content');
$filter_terms = array('bass(es|holes?)?b','bshit(e|ted|ting|ty|head)b');
$filtered_text = $text;
foreach($filter_terms as $word)
{
$match_count = preg_match_all('/' . $word . '/i', $text, $matches);
for($i = 0; $i < $match_count; $i++)
{
$bwstr = trim($matches[0][$i]);
$filtered_text = preg_replace('/b' . $bwstr . 'b/', str_repeat("*", strlen($bwstr)), $filtered_text);
}
}
$model->setData('answers',$filtered_text);