Does anyone knows how or point me in the direction to show the last guestbook entry (using the simple guestbook module) in the sidebar or homepage?
trying to have a go, I've put in HomePage.php this function
function LastGuest($nume=1) {
$guest = DataObject::get_one("Guestbook");
return ($guest) ? DataObject::get("GuestbookEntry", "", "Date DESC", "", $nume) : false;
}
and in HomePage.ss this:
<% control LastGuest %>
<div class="newsList">
<h2 class="newsTitle">$Title.XML</h2>
<article class="newsSummary">$Comment</article>
</div>
<% end_control %>
But it doesn't work. I get a 500 error. Any idea?
Thanks in advance.
This works for me. First see if you have a page of class Guestbook, grab the ID of the page. Then use that ID in the arguments to GuestbookEntry::getEntryList.
function LastGuest() {
if ($guestbook = DataObject::get_one('GuestBook')) {
$id = $guestbook->ID;
$params = array(
'filter' => 'IsActive = 1 AND IsSpam = 0 AND GuestbookID = ' . $id,
'sort' => 'Created DESC',
'limit_start' => 0,
'limit_end' => 1,
'comments' => false,
'cryptmail' => false,
'emoticons' => false,
);
$entries = GuestbookEntry::getEntryList($params);
return $entries;
}
return;
}
Related
Can you help me. i want to like example but on my source code it becomes empty emty. What is the query or source code in my project? thank You.
in Controller
public function actionView($id)
{
$con = Yii::$app->db;
$sql = $con->createCommand("SELECT * FROM track where collecting_id=$id ORDER BY collecting_id desc");
$posts = $sql->query();
return $this->render('view', [
'model' => $this->findModel($id),
'posts' => $posts,
]);
}
in View
<div class="timeline__items">
<?php
foreach($posts as $row)
{
?>
<div class="timeline__item">
<div class="timeline__content">
<h2><?php echo $row['status']; ?></h2>
<p><?php echo $row['tanggal']; ?></p>
</div>
</div>
<?php
}
?>
</div>
if the $id on the query is replaced with 'PMUEI' the result is result
Use ActiveDataProvider
public function actionView($id)
{
$model = $this->findModel($id);
$hotel = Track::find()->where(['collecting_id' => $model->collecting_id]);
$posts = new ActiveDataProvider([
'query' => $hotel,
]);
// $con = Yii::$app->db;
// $sql = $con->createCommand(
// "SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
// [':collecting_id' => '$id']
// );
// $posts = $sql->queryAll();
return $this->render(
'view', [
'model' => $this->findModel($id),
'posts' => $posts,
]);
}
the result is error .
Its always good to bind parameters when comparing columns with any such input that is provided by the user or can be edited by the user as in your case is the $id that you are passing as a parameter to the actionView(). And then you need to use queryAll() or queryOne() in case you want multiple or single rows returned.
So you should change your query to the following
public function actionView($id)
{
$con = Yii::$app->db;
$sql = $con->createCommand(
"SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
[':collecting_id' => $id]
);
$posts = $sql->queryAll();
return $this->render(
'view', [
'model' => $this->findModel($id),
'posts' => $posts,
]
);
}
Apart from the above, you should use ActiveRecord. Active Record provides an object-oriented interface for accessing and manipulating data stored in databases. Read Here to make your life easier.
I am trying to adapt the Product Comments "add a review feature" (which is on the Product page) to work on the Products List page, but the link is only recognizing the first product in the list. There is a pencil icon link next to each product in the list, but they all link to the first product only.
Can anybody let me know why this is happening, and point me in the right direction to fixing it.
Following is the code in my custom hook:
include_once dirname(__FILE__).'/ProductComment.php';
include_once dirname(__FILE__).'/ProductCommentCriterion.php';
if(in_array($this->context->controller->php_self, array('product-list'))) $products = Product::getProducts((int) Tools::getValue('id_product'), $this->context->language->id);
{
$id_guest = (!$id_customer = (int) $this->context->cookie->id_customer) ? (int) $this->context->cookie->id_guest : false;
$customerComment = ProductComment::getByCustomer((int) (Tools::getValue('id_product')), (int) $this->context->cookie->id_customer, true, (int) $id_guest);
$average = ProductComment::getAverageGrade((int) Tools::getValue('id_product'));
$image = Product::getCover((int) Tools::getValue('id_product'));
$cover_image = $this->context->link->getImageLink($product->link_rewrite, $image['id_image'], 'medium_default');
$this->context->smarty->assign(array(
'id_product_comment_form' => (int) Tools::getValue('id_product'),
'product' => $products,
'secure_key' => $this->secure_key,
'logged' => $this->context->customer->isLogged(true),
'allow_guests' => (int) Configuration::get('PRODUCT_COMMENTS_ALLOW_GUESTS'),
'productcomment_cover' => (int) Tools::getValue('id_product').'-'.(int) $image['id_image'], // retro compat
'productcomment_cover_image' => $cover_image,
'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')),
'criterions' => ProductCommentCriterion::getByProduct((int) Tools::getValue('id_product'), $this->context->language->id),
'action_url' => '',
'averageTotal' => round($average['grade']),
'ratings' => ProductComment::getRatings((int) Tools::getValue('id_product')),
'too_early' => ($customerComment && (strtotime($customerComment['date_add']) + Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME')) > time()),
'nbComments' => (int) (ProductComment::getCommentNumber((int) Tools::getValue('id_product'))),
));
return $this->display(__FILE__, '/mytemplate.tpl');
}
This is the code in my template:
<SCRIPT>
$(document).ready(function() {
if (!!$.prototype.fancybox)
$('.open-comment-form').fancybox({
'autoSize' : false,
'width': 800,
'height': auto,
'hideOnContentClick': false,
'title' : null,
});
});
</SCRIPT>
{if (!$too_early AND ($is_logged OR ($PRODUCT_COMMENTS_ALLOW_GUESTS == 0)))}
<p class="align_center">
<a class="open-comment-form" href="#new_comment_form" title="{l s='Write your review' mod='productcomments'}!"></a>
</p>
{/if}
I am using Prestashop version 1.6.1.14. Thanks aussiecomet
In yii2 project I have my own file structure setup. Anything uploaded will get saved as a file type. I can get the file dimensions using the file uploaded in the temp folder by yii2. Using those dimensions I set my own width and height and compare them. If the height and width is more than what I have declared It has display an error message in the form. Which I am unable to do it.
My Active Form
<div class="company-form">
<?php
$form = ActiveForm::begin([
'action'=>['company/logo', 'id'=>$model->company_id],
'validateOnSubmit' => true,
'options' =>
['enctype' => 'multipart/form-data','class' => 'disable-submit-buttons','id'=> 'companyLogoForm'],
'fieldConfig' => [
'template' => "<div class=\"row\">
<div class=\"col-xs-6 margin-top-8\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
\n<div class=\"col-xs-12 \">{input}</div>
</div>",
],
]); ?>
<?= $form->errorSummary($model, $options = ['header'=>'','class'=>'pull-left']); ?>
<?= $form->field($model, 'company_name')->hiddenInput(['maxlength' => true])->label(false) ?>
<?= $form->field($file, 'file')->fileInput([])->label(Yii::t('app', 'Attach Logo'),['class'=> 'margin-top-8']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Save') : Yii::t('app', 'Save'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','data' => ['disabled-text' => 'Please Wait']]) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My Controller Action
public function actionLogo($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = new File;
$file->load(Yii::$app->request->post());
$a = UploadedFile::getInstance($file,'file');
$size = getimagesize($a->tempName);
$maxWidth = 500;
$maxHeight = 500;
if ($size[0] > $maxWidth || $size[1] > $maxHeight)
{
$model->addError('file', $error = 'Error Message');
if($model->hasErrors()){
return ActiveForm::validate($model);
}
}
$file->file = UploadedFile::getInstance($file,'file');
$file->file_name = $file->file->name;
$file->file_user = Yii::$app->user->id;
$file->file_type = 1;
if($file->save()){
$file->file_path = Files::getFilePath($file->file_id);
$validDir = $file->file->createFileDir($file->file_path, $file->file_id);
if($validDir){
$file->file->saveAs($file->file_path, false);
if($file->save()){
$model->company_file = $file->file_id;
$model->save();
return $this->redirect(['index']);
}
}
}
}
}
How do I add error message in the controller and pass that to display on my form on the modal box.
Note: my form is displayed on the modal box.
Thank you!!
You should handle the file processing in your model - or even better, create a specific UploadForm model for this purpose.
In that case you can use File Validation or a custom validator to set errors during model validation.
The built-in yii\validators\FileValidator gives you plenty pf validation rules out of the box.
This is actually pretty well explained in the documentation: Uploading Files
See also the documentation for FileValidator
Example for validating an uploaded image file:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
Try this validation rule
['imageFile', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250, 'extensions' => 'jpg, gif, png', 'maxSize' => 1024 * 1024 * 2],
I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920
I want to have a add more button on clicking which i can add dynamically, textboxes in a drupal form api.. can someone help on this?
Thanks in advance
Take a look at Adding dynamic form elements using AHAH. It is a good guide to learn AHAH with Drupal's form API.
EDIT: For an example, install the Examples for Developers module, it has an AHAH example you can use to help you learn.
Here is an example how to solve this with Ajax in Drupal 7(If anyone want I can convert it also to Drupal 6 using AHAH(name before it became Ajax)).
<?php
function text_boxes_form($form, &$form_state)
{
$number = 0;
$addTextbox = false;
$form['text_lists'] = array
(
'#tree' => true,
'#theme' => 'my_list_theme',
'#prefix' => '<div id="wrapper">',
'#suffix' => '</div>',
);
if (array_key_exists('triggering_element', $form_state) &&
array_key_exists('#name', $form_state['triggering_element']) &&
$form_state['triggering_element']['#name'] == 'Add'
) {
$addTextbox = true;
}
if (array_key_exists('values', $form_state) && array_key_exists('text_lists', $form_state['values']))
{
foreach ($form_state['values']['text_lists'] as $element) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
$number++;
}
}
if ($addTextbox) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
}
$form['add_button'] = array(
'#type' => 'button',
'#name' => 'Add',
'#ajax' => array(
'callback' => 'ajax_add_textbox_callback',
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
'#value' => t('Add'),
);
return $form;
}
function ajax_add_textbox_callback($form, $form_state)
{
return $form['text_lists'];
}
function text_boxes_menu()
{
$items = array();
$items['text_boxes'] = array(
'title' => 'Text Boxes',
'description' => 'Text Boxes',
'page callback' => 'drupal_get_form',
'page arguments' => array('text_boxes_form'),
'access callback' => array(TRUE),
'type' => MENU_CALLBACK,
);
return $items;
}