Drupal render() - make printed content ucfirst - php

I have a drupal template that renders some content like this:
<?php $field_collection_state_info = reset($content['field_state_information']['0']['entity']['field_collection_item']); ?>
<?php print render($field_collection_state_info['field_state_name']); ?>
but I would like to run the php ucfirst() so all rendered content is capitalized on the first letter.
I tried this:
<?php print ucfirst(render($field_collection_state_info['field_state_name'])); ?>
But that didn't work.
How should I achieve this?
Any advise is very much appreciated.
C

I think you will have to change the content of your render array before calling render():
// the 'und' part is depending on the translation of the node
$field_collection_state_info['field_state_name']['und'][0]['value'] =
ucfirst($field_collection_state_info['field_state_name']['und'][0]['value']);
// render
print render($field_collection_state_info['field_state_name']);
// or you could try to modify the safe_value part of the array depending on your
// filter settings for the field
$field_collection_state_info['field_state_name']['und'][0]['safe_value'] =
ucfirst($field_collection_state_info['field_state_name']['und'][0]['safe_value']);
// render
print render($field_collection_state_info['field_state_name']);
EDIT Try adding this into your template.php, it changes the value for a collection_field using hook_preprocess_node():
function YOURTHEME_preprocess_node(&$vars) {
if($vars['type'] == 'YOUR-CONTENT-TYPE') {
// you might need to replace the field_content_block with the name of your field <field_state_information>
$data = reset($vars['content']['field_content_block'][0]['entity']['field_collection_item']);
// turn the first character to uppercase
$data['field_text']['#object']->field_text['und'][0]['value'] = ucwords($data['field_text']['#object']->field_text['und'][0]['value']);
// set the data in the array, like I said above your might need to change the `field_collection_block` to `field_state_information`
$vars['content']['field_content_block'][0]['entity']['field_collection_item'] = $data;
}
}

Related

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

About sql and str_replace function

First of all, thanks to everyone for helping me, and please apologize my English, I'm trying to do the best :)
This is what I wanna do:
I have a table in MySQL database, named acciones, I want to every "action" registered in that table make a replace in the text printed on screen:
<?php
include('../procesos/abre_conexion.php');
$query99 = "SELECT * from acciones";
// This line make the query
$result99 = mysql_query($query99);
$registro99 = mysql_fetch_array($result99)
?>
<?php
// create the function
function howls($valor) {
// set the variable // saving as array // possible texts
$variables = array('$registro99[original]',);
// $imagenes, tambien contendra un array
// with the replace text
$sus = array('$registro99[reemplazo]',);
// making the replace
return (str_replace($variables, $sus, $valor));
}
// starting function
ob_start("howls");
?>
#SalirA beber Cerveza Montoro en barrio santo con Andreita.
<?php
// ending function
ob_end_flush();
?>
<? include('../procesos/cierra_conexion.php'); ?>
But it don't works, any suggestion?
Firstly, you should NOT be using the mysql_* functions. They are deprecated and completely removed from PHP7.
As to what is happening with your code. You shouldn't single quote the $registro variables. If you do need them quoted for some reason, you need to double-quote them.
function howls($valor) {
// set the variable // saving as array // possible texts
$variables = array("{$registro99[original]}",);
// $imagenes, tambien contendra un array
// with the replace text
$sus = array("{$registro99[reemplazo]}",);
// making the replace
return (str_replace($variables, $sus, $valor));
}

PHP replace {replace_me} with <?php include ?> in output buffer

