Create Button in last page pagination codeigniter - forms

Hello there I have problem
I wanna create button in my pagination codeIgniter just in last page for submit form
here my code:
Controller:
function index() {
/* pagination config */
$this->load->library('pagination');
$config['base_url'] = site_url('dcm/index');
$config['per_page'] = 6;
$config['num_link'] = 5;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev' ;
$config['total_rows'] = $this->db->get('soal')->num_rows();
/* this my form still have problem but I have different post for this one */
/* if you have any Idea for this please check my Question */
$data['form_action'] = site_url('dcm/index');
$jawab = $this->input->post('jawab');
$id_soal = $this->input->post('id_soal');
$this->dcm_model->inputJawab();
/* */
/* pagination setting */
$this->pagination->initialize($config);
$data['query'] = $this->db->get('soal', $config['per_page'], $this->uri->segment(3));
$data['link'] = $this->pagination->create_links();
$this->load->view('dcm/soal', $data);
}
in view:
<form action="<?php echo $form_action; ?>">
<?php foreach($query->result() as $row) { ?>
<?php echo $row->id_soal . '. ' . $row->soal; ?>
<input type="checkbox" checked="checked" value="<?=$row->id_soal;?>" name="jawab[]" />
<?php } ?>
<?php echo $link; ?>
</form>
<input align="center" type="submit" value="selesai" />

You can check if you are on the last page with this code:
if($this->pagination->cur_page >=
ceil($this->pagination->total_rows / $this->pagination->per_page))
{
$isLastPage = true;
}
else
{
$isLastPage = false;
}
You can pass the $isLastPage variable to your view.

Related

Magento 2.2 - Append Attribute Name To Product Name (H1)

This is driving me nuts, I created a module with a helper:
namespace MyNamespace\MyModule\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $registry;
public function __construct
(
\Magento\Framework\Registry $registry,
\Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet
) {
$this->registry = $registry;
$this->attributeSet = $attributeSet;
}
public function getTitle()
{
$this->product = $this->registry->registry('product');
$product_name = $this->product->getName();
$attributeSetRepository = $this->attributeSet->get($this->product->getAttributeSetId());
if ($attributeSetRepository->getAttributeSetName() == "Default Engine Component"){
$engine = $this->product->getAttributeText('engine_select');
if (!is_array($engine)){
return "$engine $product_name";
}
}
return $product_name;
}
}
...and this works as it should. Then I added the following to:
/app/design/frontend/vendor/theme/Magento_Catalog/layout/catalog_product_view.xml
<referenceBlock name="page.main.title">
<action method="setPageTitle">
<argument name="title" xsi:type="helper" helper="MyNamespace\MyModule\Helper\Data::getTitle"></argument>
</action>
</referenceBlock>
...but it changes nothing on the product page. I know it's getting called as I can echo out the vars and they show at the top of the page, but it seems that the XML isn't doing what I hoped it would.
Anyone got any ideas?
So, tried multiple variations of achieving what I wanted but in the end, I created a template under Magento_Catalog/templates/product (in my theme), which was based of the magento-theme title.phtml and then modified the page.main.title block in the catalog_product_view layout file.
The template code may look a bit odd (getAttribute and then getAttributeText) but there's no error handling for getAttributeText and with getAttribute, if an attribute has multiple values, it's returned in a string, not an array like getAttributeText. It would have been nicer if I could have made sure the value was always present by checking which attribute set was being used but although getAttributeSetId is part of the product model, it's not available in the product/view interceptor and tbh, I've given up on trying to figure out how all that works!
Anyway, this has taken far more hours than I'd care to admit to figure out so here's the code, hope it helps someone!
Template:
<?php
$product = $block->getProduct();
$product_name = $product->getName();
$attr_exists = $product->getResource()->getAttribute('attr_code');
$title = $product_name;
$cssClass = $block->getCssClass() ? ' ' . $block->getCssClass() : '';
if ($attr_exists){
$attr_name = $product->getAttributeText('attr_code');
if (!is_array($attr_name)){
$title = "$attr_name $product_name";
}
}
?>
<?php if ($title): ?>
<div class="page-title-wrapper<?= /* #escapeNotVerified */ $cssClass ?>">
<h1 class="page-title"
<?php if ($block->getId()): ?> id="<?= /* #escapeNotVerified */ $block->getId() ?>" <?php endif; ?>
<?php if ($block->getAddBaseAttributeAria()): ?>
aria-labelledby="<?= /* #escapeNotVerified */ $block->getAddBaseAttributeAria() ?>"
<?php endif; ?>>
<?= /* #escapeNotVerified */ $title ?>
</h1>
<?= $block->getChildHtml() ?>
</div>
<?php endif; ?>
Layout:
<block name="page.main.title" class="Magento\Catalog\Block\Product\View" template="Magento_Catalog::product/product-h1.phtml" />

Get shopping cart details in Magento2

