Magento 2 get order in custom block - magento2

I have a custom module which sends email to custom email address after successful purchase. It works well but now I need to get gift message from order.
Here is my Block code
<?php
namespace Test\Test2\Block\Vendor\Shipment;
class Items extends \Magento\Framework\View\Element\Template
{
const DEFAULT_TYPE = 'default';
public function getItemRenderer($type)
{
/** #var \Magento\Framework\View\Element\RendererList $rendererList */
$rendererList = $this->getRendererListName() ? $this->getLayout()->getBlock($this->getRendererListName()) : $this->getChildBlock('renderer.list');
if (!$rendererList) {
throw new \RuntimeException('Renderer list for block "' . $this->getNameInLayout() . '" is not defined');
}
$overriddenTemplates = $this->getOverriddenTemplates() ?: [];
$template = isset($overriddenTemplates[$type]) ? $overriddenTemplates[$type] : $this->getRendererTemplate();
$renderer = $rendererList->getRenderer($type, self::DEFAULT_TYPE, $template);
$renderer->setRenderedBlock($this);
return $renderer;
}
public function getItemHtml(\Magento\Framework\DataObject $item)
{
$block = $this->getItemRenderer($item->getProductType())->setItem($item);
return $block->toHtml();
}
}
and email template .phtml
<?php $_items = $block->getItems() ?>
<?php $_order = $block->getOrder() ?>
<?php if ($_items): ?>
<table class="items email-items shipment-items order-items">
<thead>
<tr>
<th class="item-info">
<?= /* #escapeNotVerified */ __('Items'); ?>
</th>
<th class="item-price">
<?= /* #escapeNotVerified */ __('Price'); ?>
</th>
<th class="item-qty">
<?= /* #escapeNotVerified */ __('Qty'); ?>
</th>
<th class="row-total">
<?= /* #escapeNotVerified */ __('Total'); ?>
</th>
</tr>
</thead>
<?php foreach ($_items as $_item): ?>
<?php
if ($_item->getParentItem()) {
continue;
}
?>
<tbody>
<?= $block->getItemHtml($_item) ?>
</tbody>
<?php endforeach; ?>
</table>
<?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
<?php if ($_giftMessage): ?>
<br />
<table class="message-gift">
<tr>
<td>
<h3><?= /* #escapeNotVerified */ __('Gift Message for this Order') ?></h3>
<strong><?= /* #escapeNotVerified */ __('From:') ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('To:') ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('Message:') ?></strong>
<br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?>
</td>
</tr>
</table>
<?php endif; ?>
<?php endif; ?>
Obviously, I receive this error message:
Uncaught Error: Call to a member function getGiftMessageId()
since my block does not have the method getOrder.
But if I try to copy getOrder method from Magento\Sales\Block\Order\Items:
/**
* Retrieve current order model instance
*
* #return \Magento\Sales\Model\Order
*/
public function getOrder()
{
return $this->_coreRegistry->registry('current_order');
}
with __construct part
/**
* #param \Magento\Framework\View\Element\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param array $data
* #param \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory|null $itemCollectionFactory
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = [],
\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollectionFactory = null
) {
$this->_coreRegistry = $registry;
$this->itemCollectionFactory = $itemCollectionFactory ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory::class);
parent::__construct($context, $data);
}
it still shows an error that order object in null. What am I doing wrong? Or how can I obtain order object in my case? Thanks.

Related

Magento 2.1.10: Slick slider with ul li

I'm doing slick slider with ul li, and it doesn't work well.
What i mean is it take 2-5 second to load succesfully the slider (some time it take more than that). In that loading time, it look like this:
https://i.stack.imgur.com/kdte5.png
So here is the normal ul li, with out slick slider.
https://i.stack.imgur.com/ebF9m.png
And here is what after i put slick slider in:
https://i.stack.imgur.com/kdte5.png
Sorry because i cant post the direct image in here. I don't have enough reputaion to do that.
So here is the code:
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// #codingStandardsIgnoreFile
?>
<?php
/**
* Template for displaying products list widget
*
* #var $block \Gssi\ProductsSlider\Block\Product\ProductsList
*/
?>
<?php if ($exist = ($block->getProductCollection() && $block->getProductCollection()->getSize())):?>
<?php
$type = 'widget-product-grid';
$mode = 'grid';
$image = 'new_products_content_widget_grid';
$title = $block->getTitle() ? __($block->getTitle()) : '';
$items = $block->getProductCollection()->getItems();
$showWishlist = true;
$showCompare = true;
$showCart = true;
$templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::DEFAULT_VIEW;
$description = false;
?>
<div class="block widget block-products-list <?php /* #escapeNotVerified */ echo $mode; ?>">
<?php if ($title):?>
<div class="block-title">
<strong><?php /* #escapeNotVerified */ echo $title; ?></strong>
</div>
<?php endif ?>
<div class="block-content">
<?php /* #escapeNotVerified */ echo '<!-- ' . $image . '-->' ?>
<div class="products-<?php /* #escapeNotVerified */ echo $mode; ?> <?php /* #escapeNotVerified */ echo $mode; ?>">
<ul class="slick-custom product-items <?php /* #escapeNotVerified */ echo $type; ?>">
<?php $iterator = 1; ?>
<?php foreach ($items as $_item): ?>
<?php /* #escapeNotVerified */ echo($iterator++ == 1) ? '<li class="product-item">' : '</li><li class="product-item">' ?>
<div class="product-item-info">
<a href="<?php /* #escapeNotVerified */ echo $block->getProductUrl($_item) ?>" class="product-item-photo">
<?php echo $block->getImage($_item, $image)->toHtml(); ?>
</a>
<div class="product-item-details">
<strong class="product-item-name">
<a title="<?php echo $block->escapeHtml($_item->getName()) ?>"
href="<?php /* #escapeNotVerified */ echo $block->getProductUrl($_item) ?>"
class="product-item-link">
<?php echo $block->escapeHtml($_item->getName()) ?>
</a>
</strong>
<?php
echo $block->getProductPriceHtml($_item, $type);
?>
<?php if ($templateType): ?>
<?php echo $block->getReviewsSummaryHtml($_item, $templateType) ?>
<?php endif; ?>
<?php if ($showWishlist || $showCompare || $showCart): ?>
<div class="product-item-actions">
<?php if ($showCart): ?>
<div class="actions-primary">
<?php if ($_item->isSaleable()): ?>
<?php if ($_item->getTypeInstance()->hasRequiredOptions($_item)): ?>
<button class="action tocart primary"
data-mage-init='{"redirectUrl":{"url":"<?php /* #escapeNotVerified */ echo $block->getAddToCartUrl($_item) ?>"}}'
type="button" title="<?php /* #escapeNotVerified */ echo __('Add to Cart') ?>">
<span><?php /* #escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>
<?php else: ?>
<?php
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
?>
<button class="action tocart primary"
data-post='<?php /* #escapeNotVerified */ echo $postData; ?>'
type="button" title="<?php /* #escapeNotVerified */ echo __('Add to Cart') ?>">
<span><?php /* #escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>
<?php endif; ?>
<?php else: ?>
<?php if ($_item->getIsSalable()): ?>
<div class="stock available"><span><?php /* #escapeNotVerified */ echo __('In stock') ?></span></div>
<?php else: ?>
<div class="stock unavailable"><span><?php /* #escapeNotVerified */ echo __('Out of stock') ?></span></div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($showWishlist || $showCompare): ?>
<div class="actions-secondary" data-role="add-to-links">
<?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $showWishlist): ?>
<a href="#"
data-post='<?php /* #escapeNotVerified */ echo $block->getAddToWishlistParams($_item); ?>'
class="action towishlist" data-action="add-to-wishlist"
title="<?php /* #escapeNotVerified */ echo __('Add to Wish List') ?>">
<span><?php /* #escapeNotVerified */ echo __('Add to Wish List') ?></span>
</a>
<?php endif; ?>
<?php if ($block->getAddToCompareUrl() && $showCompare): ?>
<?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');?>
<a href="#" class="action tocompare"
data-post='<?php /* #escapeNotVerified */ echo $compareHelper->getPostDataParams($_item);?>'
title="<?php /* #escapeNotVerified */ echo __('Add to Compare') ?>">
<span><?php /* #escapeNotVerified */ echo __('Add to Compare') ?></span>
</a>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<?php echo($iterator == count($items)+1) ? '</li>' : '' ?>
<?php endforeach ?>
</ul>
</div>
<?php echo $block->getPagerHtml() ?>
</div>
</div>
<script>
require([
'jquery',
'slick'
], function ($) {
$(document).ready(function () {
$('.slick-custom').slick({
slidesToShow: 5,
speed: 300,
autoplay: true
});
});
});
</script>
<?php endif;?>
I've try put this in slick slider option, but doesn't work at all:
slide: 'li',
track: function() { return $(this).children('product-item'); },
EDIT 1:
After 6 hours looking for the answer, i've found the reason (or atleast i thing its the reason :D ).
Okay, so i guest its because Magento wasn't load the javascript in time. I mean it take a while to load this slick slider javascript.
Right now, it take about 1-2 seconds for slick slider called successfully. And in that 1-2 seconds, it will render that problem out (just like in picture 2).
Ok so the problem is still there, if you guys have any suggestion, please tell me. Thanks alot :)
EDIT 2:
I'm follow #HoangHieu solution, but doesn't seem to work
Here is what i've done :
<div class="products-<?php /* #escapeNotVerified */ echo $mode; ?> <?php /* #escapeNotVerified */ echo $mode; ?>" data-mage-init='{ "slick": {} }'>
<ul class="slick-custom product-items <?php /* #escapeNotVerified */ echo $type; ?>">
// some li
<li>...</li>
</ul>
</div>
I've added data-mage-init='{ "slick": {} }' in the . I called "slick" because that is what i define slickSlider in requirejs-config.js
var config = {
map: {
'*': {
slick: 'Gssi_ProductsSlider/js/lib/slick',
}
}
};
EDIT 3:
Okay so here is what i've done til now after #HoangHieu solution:
<ul class="slick-custom product-items <?php /* #escapeNotVerified */ echo $type; ?>" data-mage-init='{ "callSlick": {} }'>
//some li
</ul>
call-slick.js
define(['jquery', 'slick'], function ($) {
"use strict";
return function (config, element) {
let defaultConfig = {
infinite: true,
slidesToShow: 4,
speed: 300,
autoplay: true,
arrows: false,
dots: false,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 4
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 3
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 2
}
}
]
};
$(element).slick($.extend({}, defaultConfig, config));
};
});
requirejs-config.js
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
var config = {
map: {
'*': {
slick: 'Gssi_ProductsSlider/js/lib/slick',
callSlick: 'Gssi_ProductsSlider/js/call-slick'
}
}
};
Some widget will load after the page loaded. By if you search in HTML about <!-- BLOCK -- that is https://devdocs.magento.com/guides/v2.1/extension-dev-guide/cache/page-caching/private-content.html
Flow here
Html loaded --> KnoutJs UIComponent get Prefix BLOCK to load --> Load Block HTML using AJAX --> Append to BODY.
that means you can't apply Slick Slider by using simple ways. Using Component instead
<div data-mage-init="{'slickSlider':{}}">
<ul>
<li></li>
</ul>
</div>
See more here: https://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/js_init.html
Update 2: I think you didn't read my related documents. I will give you an example.
1: My Product List Widget Template.
<ol class="product-items <?= /* #escapeNotVerified */ $type ?>" data-mage-init='{"callSlick":{}}'>
<?php $iterator = 1; ?>
<?php foreach ($items as $_item): ?>
<?= /* #escapeNotVerified */ ($iterator++ == 1) ? '<li class="product-item">' : '</li><li class="product-item">' ?>
<div class="product-item-info">
<a href="<?= /* #escapeNotVerified */ $block->getProductUrl($_item) ?>" class="product-item-photo">
<?= $block->getImage($_item, $image)->toHtml() ?>
</a>
<div class="product-item-details">
<strong class="product-item-name">
<a title="<?= $block->escapeHtml($_item->getName()) ?>"
href="<?= /* #escapeNotVerified */ $block->getProductUrl($_item) ?>"
class="product-item-link">
<?= $block->escapeHtml($_item->getName()) ?>
</a>
</strong>
</div>
</div>
<?= ($iterator == count($items)+1) ? '</li>' : '' ?>
<?php endforeach ?>
</ol>
Requiejs-config.js
var config = {
map: {
'*': {
slickSlider: 'Magento_Catalog/js/slick', //Slick slider libary
callSlick: 'Magento_Catalog/js/call-slick'
}
}
};
call-slick.js
/**
* Created by Hidro Le.
* Job Title: Magento Developer
* Date: 27/08/2018
* Time: 10:16
*/
define(['jquery', 'slickSlider'], function ($) {
"use strict";
return function (config, element) {
let defaultConfig = {
infinite: true,
slidesToShow: 3,
slidesToScroll: 3
};
$(element).slick($.extend({}, defaultConfig, config));
};
});
**Update 2: ** The result exactly example.
Update 3: If you are work with your team. Please recheck page Style Sheet, Create new page content with an empty layout to make sure didn't have any custom CSS affected on your code.

