I have {{ knp_pagination_render(pagination1) }} on view InfCustumersBundle:Faktura:indexoryginal.html.twig
This code show me paginarion:
public function indexoryginalAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$req = $em->getRepository('...:Faktura');
$qb = $req->createQueryBuilder('p');
$search = $qb
.
.
->getQuery();
$form = $this->createFormBuilder()
.
.
->getForm();
$paginator = $this->get('knp_paginator');
$pagination1 = $paginator->paginate(
$search, $request->query->get('page', 1)/* page number */, 5/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
and this work fine, but code bellow don't show pagination tags. Only the first 3 items. Where I made a mistake ?
public function indexAction(Request $request, $type = 1) {
$data = array();
$form = $this->createFormBuilder()
.
.
->getForm();
if ($request->isMethod('GET')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$name = ($data['for'] == 'name' ? true : false);
if ($name) {
return $this->Name($form);
}
}
return $this->redirect($this->generateUrl('faktura_oryginal', array(
$this->get('session')->getFlashBag()->add('error', 'error')
)));
}
protected function Name($form) {
$em2 = $this->getDoctrine()->getManager();
$req = $em2->getRepository('InfCustomersBundle:Faktura');
$qb = $req->createQueryBuilder('p');
$query2 = $qb
.
.
->getQuery();
$entities2 = $query2->getResult();
if ($entities2) {
$paginator = $this->get('knp_paginator');
$request = $this->get('request_stack');
// $request = $this->getRequest();
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page', 1)/* page number */, 3/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
} else {
return $this->redirect($this->generateUrl('faktura_oryginal', array( $this->get('session')->getFlashBag()->add('error', 'error')
)));
}
}
}
I found a solution
I changed:
$entities2 = $query2->getResult();
if ($entities2) {
to
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page',1),25);
if (count($pagination1) > 0) {
and now is working well
Related
I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}
How can I get the current Post? I'm trying to redirect to my current post where im sending my vote but this method that i created redirects to Oldest Post created by this user.
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idPoster = $request->request->get('id_posterUser');
$positive= $request->request->get('positive');
$negative= $request->request->get('negative');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
$score = $usuari->getReputation();
if ($positive!= null) {
$score = $score + 1;
}
if($negative!= null){
$score = $score - 1;
}
$user->setReputation($score );
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
Edit: Added my Solution.
Solution :
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idTopic = $request->request->get('id_topic');
$idPoster = $request->request->get('id_poster');
$positive= $request->request->get('positive');
$negative= $request->request->get('negatiu');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneById($idTopic);
$score= $user->getReputation();
if ($positive!= null) {
$score= $score+ 1;
}
if($negative!= null){
$score= $score- 1;
}
$user->setReputation($score);
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
You are searching topic by user:
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
findOneByUser - builds query WHERE user.id = :user_id LIMIT 1
For get the last Topic you need to add ordering.
$topic = $em->getRepository(Topic::class)->findOneBy(
array('user' => $user),
array('id' => 'desc')
);
I have created a form for an entity Event with user's fields like "email" and "password" what I use to create a user manually in the controller.
I can create the event and the user without problems, but I need to send a confirmation mail to enable the user. I can do it from the normal registration form, but here I don't know how to do it.
Sorry if my english isn't very good. I'm learning it.
The controller:
class EventController extends Controller
{
public function ajaxAction(Request $request) {
if (! $request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get the province ID
$id = $request->query->get('category_id');
$result = array();
// Return a list of cities, based on the selected province
$repo = $this->getDoctrine()->getManager()->getRepository('CASEventBundle:Subcategory');
$subcategories = $repo->findByCategory($id, array('category' => 'asc'));
foreach ($subcategories as $subcategory) {
$result[$subcategory->getName()] = $subcategory->getId();
}
return new JsonResponse($result);
}
public function indexAction(Request $request) {
$lead = new Lead();
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
if(is_object($user)) {
$promotor = $em->getRepository('CASUsuariosBundle:Promotor')->find($user);
if (is_object($promotor)) {
$form = $this->createForm(new EventType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:event.html.twig";
$isPromotor = true;
}
} else {
$form = $this->createForm(new LeadType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:full_lead.html.twig";
$isPromotor = false;
}
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
if($isPromotor === true) {
$type = $promotor->getType();
$name = $user->getName();
$lastname = $user->getLastName();
$email = $user->getEmail();
$password = $user->getPassword();
$phone = $user->getPhone();
$company = $promotor->getCompany();
$lead->setEventType($type);
$lead->setPromotorName($name);
$lead->setPromotorLastName($lastname);
$lead->setPromotorEmail($email);
$lead->setPromotorPhone($phone);
$lead->setPromotorCompany($company);
}
$emailReg = $form->get('promotorEmail')->getData();
$passwordReg = $form->get('promotorPassword')->getData();
$nameReg = $form->get('promotorName')->getData();
$typeReg = $form->get('promotorType')->getData();
$lastnameReg = $form->get('promotorLastName')->getData();
$phoneReg = $form->get('promotorPhone')->getData();
$companyReg = $form->get('promotorCompany')->getData();
if(!empty($emailReg) && !empty($passwordReg)) {
$userManager = $this->get('fos_user.user_manager');
$newUser = $userManager->createUser();
$newPromotor = new Promotor();
$newUser->setUsername($emailReg);
$newUser->setEmail($emailReg);
$newUser->setName($nameReg);
$newUser->setLastname($lastnameReg);
$newUser->setPhone($phoneReg);
$newUser->setIsPromotor(true);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($newUser, strval($passwordReg));
$newUser->setPassword($encoded);
$userManager->updateUser($newUser);
$newPromotor->setType($typeReg);
$newPromotor->setCompany($companyReg);
$newPromotor->setIdPromotor($newUser);
$em->persist($newUser);
$em->persist($newPromotor);
$em->persist($lead);
$em->flush();
//return $response;
}
$em->persist($lead);
$em->flush();
return $this->redirect($this->generateUrl('CASEventBundle_create'));
}
}
return $this->render($template, array('form' => $form->createView()));
}
}
you could just create a confirmation token yourself and set it to the not yet active user, send him a mail using swift wich contains a link to confirm like :
$confiToken = "123";
$url="http://url.com/confirm/$confiToken";
$user->setConfirmationToken($confiToken);
$message = $mailer->createMessage()
->setSubject('Confirm registration')
->setFrom('from#mail.com')
->setTo($sendTo)
->setBody(
$this->renderView(
'Bundle:Email:confirm.html.twig',
array(
'headline' => "Confirm your registration",
"sendTo"=>$sendTo,
"name"=>false,
"date"=>$date,
"message"=>"here ist your confirmationlink ".$url." "
)
),
'text/html'
);
$mailer->send($message);
when the user clicks the link in the email you can manually generate the token and set the user active:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
...
$user=$em->getRepository("Bundle:User")->findOneByConfirmationToken($token);
if(!$user || $user->isEnabled()){
throw $this->createNotFoundException("link out of date");
}else {
$user->setEnabled(true);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
$em->flush();
return $this->redirect($this->generateUrl('core_customer_dashboard'));
}
I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');
how to get function return value without execute it again?
i used this but this execute function again
my function:
function article()
{
if($_GET['action'] == "article" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$article = array();
$selectArticle = mysql_query("SELECT * FROM articles WHERE id='$id'");
$rowArticle = mysql_fetch_array($selectArticle);
$id = $rowArticle['id'];
$title = stripcslashes($rowArticle['title']);
$category = stripcslashes($rowArticle['category']);
$image = stripcslashes($rowArticle['image']);
$description = stripcslashes($rowArticle['description']);
$full_description = stripcslashes($rowArticle['full_description']);
$keywords = stripcslashes($rowArticle['keywords']);
$url = "/article/" . $rowArticle['id'] . "/" . str_replace(" ","-",stripcslashes($rowArticle['title']));
$article = array('id' => $id, 'title' => $title, 'category' => $category, 'image' => $image, 'description' => $description, 'full_description' => $full_description, 'keywords' => $keywords, 'url' => $url);
mysql_query("UPDATE articles SET visits=visits+1 WHERE id='$id'");
}
return $article;
}
how to check it
if (article() != null)
{
$article = article();
return $article['title'];
}
This should do what you want
if (null !== ($article = article())) {
return $article['title'];
}
This does a 'simultaneous' assignment AND comparison.
First, this part is evaluated: ($article = article()). It yields a null value or an array which is stored in $article.
Its result (null or array) is then evaluated by the if structure: if (null !== $article) and normal flow resumes.
like so
$article_var = article();
if ($article_var!=null)
{
//do stuff
//return $article['title'] // etc
}
Modify the check a little bit.
$article = article();
return $article != null ? $article['title'] : null;