I know in Magento 1 you can get the shopping cart details on any page with:
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productId = $item->getProduct()->getId();
$productPrice = $item->getProduct()->getPrice();
}
How do I do the same thing in Magento 2?
protected $_checkoutSession;
public function __construct (
\Magento\Checkout\Model\Session $_checkoutSession
) {
$this->_checkoutSession = $_checkoutSession;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$cartData = $this->_checkoutSession->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
}
you can get the quote data in observer
I figured this out by myself in the end:
<?php
$om = \Magento\Framework\App\ObjectManager::getInstance();
$cartData = $om->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
?>
<div class="bagDrop" id="bagDrop">
<h4>Quote Basket</h4>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
<div class="bagDropWindow">
<?php if( $cartDataCount > 0 ): ?>
<div class="bagDropList" id="bagDropList">
<?php foreach( $cartData as $item ): ?>
<?php $product = $item->getProduct(); ?>
<?php $image = $product['small_image'] == '' ? '/pub/static/frontend/Clear/usb2u/en_GB/images/default-category-image_1.png' : '/pub/media/catalog/product' . $product['small_image']; ?>
<a href="<?php echo $product['request_path']; ?>" class="bagDropListItem">
<img src="<?php echo $image; ?>">
<p>
<span class="name"><?php echo $product['name']; ?></span><br>
<span class="qty">x <?php echo $item->getQty(); ?></span>
</p>
</a>
<?php endforeach; ?>
</div>
<?php else: ?>
<div class="emptyList">No products in your basket.</div>
<?php endif; ?>
</div>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
</div>
Get Product Details in Checkout Page
<?php
namespace namespace\modulename\Block\xxx;
class xxx extends \Magento\Framework\View\Element\Template {
public function __construct(
\Magento\Checkout\Model\Cart $cart,
\namespace\modulename\Model\CrossSellFactory $crosssell,
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $data = []
) {
parent::__construct($context, $data);
$this->cart = $cart;
$this->_crosssell = $crosssell;
$this->customerSession = $customerSession;
$this->_objectManager = $objectManager;
}
public function getProductIds()
{
$productInfo = $this->cart->getQuote()->getItemsCollection();
foreach ($productInfo as $item) {
$item[] = $item->getProductId();
echo"<pre>";print_r($item->getProductId());
}
return $item;
}
}
Put the above .php file in your block and return the value in phtml file like i shown below.
<?php
$Productdetails = $block->getProductIds();
echo"<pre>";print_r($Productdetails->getName());
?>
You can easily get the shopping cart details in the Magento 2 by implementing the below-mentioned code:
<?php
$object = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $object->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartCount = count( $cart );
if($cartCount > 0){
echo $cartCount;
} else{
echo "0" ;
}
?>
Usage examples:
\Magento\Checkout\Block\Cart\AbstractCart::getQuote():
/**
* Get active quote
*
* #return Quote
*/
public function getQuote()
{
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Block\Cart\Totals::getQuote():
/**
* Get active or custom quote
*
* #return \Magento\Quote\Model\Quote
*/
public function getQuote()
{
if ($this->getCustomQuote()) {
return $this->getCustomQuote();
}
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Helper\Cart::getQuote():
/**
* Retrieve current quote instance
*
* #return \Magento\Quote\Model\Quote
* #codeCoverageIgnore
*/
public function getQuote()
{
return $this->_checkoutSession->getQuote();
}

validate capcha zend not correct

I have code:
$messages = array();
$isValid = TRUE;
$captcha = $this->_getParam('captcha_code', '');
if ( ! Captcha::validate($captcha)){
$isValid = FALSE;
$messages = array_merge($messages, array('Incorrect capcha.'));
}
}
if ($isValid AND count($messages) == 0) {
.............
}
else {
Captcha::destroy();
}
$this->view->register_messages = $messages;
and view:
<input name="captcha_code" type="text" class="input-text"/>
<?php if (isset($this->register_messages) && count($this->register_messages) > 0): ?>
<div class="alert-3">
<?php foreach ($this->register_messages as $message): ?>
<div><?= $message ?></div>
<?php endforeach; ?>
But when i enter correct capcha, it still showing "Incorrect capcha". I use zend 1
Please help me find this bug. Thanks a lot!

Laravel: Unable to redirect to get Route

Routes.php
Route::get("/", "MasterController#home");
Route::get("add/a/category", "MasterController#add_a_category");
Route::post("add/a/category", "MasterController#add_a_category_post");
MasterController.php
<?php
class MasterController extends BaseController {
public function add_a_category()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// viewing
return View::make("pages.add_a_category", $data);
}
public function add_a_category_post()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// controlling
CategoryModel::add();
}
}
?>
CategoryModel.php
<?php
class CategoryModel {
protected $fillable = array("category_name", "updated_at", "created_at");
public static function add()
{
// Validation
$rules = array("category_name" => "required|min:3|max:20");
$validation = Validator::make(Input::except("submit"), $rules);
if ( $validation->fails() )
{
return Redirect::to("add/a/category")->withErrors($validation);
}
else
{
$result = DB::table("categories")
->insert(
array(Input::except("submit"))
);
return Redirect::to("add/a/category");
}
}
}
?>
add_a_category.blade.php
#extends("layouts.master")
#section("content")
<h1>Add a Category</h1>
<form action="{{ URL::to("/") }}/add/a/category" method="POST">
<label for="category_name">Category Name</label>
<input type="text" name="category_name" value="">
{{ $errors->first("email", "<span class='error'>:error</span>") }}
<div style="clear: both;"></div>
<div class="submit">
<input type="submit" name="submit" value="Add">
</div>
</form>
#stop
Now when the validation passes or fails, I'm redirecting to add/a/category route. But I don't see anyhting except a blank page while the category_name field is getting added to the database.
You need to return the response of the model's add method to the Controller's response. Instead of:
ControllerModel::add():
Try
return ControllerModel:add();