Magento2 reuse add to cart form template

Is it possible to reuse somehow magentos 2 add to cart form in a custom module? I have in tab all child products of current product and I want to allow customers to add to cart products so thats how looks my code at this status
<?php
if ($currentProduct = $block->getCurrentProduct()) {
$variants = $block->getVariants($currentProduct);
if($variants) { ?>
<ul id="product-variants">
<?php foreach ($variants as $_product) : ?>
<li>
<form>
<?php echo $_product->getName(); ?>
SKU: <?php echo $_product->getSku(); ?>
Brutto: <?php echo $_product->getPrice(); ?>
<input type="text" placeholder="Stück">
<button>Add to cart</button>
</form>
</li>
<?php endforeach; ?>
</ul>
<?php };
}
?>
you can add button in custom phtml file as follow, I have done this in custom module
In your block file
use Magento\Catalog\Block\Product\ListProduct;
<?php
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Block\Product\ListProduct $listProductBlock,
array $data = []
) {
parent::__construct($context, $data);
$this->_productCollectionFactory = $productCollectionFactory;
$this->listProductBlock = $listProductBlock;
}
public function getProductCollection()
{
/** #var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->load();
return $collection;
}
public function getAddToCartPostParams($product)
{
return $this->listProductBlock->getAddToCartPostParams($product);
}
?>
get productlist in view file
<?php
const PARAM_NAME_BASE64_URL = 'r64';
const PARAM_NAME_URL_ENCODED = 'uenc';
use Magento\Framework\App\Action\Action;
$_productCollection = $block->getProductCollection();
?>
<?php foreach ($_productCollection as $_product): ?>
<?php $postParams = $block->getAddToCartPostParams($_product); ?>
<?php echo $_product->getName()?>
<form data-role="tocart-form" action="<?php /* #escapeNotVerified */ echo $postParams['action']; ?>" method="post">
<input type="hidden" name="product" value="<?php /* #escapeNotVerified */ echo $postParams['data']['product']; ?>">
<input type="hidden" name="<?php /* #escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* #escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
<?php echo $block->getBlockHtml('formkey')?>
<?php $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Store\Model\StoreManagerInterface'); ?>
<button type="submit"
title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
class="action tocart primary">
<span><?php /* #escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>
</form>
<?php endforeach;?>

Access an id of a user in a table from a controller

PHP, Zend Framework, Apache, MySql.
I want to edit a user in a list by clicking its corresponding edit button.
when i click the edit button, the corresponding users id should be send to the controller from where it should be accessed.
But I cant seem to get the user id in the controller.
After getting the id , i want to populate the fields in edit.phtml with the data retrieved view model.
Since i cant access the id, i cant populate the fields.
The url is like /Sample/user/edit/2 where 2 is id of a user.
UserController.php
<?php
class UserController extends Zend_Controller_Action
{
protected $_user;
public function init()
{
/* Initialize action controller here */
$this->_user = new Application_Model_User();
}
public function indexAction()
{
// action body
}
public function listAllAction()
{
// action body
$this->view->users = $this->_user->listUsers();
}
public function registerAction()
{
// action body
if($this->getRequest()->isPost())
{
$data = array(
'user_uname' => $this->_request->getParam('uname'),
'user_pwd' => $this->_request->getParam('paswd'),
'user_address' => $this->_request->getParam('address')
);
$this->_user->insert($data);
}
}
public function editAction()
{
// action body
**$u_id = $this->_request->getParam('user_id');**
// print_R("Hi ".$u_id);
// exit;
if($this->_request->isPost())
{
$u_id = $this->_request->getPost('user_id');
//print_R("Hi ".$u_id);
//exit;
}
else
{
**$this->view->user = $this->_user->getUser($u_id);**
}
}
}
Model class
<?php
class Application_Model_User extends Zend_Db_Table_Abstract
{
protected $_name="tbl_user";
public function listUsers()
{
// action body
$sql = "select * from tbl_user";
$result = $this->_db->query($sql);
return $result->fetchAll();
}
public function getUser($id)
{
$query = "select * from tbl_user where user_id = ?";
return $this->_db->fetchRow($query,array($id));
}
}
ListUser.phtml
<html>
<head></head>
<body>
<b><center>List of Users</center></b>
<form name="list_users" method="post" action="">
<table>
<tr><th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php foreach ($this->users as $usr): ?>
<tr>
<td><?php echo $usr['user_id'] ?></td>
<td><?php echo $usr['user_uname'] ?></td>
<td><?php echo $usr['user_pwd'] ?></td>
<td><?php echo $usr['user_address'] ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=2>Add More Users</td>
</tr>
</table>
</form>
</body>
</html>
edit.phtml
<html>
<head></head>
<body>
<form name="user_edit" method="post" action="<?php print $this->baseUrl(); ?>/user/edit">
<b><center>Edit Profile</center></b>
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname" id="uname1" value="<?php print $this->user['user_uname'] ?>"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="paswd" id="paswd1"/></td>
</tr>
<tr>
<td>Address</td>
<td><textarea type="text" name="address" id="address1"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='edit_user' value='Update User'/></td>
</tr>
<tr>
<td colspan=2>See All Users</td>
</tr>
</table>
</body>
</html>
Thank you in advance..
I got the answer.
In usercontroller's editaction change the code $u_id = $this->_request->getParam('user_id'); to $u_id = $this->getRequest()->getParam('id');
Small change needed: change the following line:
<td>Edit</td>
to
<td>Edit</td>

