A simple question:
I have one form, it returns one number and I need create this number of labels in Controller.
I try:
$form2 = $this->createFormBuilder();
for($i = 0; $i < $num; $i++) {
$name = 'column'.$i;
$form2->add($name,'number');
}
$form2->getForm();
I think it should very simple, but i can't..
Yes, you can do it with an array / hash map instead of a real object.
Here is an example :
// Create the array
$dataObj = array();
$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';
// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
$fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
$formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();
// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
$form->bind($request); // For symfony 2.1.x
// $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
if($form->isValid())
{
$dataObj = $form->getData();
foreach($dataObj as $key => $val)
{
echo $key . ' = ' . $val . '<br />';
}
exit('Done');
}
}
// Render
return $this->render('Aaa:Bbb:ccc.html.twig', array(
'requestForm' => $form->createView()));
Related
I am trying to upload my user_login from database into acf select field, in var_dump my array result is working good, but nothing uploaded in my acf select field?
1. I added a custom field "ACF select field" in a product post.
2. I'm trying to load my options values from my database.
3. I used an array to get the user_login values from the database
function.php
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
$field = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field, ($choices[$i]->user_login));
}
}
// var_dump($field);
// exit;
return $field;
}
this is the var_dump result
array(5) {
[0]=> string(5) "Ahmed"
[1]=> string(5) "Khedr"
[2]=> string(4) "meme"
[3]=> string(5) "Menna"
[4]=> string(7) "mustafa" }
this is the array result that i want to load in acf field
i found it
this is the new code
thanks justkidding96
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
//$choices = get_field($field['choices'], $post->ID , false);
$field['choices'] = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field['choices'], ($choices[$i]->user_login));
}
}
// var_dump($field['choices']);
// exit;
return $field;
Your don’t assign your choices to the field. Try this code:
if (is_array($choices)) {
// Clear the choices
$field[‘choices’] = [];
// Assign the data to the field
foreach ($choices as $choice) {
$field[‘choices’][$choice->user_login] = $choice->user_login;
}
}
I have a small password encryption problem ^^
in my database the passwords are present, and have to present, in this form:
VwBybV5ATQ9RkdvvVZNOlldEEDU9tDjttju7t8l+HeVe4nskHeMpbuCoQsqqORUQKZ1pg7gGtFocpkSIw8N9kA==
and right now I have a function that needs to generate a password for me. Unfortunately the encryption is not good, because that's what I get:
YmY1NzFkM2VkODYwOGQ1OWFlMTRiZDVkOTc3ZDFkNzQ0ODIzN2U5NWMzNzU0ZjI1Y2U4MTZhYzBiYmExYWJjZTg2Y2JjNzYyM2QwYTJmMDUwYWJiMzQxMjliYjBjYWQxMGZiMzliYzk3OGQwZjYxMGU3Y2E0NjE0ZTkxYzFiYmM=
my code :
public function lostpasswordAction(Request $request)
{
$success = '';
$string = '';
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$max = strlen($characters) - 1;
for ($i = 0; $i < 12; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
if ($request->request->get('email') !== null) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationSonataUserBundle:User')->findByEmail($request->request->get('email'));
if (is_null($user)) {
$response = new JsonResponse('Not Found');
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
$login = $user[0]->getEmail();
$password = $string;
$user[0]->setPassword(hash('sha512',$password));
$em->persist($user[0]);
$em->flush();
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom('no-reply#noreply.com')
->setTo($request->request->get('email'))
->setBody(
$this->renderView(
'emails/lostpassword.txt.twig',
array(
'login' => $login,
'password' => $password
)
),
'text/plain'
);
$return = $this->get('mailer')->send($message);
$success = 'Email sent';
return new JsonResponse($success);
}
$response = new JsonResponse('POST only');
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
return $response;
}
Can someone help me so I get the right shape please?
Thank you in advance
I'm using the bundle "JMSSerializerBundle" for export retrieved entity data. I can export the results as json, xml or yml successfully.
But i need also a csv export for this results. This bundle can't handle csv export. But i'm also not sure how can i convert json,xml or yml to csv, because csv is a flat file.
Have anyone solve this issue before?
Update
Now i create an solution for my problem, i'm partially satisfied with my solution, because it is not recursive. I will show it.
if ($format == 'csv') {
$json = $serializer->serialize($query, 'json', SerializationContext::create()->enableMaxDepthChecks());
return $this->toCsv(json_decode($json, true));
}
/**
* #todo write an recursive function for deeper levels
*
* #param $data
* #return array
*/
protected function toCsv($data)
{
$headers = array();
$outerCounter = 0;
foreach ($data as $key => $value) {
foreach ($value as $i => $j) {
if (!is_array($j)) {
$headers[] = $i;
$result[$outerCounter][$i] = $j;
} else {
foreach ($j as $k => $m) {
if (!is_array($m)) {
$headers[] = $i. '_'.$k;
$result[$outerCounter][$i. '_'.$k] = $m;
} else {
foreach ($m as $n => $l) {
if (!is_array($l)) {
$headers[] = $i.'_'.$k.'_'.$n;
$result[$outerCounter][$i.'_'.$k.'_'.$n] = $l;
}
}
}
}
}
}
$outerCounter++;
}
asort($headers);
$headers = array_unique($headers);
return array('headers' => $headers, 'data' => $result);
}
I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.
I need to have an option on my search page which will allow the users to select the number of results that they want to display in the view i.e 25 results, 50 , 100 results per page. My theme_pager code is
function theme_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
$tags = array("", "< prev", "", "next >", "");
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$ pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// first is the first page listed by this pager piece (re quantity)
$pager_first = $pager_current - $pager_middle + 1;
// last is the last page listed by this pager piece (re quantity)
$pager_last = $pager_current + $quantity - $pager_middle;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
// Prepare for generation loop.
$i = $pager_first;
if ($pager_last > $pager_max) {
// Adjust "center" if at end of query.
$i = $i + ($pager_max - $pager_last);
$pager_last = $pager_max;
}
if ($i <= 0) {
// Adjust "center" if at start of query.
$pager_last = $pager_last + (1 - $i);
$i = 1;
}
// End of generation loop preparation.
$view = views_get_current_view();
// ensure view exists
if (!$view) return;
// set object property to return total rows
$view->get_total_rows = true;
// set display_id
$view->set_display($display_id);
// execute view
$view->execute();
// acquire data from views object and $_REQUEST
$itemsPerPage = $view->pager['items_per_page'];
$currentPage = $_REQUEST['page']+1;
$total = $view->total_rows;
// start calculation
$start = ($itemsPerPage * $currentPage) - ($itemsPerPage-1);
$end = $itemsPerPage * $currentPage;
if ($end>$total) $end = $total;
// return html
$x = "<b>Displaying $start - $end of $total</b>";
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('‹ previous')), $limit, $element, 1, $parameters);
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('next ›')), $limit, $element, 1, $parameters);
if ($pager_total[$element] > 1) {
$items[] = array(
'class' => 'pager',
'data' => $x,
);
if ($li_previous) {
$items[] = array(
'class' => 'pager-previous',
'data' => $li_previous,
);
}
// When there is more than one page, create the pager list.
if ($i != $pager_max) {
// Now generate the actual pager piece.
for (; $i <= $pager_last && $i <= $pager_max; $i++) {
if ($i < $pager_current) {
if ($pager_first > 1 && $i == $pager_first) {
$output = '...'.$i;
$stopPreEllipsis = true;
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_previous', $output, $limit, $element, ($pager_current - $i), $parameters),
);
}
if ($i == $pager_current) {
$items[] = array(
'class' => 'pager-current',
'data' => $i,
);
}
if ($i > $pager_current) {
if ($pager_last < $pager_max && $i == $pager_last) {
$output = $i.'...';
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_next', $output, $limit, $element, ($i - $pager_current), $parameters),
);
}
}
}
// End generation.
if ($li_next) {
$items[] = array(
'class' => 'pager-next',
'data' => $li_next,
);
}
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
As you might have noticed, theme_pager does not call the database, it merely presents the items from the database. It does not even render the items in the list that is paged.
You will therefore need to override the amount before it gets passed into pager_query(). With views, I have no idea. In a custom module it would be really simple: read out an url parameter or POSTed variable and pass that along as second parameter into pager_query(). I suspect views has some hook to override the amount-per-page in runtime, just before it gets passed to the query-builder. But due to the poor documentation of views, it is not easily found.