How to use select query for creating form in drupal 8? - drupal-modules

I have a table in my database. I want to use the data of that table and create form of that data. I created a module and made a form.php page. Wrote select query in function but how to make form from that data?

I believe you want to create listing page of the table data. Here is how you can create a tabular listing with pagination and column sorting.
Suppose you have a table named "students" with the below fields.
id, name, email
1. Create a controller in your module in the below path.
modules/your_module/Src/Controller/StudentsController.php
<?php
namespace Drupal\your_module\Controller;
use Drupal\Core\Controller\ControllerBase;
class StudentsController extends ControllerBase {
public function __construct() {
}
public function list() {
$header = array(
array('data' => t('ID'), 'field' => 'st.id'),
array('data' => t('Name'), 'field' => 'st.name'),
array('data' => t('Email'), 'field' => 'st.email'),
);
$query = db_select('students', 'st')
->fields('st', array('id', 'name', 'email'))
->extend('Drupal\Core\Database\Query\TableSortExtender')
->extend('Drupal\Core\Database\Query\PagerSelectExtender')
->orderByHeader($header);
$data = $query->execute();
$rows = array();
foreach ($data as $row) {
$rows[] = array('data' => (array) $row);
}
$build['table_pager'][] = array(
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
);
$build['table_pager'][] = array(
'#type' => 'pager',
);
return $build;
}
}
So your controller action is ready, now you have to add routing in order to create path to this listing page.
2. Create routing.yml file inside your module folder as the file name mentioned below, and the code below.
modules/your_module/your_module.routing.yml
students.list:
path: 'admin/config/students/list'
defaults:
_controller: 'Drupal\your_module\Controller\StudentsController::list'
_title: 'Students List'
requirements:
_permission: 'access students list'
3. To create permissions, you can create the followin ing file in your module.
modules/your_module/your_module.permissions.yml
access students list:
title: 'Access students list page'
Clear CMS cache
Go to People => Permissions, Enable the permission for relevant user roles.
Then, browse your page "admin/config/students/list"

Related

Adding WooCommerce Attribute via PHP code

I could see a lots of question on adding woocommerce product attribute. But doing so, I could see those added attributes in this screen
wp-admin/edit.php?post_type=product&page=product_attributes
My question is how can we add the attributes via PHP code to so that it appears in this above specified woocommerce attribute screen ? My intention is to make these attributes visible under 'Layered Navs' widget to filter out.
Following code will create the attribute programmatically which will be visible on the product_attributes page in the backend.
global $wpdb;
$insert = $wpdb->insert(
$wpdb->prefix . 'woocommerce_attribute_taxonomies',
array(
'attribute_label' => 'name',
'attribute_name' => 'slug',
'attribute_type' => 'type',
'attribute_orderby' => 'order_by',
'attribute_public' => 1
),
array( '%s', '%s', '%s', '%s', '%d' )
);
if ( is_wp_error( $insert ) ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 );
}
// Clear transients
delete_transient( 'wc_attribute_taxonomies' );
Change name, slug etc with the relevant values.

Magento - custom product option don't show in order

I'm try to add custom option to product programmatically whyle add him to cart. I'm use:
$a_options = array(
'options' => array(
'label' => 'Glove Size',
'value' => $attr_value ,
)
);
$item->addOption(new Varien_Object(
array(
'product' => $item->getProduct(),
'code' => 'additional_options',
'value' => serialize($a_options)
)
));
$quote->addItem($item);
This is shows option for product in cart and during checkout process, but don't show option in order information.
I also tried:
$item->getProduct()->addCustomOption('additional_options', $attr_value );
Try to show them via attributes - didn't help.
$params = array('product' => '1919','qty' => 1,
'options' => array(
'glove_size' => $gloves_id,
),);
$cart->addProduct('1919', $params);
Magento version is 1.5
I haven't check that in 1.5 version but the below code will work in 1.7.2 version:
For viewing the custom options you need set options in order items.That can be done through by calling an event sales_convert_quote_item_to_order_item
<sales_convert_quote_item_to_order_item>
<observers>
<jrb_setcustomoption_observer>
<type>singleton</type>
<class>jrb_setcustomoption/observer</class>
<method>salesConvertQuoteItemToOrderItem</method>
</jrb_setcustomoption_observer>
</observers>
</sales_convert_quote_item_to_order_item>
Set the details options in your observer
public function salesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
$quoteItem = $observer->getItem();
if ($additionalOptions = $quoteItem->getOptionByCode('additional_options')) {
$orderItem = $observer->getOrderItem();
$options = $orderItem->getProductOptions();
$options['additional_options'] = unserialize($additionalOptions->getValue());
$orderItem->setProductOptions($options);
}
}
For More details you can find in this article:
Magento - custom product option don't show in order
Thanks to Vinai