dynamically load form in codeigniter

I am new to codeigniter trying out some simple pages. I have successfully connected to the database for inserting and updating. But now I want to populate the fields from the database for updating. That is when the user selects the name from the dropdown the corresponding values should appear in the other fields so that the user can update easily.
I have worked on this to do without ajax or jquery. It worked for me but with some warning message - Use of undefined constant.
I am giving by mvc. Help me clear this.
Controller:
public function update()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update Type';
$data['product_type'] = $this->editType_model->get_product_type();
$data['row'] = $this->editType_model->get_row();
$this->form_validation->set_rules('productype', 'productype', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('cm/update', $data);
$this->load->view('templates/footer');
}
else
{
$data['title']= 'Updation';
$data['message']= 'Updation succeeded';
$this->editType_model->update_news();
$this->load->view('cm/success', $data);
}
}
Model:
public function get_product_type() {
$data = array();
$this->db->order_by("product_type_name", "desc");
$query = $this->db->get('product_type');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function get_row() {
$data = array();
$id= $_POST[product_type_id];
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function update_news()
{
$this->load->helper('date');
$Product = $this->input->post('product_type_id');
$data = array(
'product_type_name'=>($_POST['productype']),
'rank'=>($_POST['rank'])
);
$this->db->where('product_type_id',$Product);
return $this->db->update('product_type', $data);
}
View:
<?php $productType = 0;
if(isset($_POST['product_type_id'])){
$productType = $_POST['product_type_id'];
}?>
<div id="Content"><div>
<form action="" method="post" name="f1">
<table ><tr><td>Select Product Type Name:</td>
<td><Select id="product_type_id" name="product_type_id" onChange="document.f1.submit()">
<option value="0">--SELECT</option>
<?php if (count($product_type)) {
foreach ($product_type as $list) { ?>
<option value="<?php echo $list['product_type_id']; ?>"
<?php if($productType==$list['product_type_id']) echo "Selected" ?> >
<?php echo $list['product_type_name']; ?></option>
<?php }} ?></Select></td></tr></table></form>
<?php if($productType){
if (count($row)) {
foreach ($row as $faProductType) { ?>
<div > <form action="" method="post" class="form-Fields" >
<input type="hidden" name="product_type_id" id="product_type_id" value="<?php echo $faProductType['product_type_id']; ?>" >
<table border="0" cellpadding="8" cellspacing="0" >
<tr><td>Product Type <font color="red">*</font></td><td style="width: 10px;"> : </td>
<td><input name="productype" type="text" value="<?php echo $faProductType['product_type_name']; ?>" style=" width:300px;" /></td>
<td><span class="err" id="productTypeDesc1Err"></span></td></tr>
<tr><td >Rank</td><td style="width:10px;"> : </td>
<td ><input type="text" name="rank" id="rank" value="<?php echo $faProductType['rank']; ?>" size="39" /> <span class="err" id="productTypeNameErr"></span></td>
<td ></td></tr><tr><td></td><Td colspan="2" align="center">
<input type="submit" value="Update" class="buttonimg" name='cm/editType/update' style="width:100px"
onClick="return validEditProductType();">
</Td><td></td></tr></table></form></div></div></div>
<?php }}} ?>
you can use Ajax for this purpose
onchange of your select box fill a div with form.
Controller Method
function getUserdata(){
$where['username'] = $this->input->post('username');
$this->load->model('users_model');
$data['user'] = $this->users_model->getUser($where);
$this->load->view('userform',$data);
}
And you model method
function getUser($where){
return $this->db->where($where)->get('usertable')->row()
}
Ajax
$(function(){
$('#selecttion').change(function(){
var username = $(this).val();
$.ajax({
url : '<?php 'echo url to controller method'?>',
type : 'POST' ,
data : 'username='+username,
success : function(data){
$('#dividtofill').html(data);
}
});
});
})
EDIT :
calling ajax is easy
for this include jquery library in your header.
Here is your dropdown
Note : put the above ajax code in your head section in script
<select name="user" id="selecttion">
<option value="John">John</option>
<option value="Sam">Sam</option>
<option value="David">David</option>
</select>
Now when this dropdown value is changed the ajax function defined above will be called.
I have finally cleared the error. I have done this by a simple if isset loop.
Now my get_row() in my model looks like this.
public function get_row() {
$data = array();
$id= 0;
if(isset($_POST['product_type_id'])){
$id = $_POST['product_type_id'];
}
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}