I have a file like this
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
Everything inside the buffer is dynamically made with data from the database.
And inserting php into the database is not an option.
The issue is, I got my output buffer and i want to replace '{replace}' with a working php include, which includes a file that also has some html/php.
So my actual question is: How do i replace a string with working php-code in a output-buffer?
I hope you can help, have used way to much time on this.
Best regards - user2453885
EDIT - 25/11/14
I know wordpress or joomla is using some similar functions, you can write {rate} in your post, and it replaces it with a rating system(some rate-plugin). This is the secret knowledge I desire.
You can use preg_replace_callback and let the callback include the file you want to include and return the output. Or you could replace the placeholders with textual includes, save that as a file and include that file (sort of compile the thing)
For simple text you could do explode (though it's probably not the most efficient for large blocks of text):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
I might be misunderstanding something here, but something simple like this might work?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
You can also use a return statement from within an include file if you wish to remove the output buffer from that task too.
Good luck!
Ty all for some lovely input.
I will try and anwser my own question as clear as I can.
problem: I first thought that I wanted to implement a php-function or include inside a buffer. This however is not what I wanted, and is not intended.
Solution: Callback function with my desired content. By using the function preg_replace_callback(), I could find the text I wanted to replace in my buffer and then replace it with whatever the callback(function) would return.
The callback then included the necessary files/.classes and used the functions with written content in it.
Tell me if you did not understand, or want to elaborate/tell more about my solution.

Executing a PHP page after search + replacing keywords for language translation in the HTML

I am translating my website into different languages and I have over 130 pages so i want to pass my .php files through a function that will replace keywords
IE: Accessories = อุปกรณ์
Which is English to Thai.
I can get it to work using my method however... I have php (obviously) in these pages, and the output only displays the html and not executing the php
Is there a header method or something I have to pass at the start of my php pages..
here is the function I'm using to find text results and then replace them from my php files..
<?php
// lang.php
function get_lang($file)
{
// Include a language file
include 'lang_thai.php';
// Get the data from the HTML
$html = file_get_contents($file);
// Create an empty array for the language variables
$vars = array();
// Scroll through each variable
foreach($lang as $key => $value)
{
// Finds the array results in my lang_thai.php file (listed below)
$vars[$key] = $value;
}
// Finally convert the strings
$html = strtr($html, $vars);
// Return the data
echo $html;
}
?>
//This is the lang_thai.php file
<?php
$lang = array(
'Hot Items' => 'รายการสินค้า',
'Accessories' => 'อุปกรณ์'
);
?>
A lot of frameworks use a function to translate as it goes instead of replacing after the fact using .pot files. The function would look like this:
<h1><?php echo _('Hello, World') ?>!</h1>
So if it was English and not translated that function would just return the string untranslated. If it was to be translated then it would return the translated string.
If you want to continue with your route which is definitely faster to implement try this:
<?php
function translate($buffer) {
$translation = include ('lang_tai.php');
$keys = array_keys($translation);
$vals = array_values($translation);
return str_replace($keys, $vals, $buffer);
}
ob_start('translate');
// ... all of your html stuff
Your language file is:
<?php
return array(
'Hot Items' => 'รายการสินค้า',
'Accessories' => 'อุปกรณ์'
);
One cool thing is include can return values! So this is a good way to pass values from a file. Also the ob_start is an output buffer with a callback. So what happens is after you echo all of your html to the screen, right before it actually displays to the screen it passes all of that data to the translate function and we then translate all of the data!

How can I use node_load and render contextual links

I have an array of node IDs with which loop through and run node_load($nid) to retrieve the data for each of those nodes. Take for example the below code- that's roughly how it works at the moment.
foreach( $node->field_flights['und'] as $flight ):
$flightNode = node_load($flight['nid']);
echo $flightNode->title;
What I want to achieve is to load the node, then be able to do something along the lines of echo render($flightNode); so that it loads the template file for that node and I can render the $title_suffix variable in the node template which has been loaded.
I've tried the following to no avail. Nothing is output at all.
$flightNode = node_load($flight['nid']);
$builtFlightNode = node_build_content( $flightNode );
echo render( $builtFlightNode );
Would anyone provide some insight?
You can use node_view() to prepare the render array. For performance it might be wise to consider using node_load_multiple() (and it's counterpart node_view_multiple()) like this:
$nids = array();
foreach($node->field_flights['und'] as $flight):
$nids[] = $flight['nid'];
endforeach;
$flight_nodes = node_load_multiple($nids);
$view_mode = 'teaser'; // could also be 'full'
$views = node_view_multiple($flight_nodes, $view_mode);
// Renders all nodes in one go
echo render($views);
If that doesn't fit in with what you're doing though this should work on a node by node basis:
foreach($node->field_flights['und'] as $flight):
$flight_node = node_load($flight['nid']);
$view = node_view($flight_node, $view_mode);
echo render($view);
endforeach;
If you need to modify the content before it's rendered, you can just step through the $views or $view arrays and change what you need to before running it through render(). If you just want a particular part of the node content rendered, again just step through the array and apply render to the particular sub-array you're interested in.

Categories