how to sign up with different fields in kohana

The Model_Auth_User class in Kohana uses 'username', 'email','password' to create a new user
what if i want it to take only 'email', 'password' and also modify the validation to validate 'email_confirm' instead of 'password_confirm'
Finally i did it, All what I have to doe is to comment some lines which add the rules of validating user input
open C:\xampp\htdocs\kohana\modules\orm\classes\Model\Auth\User.php
and comment lines from 33:38 inclusive as following:
public function rules()
{
return array(
//as we don't have a username we don't need to validate it!
// 'username' => array(
// array('not_empty'),
// array('max_length', array(':value', 32)),
// array(array($this, 'unique'), array('username', ':value')),
// ),
'password' => array(
array('not_empty'),
),
'email' => array(
array('not_empty'),
array('email'),
array(array($this, 'unique'), array('email', ':value')),
),
);
}
You only keep the rules for validating what you need
Avoid changing of the system folder contents. Otherwise your changes will be lost after the next upgrade.
The more correct approach is to override the validation rules.
In file application/classes/Model/user.php:
<?php
class Model_User extends Model_Auth_User
{
public function rules()
{
$rules = parent::rules();
unset($rules['username']);
return $rules;
}
}
?>

How to implement a pagination for a search module in Zend Framework 2?

I have a module Search in my ZF2 application. The user fills in a search form out and gets a list of courses.
Now I'm adding the pagination to the module. The paginator is basically working: I can retrieve data over it and the pagination is displayed correctly (pagelinks 1-7 for 70 found courses with the dafault setting 10 items per page).
But it's still not usable. When I click on a pagelink, the form POST data is lost. I know -- it cannot work the way, how I implemented it (see the code below). But I have no idea, how to do it correctly, in order to eep checking the form data and nonetheless be able to use pagination.
That is my code:
Table class Search\Model\CourseTable
class CourseTable {
...
// without pagination
// public function findAllByCriteria(CourseSearchInput $input) {
// with pagination
public function findAllByCriteria(CourseSearchInput $input, $pageNumber) {
...
$select = new Select();
$where = new Where();
$having = new Having();
...
// without pagination
// $resultSet = $this->tableGateway->selectWith($select);
// return $resultSet;
// with pagination
$adapter = new \MyNamespqce\Paginator\Adapter\DbSelect($select, $this->tableGateway->getAdapter());
$paginator = new \Zend\Paginator\Paginator($adapter);
$paginator->setCurrentPageNumber($pageNumber);
return $paginator;
}
...
}
Search\Controller\SearchController
class SearchController extends AbstractActionController {
public function searchCoursesAction() {
$form = $this->getServiceLocator()->get('Search\Form\CourseSearchForm');
$request = $this->getRequest();
if ($request->isPost()) {
$courseSearchInput = new CourseSearchInput();
$form->setInputFilter($courseSearchInput->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$courseSearchInput->exchangeArray($form->getData());
// without pagination
// $courses = $this->getCourseTable()->findAllByCriteria($courseSearchInput);
// with pagination
$page = $this->params()->fromRoute('page');
$paginator = $this->getCourseTable()->findAllByCriteria($courseSearchInput, $page);
} else {
$paginator = null;
}
} else {
$paginator = null;
}
return new ViewModel(array(
'form' => $form,
// without pagination
// 'courses' => $courses,
// with pagination
'paginator' => $paginator,
'cities' => ...
));
}
...
}
How to get it working?
I also have the same problem, and I have solved it. But this is not good way. May be the idea will help you.
I solved it as follow: (Search pagination for Zend tutorial album module)
I build two action in controller named "search" and "index".
Whenever the search form submitted, it always post the value to search action. Search action build the url with search parameters, and redirect to index to disply search result.
And when the pagination links clicked, then posted values are passed through url. So whenever index action ask for search parameters, it always get the values in same format.
I defined route as follows:
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id][/page/:page][/order_by/:order_by][/:order][/search_by/:search_by]',
'constraints' => array(
'action' => '(?!\bpage\b)(?!\border_by\b)(?!\bsearch_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',
),
),
),
There is a parameter named "search_by", which will keep all search parameters as a json string. This is the point, which is not good I know, but have not find any other way yet.
"Search" action build this string as -
public function searchAction()
{
$request = $this->getRequest();
$url = 'index';
if ($request->isPost()) {
$formdata = (array) $request->getPost();
$search_data = array();
foreach ($formdata as $key => $value) {
if ($key != 'submit') {
if (!empty($value)) {
$search_data[$key] = $value;
}
}
}
if (!empty($search_data)) {
$search_by = json_encode($search_data);
$url .= '/search_by/' . $search_by;
}
}
$this->redirect()->toUrl($url);
}
And next index action decode the string, do necessary action, and also send the json string to view.
public function indexAction() {
$searchform = new AlbumSearchForm();
$searchform->get('submit')->setValue('Search');
$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;
$select->order($order_by . ' ' . $order);
$search_by = $this->params()->fromRoute('search_by') ?
$this->params()->fromRoute('search_by') : '';
$where = new \Zend\Db\Sql\Where();
$formdata = array();
if (!empty($search_by)) {
$formdata = (array) json_decode($search_by);
if (!empty($formdata['artist'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('artist', '%' . $formdata['artist'] . '%')
);
}
if (!empty($formdata['title'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('title', '%' . $formdata['title'] . '%')
);
}
}
if (!empty($where)) {
$select->where($where);
}
$album = $this->getAlbumTable()->fetchAll($select);
$totalRecord = $album->count();
$itemsPerPage = 2;
$album->current();
$paginator = new Paginator(new paginatorIterator($album));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage($itemsPerPage)
->setPageRange(7);
$searchform->setData($formdata);
return new ViewModel(array(
'search_by' => $search_by,
'order_by' => $order_by,
'order' => $order,
'page' => $page,
'paginator' => $paginator,
'pageAction' => 'album',
'form' => $searchform,
'totalRecord' => $totalRecord
));
}
All the sorting and paging url contain that string.
If you know all the searching paarameters before, then you can define that at route, and pass like the same way without json string. As I have to build a common search, I have build a single string.
Source code for "Album search" is available in git hub at https://github.com/tahmina8765/zf2_search_with_pagination_example.
Live Demo: http://zf2pagination.lifencolor.com/public/album
#Sam & #automatix in the question comments are both right. My suggestion (though I'm looking for a simpler alternative) is to construct a segment route, which covers all of the options that you're likely to need and start with a standard form POST request.
Then, after the request is validated, pass the form data to the paginationControl helper as follows:
$resultsView = new ViewModel(array(
'paginator' => $paginator,
'routeParams' => array_filter($form->getData())
));
Then, in your view template, set the route parameters in the paginationControl view helper:
<?php echo $this->paginationControl($paginator, 'Sliding', 'paginator/default',
array('routeParams' => $routeParams)
) ?>
I've used array_filter here because it's a really simple way of removing any element from the form data that's null, empty or so on. That way you don't pass in extra data that you don't need.

Search through related model in Yii

I have a problem with searching in Yii. I have two models: Teams and Workers. On website there is a page called 'Team Workers' where I want to display CGridView widget with searching that displays Workers from the team (team id is passed as a _GET parameter).
I did this in TeamsController:
public function actionWorkers($id)
{
$model = Teams::model()->findByPk($id);
$workers = Workers::model();
$workers->unsetAttributes();
if(isset($_GET['Workers']))
{
$_GET['Workers']['idTeam'] = $id;
$workers->attributes = $_GET['Workers'];
}
else {
$workers->attributes = array('idTeam' => $id);
}
$teamWorkers = $workers;
$this->render('workers', array(
'model' => $model,
'teamWorkers' => $teamWorkers
));
}
And in the view file:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'team-workers-grid',
'dataProvider'=>$teamWorkers->search(),
'filter' => $teamWorkers,
'columns'=>array(
'name',
'surname',
array(
'id' => 'idWorker',
'class' => 'CCheckBoxColumn',
'checked' => '$data->confirmer',
'selectableRows' => '2',
// 'headerTemplate' => '{item}'
)
),
)); ?>
I got the error:
CDbCommand nie zdołał wykonać instrukcji SQL: SQLSTATE[23000]: Integrity constraint
violation: 1052 Column 'idTeam' in where clause is ambiguous. The SQL statement
executed was: SELECT COUNT(DISTINCT `t`.`idWorker`) FROM `workers` `t` LEFT OUTER JOIN
`teams` `Team` ON (`t`.`idTeam`=`Team`.`idTeam`) WHERE ((idTeam=:ycp0) AND (Team.name
LIKE :ycp1))
When I dont set idTeam attribute - it works fine. It's pretty weird - at the regular CRUD admin page - idTeam attribute is passed and that works fine.
Hot to deal with it?
In Workers::search() you have something like
$criteria->compare('idTeam',$this->idTeam);
Change it to
$criteria->compare('t.idTeam',$this->idTeam);
i.e prefix sql attribute with t. if it is from current model or with relation name if from other table/model
Also instead of:
$workers->attributes = array('idTeam' => $id);
yould could keep it simpler with:
$workers->idTeam = $id;
You have defined the column idTeam in Team and Workers. By joining those tables you would have a duplicate ("ambiguous") column in the result. That's what the error message tells you.
To solve this you have to use an alias for one of the columns.

Resources