what is the difference between form and chtml in yii

confusion between form and chtml
i used to form to write form ans submit to database working fine, but for some particular places, according to google search used CHTML instead of form. but when i submitted that form to database
CHTML textfield value is not submitting to database
here goes my code
_Form.php
<script language="javascript">
function firstlang(flang,slang,tlang,math,scien,soci)
{
var sflang=parseInt(flang)+parseInt(slang)+parseInt(tlang)+parseInt(math)+parseInt(scien)+parseInt(soci);
document.getElementById('totalmarks').value=sflang;
if(sflang>=300 && sflang<400)
{
var flang='C';
document.getElementById('grade').value=flang;
}
else if(sflang>=400 && sflang<500)
{
var flang='B';
document.getElementById('grade').value=flang;
}
else if(sflang>=550 && sflang<=600)
{
var flang='A';
document.getElementById('grade').value=flang;
}
}
</script>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'marks-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'focus'=>array($model,'class'),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<table width="200" border="1">
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'class'); ?></span></td>
<td><span class="row">
<?php echo CHtml::dropDownList('class','',CHtml::listData(class1::model()->findAll(),'class','class'),array('empty'=>'Choose one',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Marks/dynamicstates'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#studentid', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
?></span></td>
<td><span class="row"><?php echo $form->error($model,'class'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'studentid'); ?></span></td>
<td><span class="row"><?php echo CHtml::dropdownlist('studentid','',array()); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'studentid'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'examtype'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'examtype',array('size'=>30,'maxlength'=>30)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'examtype'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'firsttlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'firsttlanguage',array('id'=>'firsttlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,secondlanguage.value,thirdlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'firsttlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'secondlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'secondlanguage',array('id'=>'secondlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,thirdlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'secondlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'thirdlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'thirdlanguage',array('id'=>'thirdlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'thirdlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'mathematics'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'mathematics',array('id'=>'mathematics','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'mathematics'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'science'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'science',array('id'=>'science','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,mathematics.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'science'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'social'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'social',array('id'=>'social','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,mathematics.value,science.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'social'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'totalmarks'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'totalmarks',array('id'=>'totalmarks','size'=>5,'maxlength'=>5)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'totalmarks'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'grade'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'grade',array('id'=>'grade','size'=>5,'maxlength'=>5)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'grade'); ?></span></td>
</tr>
<tr>
<td> </td>
<td><span class="row buttons"><?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?></span></td>
<td> </td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form -->
MarksController.php
<?php
class MarksController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','dynamicstates'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Marks;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Marks']))
{
$model->attributes=$_POST['Marks'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Marks']))
{
$model->attributes=$_POST['Marks'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Marks');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Marks('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Marks']))
$model->attributes=$_GET['Marks'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Marks::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='marks-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actiondynamicstates()
{
// $model1=new Examresults;
/*$exam_type=(int)$_POST['exam_type'];
if ($exam_type==0)
$data=array(0=>'States:');
else if ($exam_type==1)
$data=array(1=>'Alaska', 2=>'California');
else if ($exam_type==2)
$data=array(1=>'Orleans', 2=>'Bordeaux');
else if ($exam_type==3)
$data=array(1=>'Hokkaido', 2=>'Okinawa');*/
//$schoolfee = feesettings::model()->find("feetype='schoolfee' and class='".$_REQUEST['class']."'");
$data=admission::model()->findAll('class=:class',
array(':class'=>$_POST['class']));
$data=CHtml::listData($data,'studentid','studentfname');
foreach($data as $value=>$name)
echo CHtml::tag('option', array('value'=>$value), CHtml::encode($name), true);
}
}
Marks.php
<?php
/**
* This is the model class for table "marks".
*
* The followings are the available columns in table 'marks':
* #property integer $id
* #property string $class
* #property string $studentid
* #property string $examtype
* #property integer $firsttlanguage
* #property integer $secondlanguage
* #property integer $thirdlanguage
* #property integer $mathematics
* #property integer $science
* #property integer $social
* #property integer $totalmarks
* #property string $grade
*/
class Marks extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Marks the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'marks';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('class, studentid', 'required'),
array('firsttlanguage, secondlanguage, thirdlanguage, mathematics, science, social, totalmarks', 'numerical', 'integerOnly'=>true),
array('class, studentid, examtype', 'length', 'max'=>30),
array('grade', 'length', 'max'=>5),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, class, studentid, examtype, firsttlanguage, secondlanguage, thirdlanguage, mathematics, science, social, totalmarks, grade', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'class' => 'Class',
'studentid' => 'Studentid',
'examtype' => 'Examtype',
'firsttlanguage' => 'Firsttlanguage',
'secondlanguage' => 'Secondlanguage',
'thirdlanguage' => 'Thirdlanguage',
'mathematics' => 'Mathematics',
'science' => 'Science',
'social' => 'Social',
'totalmarks' => 'Totalmarks',
'grade' => 'Grade',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('class',$this->class,true);
$criteria->compare('studentid',$this->studentid,true);
$criteria->compare('examtype',$this->examtype,true);
$criteria->compare('firsttlanguage',$this->firsttlanguage);
$criteria->compare('secondlanguage',$this->secondlanguage);
$criteria->compare('thirdlanguage',$this->thirdlanguage);
$criteria->compare('mathematics',$this->mathematics);
$criteria->compare('science',$this->science);
$criteria->compare('social',$this->social);
$criteria->compare('totalmarks',$this->totalmarks);
$criteria->compare('grade',$this->grade,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
Have a look here Creating Form. Since Yii 1.1.1 there is a widget called CActiveForm
so when you use this widget you create the form inputs with $form->textField($model,'username')instead of using CHtml::activeTextField($model,'username')but both work in the same way.
So if that field is not being saved in the database it's probably because you haven't added it to the rules of your model.
public function rules() {
return array(
array('username', 'safe'),
);
)

jquery ajax in Zend framework

i am new to ZF i want to create ajax link that will go to "task" controller and "ajax" action
do something like this
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$sql = "SELECT * FROM task ORDER BY task_name ASC";
$result = $DB->fetchAll($sql);
than put the result in this div
<div id="container">container</div>
this is my view where i am doing this
<?php echo $this->jQuery()->enable(); ?>
<?php echo $this->jQuery()->uiEnable(); ?>
<div id="container">container</div>
<?php
echo $this->ajaxLink("Bring All Task","task/ajax",array('update' => '#container'));
?>
i dont know the syntax how i will do this , retouch my code if i am wrong i searched alot but all in vain plz explain me thanking you all in anticipation also refer me some nice links of zendx_jquery tutorial
This should work:
class IndexController extends Zend_Controller_Action
{
/**
* Homepage - display result of ajaxRequest
*/
public function indexAction()
{
}
/**
* Print result of database query
*/
public function ajaxAction()
{
// disable rendering of view and layout
$this->_helper->layout()->disableLayout();
$registry = Zend_Registry::getInstance();
$db = $registry['DB'];
// get select object to build query
$select = $db->select();
$select->from('task')->order('task_name ASC');
// echo result or what ever..
$this->view->tasks = $db->fetchAll($select);
}
}
// index.phtml (view)
<?php
echo $this->jQuery()->enable();
echo $this->jQuery()->uiEnable();
// create link to ajaxAction
$url = $this->url(array(
'controller' => 'index',
'action' => 'ajax',
));
?>
<div id="container">container</div>
<?php
echo $this->ajaxLink(
"Bring All Task", $url, array('update' => '#container')
);
?>
and in your ajax.phtml
<?php if ($this->tasks): ?>
<table>
<tr>
<th>task ID</th>
<th>task Name</th>
</tr>
<?php foreach($this->tasks as $task) : ?>
<tr>
<td><?php echo $task['task_id']; /* depending on your column names */ ?>
</td>
<td><?php echo $this->escape($task['task_name']); /* to replace " with " and so on */ ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
No tasks in table.
<?php endif; ?>
regarding db you have to setup it first somewhere earlier in your code, for example front controller index.php or bootstrap.php, for example:
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
Zend_Registry::set('DB', $db);