I'm having trouble doing a basic record update via POST in Laravel.
I have captured all the post data in an array, and if the existing Order# is 0, then I create a new record (works fine). Otherwise I update the existing record.
Order.php
class Order extends Eloquent {
public static $table = 'my_orders';
}
Routes.php
//Handle a new order POST
Route::post('order', array('do' => function() {
$thisOrder = array(
'qty' => Input::get('quantity'),
'desc' => Input::get('description'),
);
$thisOrderID = Input::get('orderNo');
//CHECK FOR NEW OR EXISTING ORDER
if($thisOrderID > 0) {
//THIS FUNCTION SOMEHOW RETURNS THE FUNCTION CALL AND DOESNT CONTINUE PAST
//AND THE RECORD IS NOT UPDATED
$updateOrder = Order::update($thisOrderID, $thisOrder);
}
}
Update:
The code above does in fact work. I had a validation error, which was causing the function to return early.
Instead of this line:
$updateOrder = Order::update($thisOrderID, $thisOrder);
You need to do:
$updateOrder = Order::find($thisOrderID)->update($thisOrder);
With find() (which equals where_id()) you select a specific row from the database and with update you pass the new data.
What do you think of this:
//Handle a new order POST
Route::post('order', array('do' => function() {
$thisOrder = array(
'qty' => Input::get('quantity'),
'desc' => Input::get('description'),
);
$thisOrderID = Input::get('orderNo');
$order = Order::find( $thisOrderID );
//CHECK FOR NEW OR EXISTING ORDER
if( $order ) {
$order->title = 'New order title';
$order->desc = 'New description';
$order->save();
}
}
erm , I will suggest to do it this way, if $thisOrder include the key, it will just update the record, else it will just create a new record.
$thisOrder = array(
'orderNo' => Input::get('orderNo'),
'qty' => Input::get('quantity'),
'desc' => Input::get('description'),
);
$updateOrder = Order::save($thisOrder);
if Input::get('orderNo') no value will be create else update
Related
This is the content of the global.php file:
return array(
'db' => array(
'driver' => 'Mysqli',
'database' => 'web_builder',
'username' => 'root',
'password' => ''
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
This is the content of my model:
namespace Application\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
class UsersTable extends AbstractTableGateway {
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
}
public function user_login($getData,$session_id){ // manage the user's login
$email = $getData['login_email'];
$password = $getData['login_password'];
$select = $this->adapter->query ("select count(*) as counter from users where email = '$email' and password = '".md5($password)."'");
$results = $select->execute();
if ($results->current()['counter'] == 1 ){
$select->getDataSource()->getResource()->closeCursor();
$update_user = $this->adapter->query("UPDATE users SET session_id = '".$session_id."' WHERE email = '".$email."'");
$update_session = $update_user->execute();
return 1;
}else{
return 0;
}
}
}
For some reason the update query is not working. If i commented the count query it works. I observed that i cannot execute multiple queries in the same function for some God know reason :P. I'm getting this message: Statement couldn't be produced with sql: ...... . Both query works perfectly if i executed them in phpmyadmin. Can anyone explain me why this cannot work ? I'm a little desperate :| , I spent severals hours on this
It could be a formatting / preparation issue, taking a look at the manual it suggests the following format to prepare your statement:
$adapter->query('SELECT * FROM `artist` WHERE `id` = ?', array(5));
So in your case try formatting it as so:
$select = $this->adapter->query ('select count(*) as counter from users where email = ? and password = ? ', $email , md5($password) );
I have a webpage with criteria fields which filters data. The query for this is:
CompanyAddress ca = null;
CompanyAddress cad = null;
WorkInfo wi = null;
PrivateInfo pi = null;
SearchResultInfo sri = null;
/***************************/
/* SEARCH FOR MAIN COMPANY */
/***************************/
var company = Session.QueryOver<Company>()
.JoinAlias(c => c.Addresses, () => ca)
.Where(() => ca.Main)
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property("Id").WithAlias(() => sri.TopId),
Projections.Property("ca.Id").WithAlias(() => sri.Id),
Projections.Property("Name").WithAlias(() => sri.Name),
Projections.Property("ca.Address").WithAlias(() => sri.Address),
Projections.Property("ca.ContactData").WithAlias(() => sri.ContactData),
Projections.Constant(ContactClassType.Company).WithAlias(() => sri.Type)
);
if (!string.IsNullOrEmpty(_name)) company = company.WhereRestrictionOn(c => c.Name).IsLike("%" + _name + "%");
//// TODO: fix error
if (_selectedTag != null) company = company.Where(Restrictions.In("_selectedTag", ca.Tags.Select(x => x.Tag.Id).ToArray()));
if (!string.IsNullOrEmpty(_selectedCity)) company = company.Where(() => ca.Address.City == _selectedCity);
if (_selectedCountry != null) company = company.Where(() => ca.Address.Country.Id == _selectedCountry);
if (!string.IsNullOrEmpty(_selectedZipCode)) company = company.Where(() => ca.Address.ZipCode == _selectedZipCode);
company.TransformUsing(Transformers.AliasToBean<SearchResultInfo>());
Now if selectedTag has an ID the query gives me an error telling ca is null. All the other where clauses work except this one. So I want to check if the incoming ID is in the Tag list from the object CompanyAddress.
Does anyone have an idea whats wrong here?
** SQL FROM ANDREW WITHTAKERS SOLUTION **
SELECT this_.Id as y0_,
ca1_.Id as y1_,
this_.Name as y2_,
ca1_.IdAddressType as y3_,
ca1_.Street as y4_,
ca1_.Number as y5_,
ca1_.ZipCode as y6_,
ca1_.City as y7_,
ca1_.Country as y8_,
ca1_.Email as y9_,
ca1_.Fax as y10_,
ca1_.PhoneNumber as y11_,
ca1_.CellNumber as y12_,
ca1_.Url as y13_,
#p0 as y14_
FROM CON_Company this_ inner join CON_CompanyAddress ca1_ on this_.Id=ca1_.IdCompany
inner join CON_CompanyAddrTag tagalias2_ on ca1_.Id=tagalias2_.IdCompanyAddr
WHERE ca1_.Main = #p1 and this_.Status = #p2 and tagalias2_.Id = #p3',N'#p0 int,#p1 bit,#p2 int,#p3 int',#p0=3,#p1=1,#p2=0,#p3=3
You're going to have to join to Tag in order to do this:
if (_selectedTag != null)
{
Tag tagAlias = null;
company
.JoinAlias(() => ca.Tags, () => tagAlias)
.Where(() => tagAlias.Id == _selectedTag.Id)
}
(Assuming you want Tags compared by Id)
The thing to remember about QueryOver/Criteria is that it's ultimately going to be turned into SQL. calling ca.Tags.Select(...) doesn't make sense from inside of a SQL query since there's an implied JOIN there to Tag.
Also, you're mixing QueryOver and Criteria syntax which is kind of confusing. I'd rework things a bit:
Company companyAlias = null;
var company = Session.QueryOver<Company>(() => companyAlias)
.JoinAlias(c => c.Addresses, () => ca)
.Where(() => ca.Main)
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property(() => companyAlias.Id).WithAlias(() => sri.TopId),
Projections.Property(() => ca.Id).WithAlias(() => sri.Id),
Projections.Property(() => companyAlias.Name).WithAlias(() => sri.Name),
Projections.Property(() => ca.Address).WithAlias(() => sri.Address),
Projections.Property(() => ca.ContactData).WithAlias(() => sri.ContactData),
Projections.Constant(ContactClassType.Company).WithAlias(() => sri.Type)
);
I need to add a pagination in this code:
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
I tried this example, but I can't do it with the join table.
Anyone can help me?
public function fetchAll($paginated=false)
{
if($paginated) {
// create a new Select object for the table album
$select = $this->getallAlbum();
// create a new result set based on the Album entity
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
// create a new pagination adapter object
$paginatorAdapter = new DbSelect(
// our configured select object
$select,
// the adapter to run it against
$this->tableGateway->getAdapter(),
// the result set to hydrate
$resultSetPrototype
);
$paginator = new Paginator($paginatorAdapter);
return $paginator;
}
$resultSet = $this->tableGateway->select();
return $resultSet;
}
function getallAlbum(){
$sql = new Select();
$sql->from('album')->columns(array('id', 'artist', 'title'))->join('albumcategory', 'album.catId = albumcategory.catId', array('catName' => 'catName'), Select::JOIN_LEFT);
return $sql;
}
Pagination should work fine with joins. This is what I have, similar to an example you provided:
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
return new \Zend\Paginator\Paginator(
new \Zend\Paginator\Adapter\DbSelect(
$select,
$this->tableGateway->getAdapter()
)
);
Please post an exact error that you are getting if the above doesn't work.
Thank you for the answer, but i tried your code, but i had this PDOException message:
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'school_parent_id'
I also tried, to adapat my "join tables" with the example of Rob Allen:
public function fetchAll($paginated=false)
{
if($paginated) {
// create a new Select object for the table album
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
// create a new result set based on the Album entity
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new School());
// create a new pagination adapter object
$paginatorAdapter = new DbSelect(
// our configured select object
$select,
// the adapter to run it against
$this->tableGateway->getAdapter(),
// the result set to hydrate
$resultSetPrototype
);
$paginator = new Paginator($paginatorAdapter);
return $paginator;
}
$resultSet = $this->tableGateway->select();
return $resultSet;
}
But the result is the same.
// create a new Select object for the table album
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
//change this like the following
// create a new Select object for the table album
$select = $this->yourFunction();
//and define yourFunction like
function youFunction(){
$sql = new Select();
$sql->from('school')->columns(array('schoolid', 'schoolname', 'anotherfield'))->join('school_parent', 'school.school_parent_id= school_parent.school_parent_id', array('schoolName' => 'schoolName'), Select::JOIN_LEFT);
return $sql;
}
Please try the join syntax
$select->from('table1')->join('table2', 'table1 = table2', array('table2.colum_to_return1', 'table2.colum_to_return2'));
Example pagination and sort Url
https://github.com/bigemployee/zf2-tutorial-paginate-sort
Try with another example pagination and sorting
### module_config.php ###
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id][/page/:page][/order_by/:order_by][/:order]',
'constraints' => array(
'action' => '(?!\bpage\b)(?!\border_by\b)[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
'page' => '[0-9]+',
'order_by' => '[a-zA-Z][a-zA-Z0-9_-]*',
'order' => 'ASC|DESC',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
###### AlbumController ###
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album;
use Album\Form\AlbumForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
class AlbumController extends AbstractActionController {
protected $albumTable;
public function indexAction() {
$select = new Select();
$order_by = $this->params()->fromRoute('order_by') ?
$this->params()->fromRoute('order_by') : 'id';
$order = $this->params()->fromRoute('order') ?
$this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$albums = $this->getAlbumTable()->fetchAll($select->order($order_by . ' ' . $order));
$itemsPerPage = 10;
$albums->current();
$paginator = new Paginator(new paginatorIterator($albums));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage($itemsPerPage)
->setPageRange(7);
return new ViewModel(array(
'order_by' => $order_by,
'order' => $order,
'page' => $page,
'paginator' => $paginator,
));
}
}
Add this line to your code:
$select->columns(array(new Expression('DISTINCT school.school_parent_id')));
OR something like this:
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id', array('sp_id' => 'school_parent_id'));
What I am actually doing is, fetching a list of companies from the database and passing that to the form SELECT element.
So I created a Model file, which returns an array
//=== return an array of $ID => $name of companies to use in dropdown in reports form
public function getTotalResult($table, $type, $id) {
$this->table = $table;
$select = new Select();
$spec = new Where();
$spec->equalTo('status', 1);
if ($type == 'name') {
$spec->equalTo('id', $id);
}
$select->from($this->table);
$select->where($spec);
$resultSet = $this->selectWith($select);
//$resultSet->buffer();
return $resultSet;
}
public function resultList($table){
$results = $this->getTotalResult($table, '', '');
foreach ($results as $result) {
$this->id[] = $result->id;
$this->name[] = $result->name;
}
$result = array_combine($this->id, $this->name);
return $result;
}
Then I tested this in my Controller, which returned exactly what I wanted:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use SpangelLogin\Model\Register; // <-- Add this import
use SpangelLogin\Model\companyList; // <-- Add this import
class RegisterController extends AbstractActionController
{
protected $registerTable;
protected $companyList;
public function getcompanyList()
{
if (!$this->companyList) {
$sm = $this->getServiceLocator();
$this->companyList = $sm->get('SpangelLogin\Model\companyList');
}
return $this->companyList;
}
public function indexAction()
{
//== get list of companies
$company_table = 'rs_company';
$sector_table = 'rs_sector';
$companiesList = $this->getcompanyList()->getName($company_table, 2);
}
}
So now I want this companiesList array passed in my form's Select Element. How can I achieve that. Here is my form in which I am using select.
use Zend\Form\Form;
use Zend\Form\Element;
class SectorReportForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('sectorreport');
$companiesArray = $this->companiesList();
$sectorsArray = $this->sectorsList();
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'company',
'attributes' => array(
'id' => 'company',
'multiple' => true,
'options' => $companiesArray,
),
'options' => array(
'label' => 'Company',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Upload',
'id' => 'submitbutton',
'class' => 'button violet right'
),
));
}
}
From a Design-Perspective, the best approach would be to handle this via Dependency-Injection. That sneaky little buzzword that confuses people so much, but actually is nothing more but to forward data between objects :P
General Dependency-Injection for Forms can be seen looking at the following answer, as well as my Blog article
How to get data from different model for select?
Zend\Form\Element\Select and Database-Values
If you do not want to go this approach, you can handle this at the Controller level, too.
$form = new My\Form();
$select = $form->get('selectCountries');
$model = new My\Countries();
$listData = $model->getCountriesAsArray();
$select->setValueOptions($listData);
I still advise you to go the different approach ;) Keeps the controllers more clean, too, which is always a good thing. Separation of concern!
I have a WP front end post form that I have made for my website, the Idea was to make it so artists can post up their own mixtape submissions!
So far I have managed to get the form to either use the image uploaded as the featured image OR give me the images ID so I can put it in the post content, the problem is I need both! I need the image automatically set as the thumbnail for the post and I need the ID so I can set the form to automatically put the image where I want it in the post!
So far I have located the problem to be this bit of code:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id
}
}
I say this as, the location of this code is what changes whether I successfully get the ID of the attachment or whether the image is set as the thumbnail.
The whole code is as follows:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
function mixtape_fep($content = null) {
global $post;
// We're outputing a lot of html and the easiest way
// to do it is with output buffering from php.
ob_start(); ?> <?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter the wine name';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter some notes';
}
$cover_id = get_post_meta($post->ID, 'thumb', true);
$cover = wp_get_attachment_link($cover_id);
$content = $cover.'<br /><br />'.$description;
$tags = $_POST['post_tags'];
// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
}
//SET OUR TAGS UP PROPERLY
wp_set_post_tags($pid, $_POST['post_tags']);
//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post'); ?>
The issue of assigning the thumbnail and inserting the image was fixed by adding this into the code:
if ( $_FILES ) {
$files = $_FILES['cover'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("cover" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
and then
set_post_thumbnail( $pid, $newupload );
below the insert post function.